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
34,178
[Bug]: Chrome Extension V3 service_worker - Supported APIs do not function
### 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 13.6.9, 18.2.0, 20.0.0-nightly.20220505 ### What operating system are you using? macOS ### Operating System Version macOS Monterey 12.3.1 ### What arch are you using? x64 ### Last Known Working Electron version N/A ### Expected Behavior For successful messages to be sent to and from the Service Worker in the extension. The test case provided uses Electron's supported Chrome APIs as defined here: https://www.electronjs.org/docs/latest/api/extensions#loading-extensions - A content page is supplied by this extension which simply calls "chrome.runtime.sendMessage" to send a message. - A service worker is supplied by this extension which calls - "chrome.runtime.onInstalled" to print a logging statement - "chrome.runtime.onMessage.addListener" to listen for messages, and to send a response. Expected to see the log message show up on any web page: `I'm a content script, and I'm going to try to send a message to anyone that is listening.` `Hello sender, I received your message.` With the ELECTRON_ENABLE_LOGGING=1 env set, expected to see: `[xxx:INFO:CONSOLE(1)] "Hello, I'm a service worker", source: chrome-extension:///<some_chrome_extension_id>/background.js` `[xxx:INFO:CONSOLE(1)] "Hello, I was just installed.", source: chrome-extension:///<some_chrome_extension_id>/background.js` `[xxx:INFO:CONSOLE(1)] "Hello, I'm a service worker and I just received a message.", source: chrome-extension:///<some_chrome_extension_id>/background.js` ### Actual Behavior Actual logs seen on any web page: `I'm a content script, and I'm going to try to send a message to anyone that is listening.` Actual logs seen in terminal: With the ELECTRON_ENABLE_LOGGING=1 env set, expected to see: `[xxx:INFO:CONSOLE(1)] "Hello, I'm a service worker", source: chrome-extension:///<some_chrome_extension_id>/background.js` ### Testcase Gist URL https://gist.github.com/schetle/8ea7451215b89c4cc28506f96e9f384a ### Additional Information By January of this upcoming year, Manifest V2 extensions will cease to function (please see: https://developer.chrome.com/docs/extensions/mv3/mv2-sunset/) Part of the migration process to get from a V2 -> V3 extension requires that background pages are replaced with service workers (please see: https://developer.chrome.com/docs/extensions/mv3/intro/mv3-migration/#background-service-workers)
https://github.com/electron/electron/issues/34178
https://github.com/electron/electron/pull/39290
b2c62d6ad1fb0745544a20c85abef312c7196d14
c8f7a0e0522b0527082a23438da11bf6f148825c
2022-05-11T16:10:16Z
c++
2023-08-01T06:04:38Z
spec/extensions-spec.ts
import { expect } from 'chai'; import { app, session, BrowserWindow, ipcMain, WebContents, Extension, Session } from 'electron/main'; import { closeAllWindows, closeWindow } from './lib/window-helpers'; import * as http from 'node:http'; import * as path from 'node:path'; import * as fs from 'node:fs'; import * as WebSocket from 'ws'; import { emittedNTimes, emittedUntil } from './lib/events-helpers'; import { ifit, listen } from './lib/spec-helpers'; import { once } from 'node:events'; const uuid = require('uuid'); const fixtures = path.join(__dirname, 'fixtures'); describe('chrome extensions', () => { const emptyPage = '<script>console.log("loaded")</script>'; // NB. extensions are only allowed on http://, https:// and ftp:// (!) urls by default. let server: http.Server; let url: string; let port: number; before(async () => { server = http.createServer((req, res) => { if (req.url === '/cors') { res.setHeader('Access-Control-Allow-Origin', 'http://example.com'); } res.end(emptyPage); }); const wss = new WebSocket.Server({ noServer: true }); wss.on('connection', function connection (ws) { ws.on('message', function incoming (message) { if (message === 'foo') { ws.send('bar'); } }); }); ({ port, url } = await listen(server)); }); after(() => { server.close(); }); afterEach(closeAllWindows); afterEach(() => { session.defaultSession.getAllExtensions().forEach((e: any) => { session.defaultSession.removeExtension(e.id); }); }); it('does not crash when using chrome.management', async () => { const customSession = session.fromPartition(`persist:${require('uuid').v4()}`); const w = new BrowserWindow({ show: false, webPreferences: { session: customSession, sandbox: true } }); await w.loadURL('about:blank'); const promise = once(app, 'web-contents-created') as Promise<[any, WebContents]>; await customSession.loadExtension(path.join(fixtures, 'extensions', 'persistent-background-page')); const args: any = await promise; const wc: Electron.WebContents = args[1]; await expect(wc.executeJavaScript(` (() => { return new Promise((resolve) => { chrome.management.getSelf((info) => { resolve(info); }); }) })(); `)).to.eventually.have.property('id'); }); it('can open WebSQLDatabase in a background page', async () => { const customSession = session.fromPartition(`persist:${require('uuid').v4()}`); const w = new BrowserWindow({ show: false, webPreferences: { session: customSession, sandbox: true } }); await w.loadURL('about:blank'); const promise = once(app, 'web-contents-created') as Promise<[any, WebContents]>; await customSession.loadExtension(path.join(fixtures, 'extensions', 'persistent-background-page')); const args: any = await promise; const wc: Electron.WebContents = args[1]; await expect(wc.executeJavaScript('(()=>{try{openDatabase("t", "1.0", "test", 2e5);return true;}catch(e){throw e}})()')).to.not.be.rejected(); }); function fetch (contents: WebContents, url: string) { return contents.executeJavaScript(`fetch(${JSON.stringify(url)})`); } it('bypasses CORS in requests made from extensions', async () => { const customSession = session.fromPartition(`persist:${require('uuid').v4()}`); const w = new BrowserWindow({ show: false, webPreferences: { session: customSession, sandbox: true } }); const extension = await customSession.loadExtension(path.join(fixtures, 'extensions', 'ui-page')); await w.loadURL(`${extension.url}bare-page.html`); await expect(fetch(w.webContents, `${url}/cors`)).to.not.be.rejectedWith(TypeError); }); it('loads an extension', async () => { // NB. we have to use a persist: session (i.e. non-OTR) because the // extension registry is redirected to the main session. so installing an // extension in an in-memory session results in it being installed in the // default session. const customSession = session.fromPartition(`persist:${uuid.v4()}`); await customSession.loadExtension(path.join(fixtures, 'extensions', 'red-bg')); const w = new BrowserWindow({ show: false, webPreferences: { session: customSession } }); await w.loadURL(url); const bg = await w.webContents.executeJavaScript('document.documentElement.style.backgroundColor'); expect(bg).to.equal('red'); }); it('does not crash when loading an extension with missing manifest', async () => { const customSession = session.fromPartition(`persist:${uuid.v4()}`); const promise = customSession.loadExtension(path.join(fixtures, 'extensions', 'missing-manifest')); await expect(promise).to.eventually.be.rejectedWith(/Manifest file is missing or unreadable/); }); it('does not crash when failing to load an extension', async () => { const customSession = session.fromPartition(`persist:${uuid.v4()}`); const promise = customSession.loadExtension(path.join(fixtures, 'extensions', 'load-error')); await expect(promise).to.eventually.be.rejected(); }); it('serializes a loaded extension', async () => { const extensionPath = path.join(fixtures, 'extensions', 'red-bg'); const manifest = JSON.parse(fs.readFileSync(path.join(extensionPath, 'manifest.json'), 'utf-8')); const customSession = session.fromPartition(`persist:${uuid.v4()}`); const extension = await customSession.loadExtension(extensionPath); expect(extension.id).to.be.a('string'); expect(extension.name).to.be.a('string'); expect(extension.path).to.be.a('string'); expect(extension.version).to.be.a('string'); expect(extension.url).to.be.a('string'); expect(extension.manifest).to.deep.equal(manifest); }); it('removes an extension', async () => { const customSession = session.fromPartition(`persist:${uuid.v4()}`); const { id } = await customSession.loadExtension(path.join(fixtures, 'extensions', 'red-bg')); { const w = new BrowserWindow({ show: false, webPreferences: { session: customSession } }); await w.loadURL(url); const bg = await w.webContents.executeJavaScript('document.documentElement.style.backgroundColor'); expect(bg).to.equal('red'); } customSession.removeExtension(id); { const w = new BrowserWindow({ show: false, webPreferences: { session: customSession } }); await w.loadURL(url); const bg = await w.webContents.executeJavaScript('document.documentElement.style.backgroundColor'); expect(bg).to.equal(''); } }); it('emits extension lifecycle events', async () => { const customSession = session.fromPartition(`persist:${require('uuid').v4()}`); const loadedPromise = once(customSession, 'extension-loaded'); const readyPromise = emittedUntil(customSession, 'extension-ready', (event: Event, extension: Extension) => { return extension.name !== 'Chromium PDF Viewer'; }); const extension = await customSession.loadExtension(path.join(fixtures, 'extensions', 'red-bg')); const [, loadedExtension] = await loadedPromise; const [, readyExtension] = await readyPromise; expect(loadedExtension).to.deep.equal(extension); expect(readyExtension).to.deep.equal(extension); const unloadedPromise = once(customSession, 'extension-unloaded'); await customSession.removeExtension(extension.id); const [, unloadedExtension] = await unloadedPromise; expect(unloadedExtension).to.deep.equal(extension); }); it('lists loaded extensions in getAllExtensions', async () => { const customSession = session.fromPartition(`persist:${uuid.v4()}`); const e = await customSession.loadExtension(path.join(fixtures, 'extensions', 'red-bg')); expect(customSession.getAllExtensions()).to.deep.equal([e]); customSession.removeExtension(e.id); expect(customSession.getAllExtensions()).to.deep.equal([]); }); it('gets an extension by id', async () => { const customSession = session.fromPartition(`persist:${uuid.v4()}`); const e = await customSession.loadExtension(path.join(fixtures, 'extensions', 'red-bg')); expect(customSession.getExtension(e.id)).to.deep.equal(e); }); it('confines an extension to the session it was loaded in', async () => { const customSession = session.fromPartition(`persist:${uuid.v4()}`); await customSession.loadExtension(path.join(fixtures, 'extensions', 'red-bg')); const w = new BrowserWindow({ show: false }); // not in the session await w.loadURL(url); const bg = await w.webContents.executeJavaScript('document.documentElement.style.backgroundColor'); expect(bg).to.equal(''); }); it('loading an extension in a temporary session throws an error', async () => { const customSession = session.fromPartition(uuid.v4()); await expect(customSession.loadExtension(path.join(fixtures, 'extensions', 'red-bg'))).to.eventually.be.rejectedWith('Extensions cannot be loaded in a temporary session'); }); describe('chrome.i18n', () => { let w: BrowserWindow; let extension: Extension; const exec = async (name: string) => { const p = once(ipcMain, 'success'); await w.webContents.executeJavaScript(`exec('${name}')`); const [, result] = await p; return result; }; beforeEach(async () => { const customSession = session.fromPartition(`persist:${uuid.v4()}`); extension = await customSession.loadExtension(path.join(fixtures, 'extensions', 'chrome-i18n')); w = new BrowserWindow({ show: false, webPreferences: { session: customSession, nodeIntegration: true, contextIsolation: false } }); await w.loadURL(url); }); it('getAcceptLanguages()', async () => { const result = await exec('getAcceptLanguages'); expect(result).to.be.an('array').and.deep.equal(['en-US', 'en']); }); it('getMessage()', async () => { const result = await exec('getMessage'); expect(result.id).to.be.a('string').and.equal(extension.id); expect(result.name).to.be.a('string').and.equal('chrome-i18n'); }); }); describe('chrome.runtime', () => { let w: BrowserWindow; const exec = async (name: string) => { const p = once(ipcMain, 'success'); await w.webContents.executeJavaScript(`exec('${name}')`); const [, result] = await p; return result; }; beforeEach(async () => { const customSession = session.fromPartition(`persist:${uuid.v4()}`); await customSession.loadExtension(path.join(fixtures, 'extensions', 'chrome-runtime')); w = new BrowserWindow({ show: false, webPreferences: { session: customSession, nodeIntegration: true, contextIsolation: false } }); await w.loadURL(url); }); it('getManifest()', async () => { const result = await exec('getManifest'); expect(result).to.be.an('object').with.property('name', 'chrome-runtime'); }); it('id', async () => { const result = await exec('id'); expect(result).to.be.a('string').with.lengthOf(32); }); it('getURL()', async () => { const result = await exec('getURL'); expect(result).to.be.a('string').and.match(/^chrome-extension:\/\/.*main.js$/); }); it('getPlatformInfo()', async () => { const result = await exec('getPlatformInfo'); expect(result).to.be.an('object'); expect(result.os).to.be.a('string'); expect(result.arch).to.be.a('string'); expect(result.nacl_arch).to.be.a('string'); }); }); describe('chrome.storage', () => { it('stores and retrieves a key', async () => { const customSession = session.fromPartition(`persist:${uuid.v4()}`); await customSession.loadExtension(path.join(fixtures, 'extensions', 'chrome-storage')); const w = new BrowserWindow({ show: false, webPreferences: { session: customSession, nodeIntegration: true, contextIsolation: false } }); try { const p = once(ipcMain, 'storage-success'); await w.loadURL(url); const [, v] = await p; expect(v).to.equal('value'); } finally { w.destroy(); } }); }); describe('chrome.webRequest', () => { function fetch (contents: WebContents, url: string) { return contents.executeJavaScript(`fetch(${JSON.stringify(url)})`); } let customSession: Session; let w: BrowserWindow; beforeEach(() => { customSession = session.fromPartition(`persist:${uuid.v4()}`); w = new BrowserWindow({ show: false, webPreferences: { session: customSession, sandbox: true, contextIsolation: true } }); }); describe('onBeforeRequest', () => { it('can cancel http requests', async () => { await w.loadURL(url); await customSession.loadExtension(path.join(fixtures, 'extensions', 'chrome-webRequest')); await expect(fetch(w.webContents, url)).to.eventually.be.rejectedWith('Failed to fetch'); }); it('does not cancel http requests when no extension loaded', async () => { await w.loadURL(url); await expect(fetch(w.webContents, url)).to.not.be.rejectedWith('Failed to fetch'); }); }); it('does not take precedence over Electron webRequest - http', async () => { return new Promise<void>((resolve) => { (async () => { customSession.webRequest.onBeforeRequest((details, callback) => { resolve(); callback({ cancel: true }); }); await w.loadURL(url); await customSession.loadExtension(path.join(fixtures, 'extensions', 'chrome-webRequest')); fetch(w.webContents, url); })(); }); }); it('does not take precedence over Electron webRequest - WebSocket', () => { return new Promise<void>((resolve) => { (async () => { customSession.webRequest.onBeforeSendHeaders(() => { resolve(); }); await w.loadFile(path.join(fixtures, 'api', 'webrequest.html'), { query: { port: `${port}` } }); await customSession.loadExtension(path.join(fixtures, 'extensions', 'chrome-webRequest-wss')); })(); }); }); describe('WebSocket', () => { it('can be proxied', async () => { await w.loadFile(path.join(fixtures, 'api', 'webrequest.html'), { query: { port: `${port}` } }); await customSession.loadExtension(path.join(fixtures, 'extensions', 'chrome-webRequest-wss')); customSession.webRequest.onSendHeaders((details) => { if (details.url.startsWith('ws://')) { expect(details.requestHeaders.foo).be.equal('bar'); } }); }); }); }); describe('chrome.tabs', () => { let customSession: Session; before(async () => { customSession = session.fromPartition(`persist:${uuid.v4()}`); await customSession.loadExtension(path.join(fixtures, 'extensions', 'chrome-api')); }); it('executeScript', async () => { const w = new BrowserWindow({ show: false, webPreferences: { session: customSession, nodeIntegration: true } }); await w.loadURL(url); const message = { method: 'executeScript', args: ['1 + 2'] }; w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`); const [,, responseString] = await once(w.webContents, 'console-message'); const response = JSON.parse(responseString); expect(response).to.equal(3); }); it('connect', async () => { const w = new BrowserWindow({ show: false, webPreferences: { session: customSession, nodeIntegration: true } }); await w.loadURL(url); const portName = uuid.v4(); const message = { method: 'connectTab', args: [portName] }; w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`); const [,, responseString] = await once(w.webContents, 'console-message'); const response = responseString.split(','); expect(response[0]).to.equal(portName); expect(response[1]).to.equal('howdy'); }); it('sendMessage receives the response', async () => { const w = new BrowserWindow({ show: false, webPreferences: { session: customSession, nodeIntegration: true } }); await w.loadURL(url); const message = { method: 'sendMessage', args: ['Hello World!'] }; w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`); const [,, responseString] = await once(w.webContents, 'console-message'); const response = JSON.parse(responseString); expect(response.message).to.equal('Hello World!'); expect(response.tabId).to.equal(w.webContents.id); }); it('update', async () => { const w = new BrowserWindow({ show: false, webPreferences: { session: customSession, nodeIntegration: true } }); await w.loadURL(url); const w2 = new BrowserWindow({ show: false, webPreferences: { session: customSession } }); await w2.loadURL('about:blank'); const w2Navigated = once(w2.webContents, 'did-navigate'); const message = { method: 'update', args: [w2.webContents.id, { url }] }; w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`); const [,, responseString] = await once(w.webContents, 'console-message'); const response = JSON.parse(responseString); await w2Navigated; expect(new URL(w2.getURL()).toString()).to.equal(new URL(url).toString()); expect(response.id).to.equal(w2.webContents.id); }); }); describe('background pages', () => { it('loads a lazy background page when sending a message', async () => { const customSession = session.fromPartition(`persist:${uuid.v4()}`); await customSession.loadExtension(path.join(fixtures, 'extensions', 'lazy-background-page')); const w = new BrowserWindow({ show: false, webPreferences: { session: customSession, nodeIntegration: true, contextIsolation: false } }); try { w.loadURL(url); const [, resp] = await once(ipcMain, 'bg-page-message-response'); expect(resp.message).to.deep.equal({ some: 'message' }); expect(resp.sender.id).to.be.a('string'); expect(resp.sender.origin).to.equal(url); expect(resp.sender.url).to.equal(url + '/'); } finally { w.destroy(); } }); it('can use extension.getBackgroundPage from a ui page', async () => { const customSession = session.fromPartition(`persist:${uuid.v4()}`); const { id } = await customSession.loadExtension(path.join(fixtures, 'extensions', 'lazy-background-page')); const w = new BrowserWindow({ show: false, webPreferences: { session: customSession } }); await w.loadURL(`chrome-extension://${id}/page-get-background.html`); const receivedMessage = await w.webContents.executeJavaScript('window.completionPromise'); expect(receivedMessage).to.deep.equal({ some: 'message' }); }); it('can use extension.getBackgroundPage from a ui page', async () => { const customSession = session.fromPartition(`persist:${uuid.v4()}`); const { id } = await customSession.loadExtension(path.join(fixtures, 'extensions', 'lazy-background-page')); const w = new BrowserWindow({ show: false, webPreferences: { session: customSession } }); await w.loadURL(`chrome-extension://${id}/page-get-background.html`); const receivedMessage = await w.webContents.executeJavaScript('window.completionPromise'); expect(receivedMessage).to.deep.equal({ some: 'message' }); }); it('can use runtime.getBackgroundPage from a ui page', async () => { const customSession = session.fromPartition(`persist:${uuid.v4()}`); const { id } = await customSession.loadExtension(path.join(fixtures, 'extensions', 'lazy-background-page')); const w = new BrowserWindow({ show: false, webPreferences: { session: customSession } }); await w.loadURL(`chrome-extension://${id}/page-runtime-get-background.html`); const receivedMessage = await w.webContents.executeJavaScript('window.completionPromise'); expect(receivedMessage).to.deep.equal({ some: 'message' }); }); it('has session in background page', async () => { const customSession = session.fromPartition(`persist:${require('uuid').v4()}`); const promise = once(app, 'web-contents-created') as Promise<[any, WebContents]>; const { id } = await customSession.loadExtension(path.join(fixtures, 'extensions', 'persistent-background-page')); const [, bgPageContents] = await promise; expect(bgPageContents.getType()).to.equal('backgroundPage'); await once(bgPageContents, 'did-finish-load'); expect(bgPageContents.getURL()).to.equal(`chrome-extension://${id}/_generated_background_page.html`); expect(bgPageContents.session).to.not.equal(undefined); }); it('can open devtools of background page', async () => { const customSession = session.fromPartition(`persist:${require('uuid').v4()}`); const promise = once(app, 'web-contents-created') as Promise<[any, WebContents]>; await customSession.loadExtension(path.join(fixtures, 'extensions', 'persistent-background-page')); const [, bgPageContents] = await promise; expect(bgPageContents.getType()).to.equal('backgroundPage'); bgPageContents.openDevTools(); bgPageContents.closeDevTools(); }); }); describe('devtools extensions', () => { let showPanelTimeoutId: any = null; afterEach(() => { if (showPanelTimeoutId) clearTimeout(showPanelTimeoutId); }); const showLastDevToolsPanel = (w: BrowserWindow) => { w.webContents.once('devtools-opened', () => { const show = () => { if (w == null || w.isDestroyed()) return; const { devToolsWebContents } = w as unknown as { devToolsWebContents: WebContents | undefined }; if (devToolsWebContents == null || devToolsWebContents.isDestroyed()) { return; } const showLastPanel = () => { // this is executed in the devtools context, where UI is a global const { UI } = (window as any); const tabs = UI.inspectorView.tabbedPane.tabs; const lastPanelId = tabs[tabs.length - 1].id; UI.inspectorView.showPanel(lastPanelId); }; devToolsWebContents.executeJavaScript(`(${showLastPanel})()`, false).then(() => { showPanelTimeoutId = setTimeout(show, 100); }); }; showPanelTimeoutId = setTimeout(show, 100); }); }; // TODO(jkleinsc) fix this flaky test on WOA ifit(process.platform !== 'win32' || process.arch !== 'arm64')('loads a devtools extension', async () => { const customSession = session.fromPartition(`persist:${uuid.v4()}`); customSession.loadExtension(path.join(fixtures, 'extensions', 'devtools-extension')); const winningMessage = once(ipcMain, 'winning'); const w = new BrowserWindow({ show: true, webPreferences: { session: customSession, nodeIntegration: true, contextIsolation: false } }); await w.loadURL(url); w.webContents.openDevTools(); showLastDevToolsPanel(w); await winningMessage; }); }); describe('chrome extension content scripts', () => { const fixtures = path.resolve(__dirname, 'fixtures'); const extensionPath = path.resolve(fixtures, 'extensions'); const addExtension = (name: string) => session.defaultSession.loadExtension(path.resolve(extensionPath, name)); const removeAllExtensions = () => { Object.keys(session.defaultSession.getAllExtensions()).map(extName => { session.defaultSession.removeExtension(extName); }); }; let responseIdCounter = 0; const executeJavaScriptInFrame = (webContents: WebContents, frameRoutingId: number, code: string) => { return new Promise(resolve => { const responseId = responseIdCounter++; ipcMain.once(`executeJavaScriptInFrame_${responseId}`, (event, result) => { resolve(result); }); webContents.send('executeJavaScriptInFrame', frameRoutingId, code, responseId); }); }; const generateTests = (sandboxEnabled: boolean, contextIsolationEnabled: boolean) => { describe(`with sandbox ${sandboxEnabled ? 'enabled' : 'disabled'} and context isolation ${contextIsolationEnabled ? 'enabled' : 'disabled'}`, () => { let w: BrowserWindow; describe('supports "run_at" option', () => { beforeEach(async () => { await closeWindow(w); w = new BrowserWindow({ show: false, width: 400, height: 400, webPreferences: { contextIsolation: contextIsolationEnabled, sandbox: sandboxEnabled } }); }); afterEach(async () => { removeAllExtensions(); await closeWindow(w); w = null as unknown as BrowserWindow; }); it('should run content script at document_start', async () => { await addExtension('content-script-document-start'); w.webContents.once('dom-ready', async () => { const result = await w.webContents.executeJavaScript('document.documentElement.style.backgroundColor'); expect(result).to.equal('red'); }); w.loadURL(url); }); it('should run content script at document_idle', async () => { await addExtension('content-script-document-idle'); w.loadURL(url); const result = await w.webContents.executeJavaScript('document.body.style.backgroundColor'); expect(result).to.equal('red'); }); it('should run content script at document_end', async () => { await addExtension('content-script-document-end'); w.webContents.once('did-finish-load', async () => { const result = await w.webContents.executeJavaScript('document.documentElement.style.backgroundColor'); expect(result).to.equal('red'); }); w.loadURL(url); }); }); describe('supports "all_frames" option', () => { const contentScript = path.resolve(fixtures, 'extensions/content-script'); const contentPath = path.join(contentScript, 'frame-with-frame.html'); // Computed style values const COLOR_RED = 'rgb(255, 0, 0)'; const COLOR_BLUE = 'rgb(0, 0, 255)'; const COLOR_TRANSPARENT = 'rgba(0, 0, 0, 0)'; let server: http.Server; let port: number; before(async () => { server = http.createServer((_, res) => { fs.readFile(contentPath, (error, content) => { if (error) { res.writeHead(500); res.end(`Failed to load ${contentPath} : ${error.code}`); } else { res.writeHead(200, { 'Content-Type': 'text/html' }); res.end(content, 'utf-8'); } }); }); ({ port, url } = await listen(server)); session.defaultSession.loadExtension(contentScript); }); after(() => { session.defaultSession.removeExtension('content-script-test'); }); beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { // enable content script injection in subframes nodeIntegrationInSubFrames: true, preload: path.join(contentScript, 'all_frames-preload.js') } }); }); afterEach(() => closeWindow(w).then(() => { w = null as unknown as BrowserWindow; }) ); it('applies matching rules in subframes', async () => { const detailsPromise = emittedNTimes(w.webContents, 'did-frame-finish-load', 2); w.loadURL(`http://127.0.0.1:${port}`); const frameEvents = await detailsPromise; await Promise.all( frameEvents.map(async frameEvent => { const [, isMainFrame, , frameRoutingId] = frameEvent; const result: any = await executeJavaScriptInFrame( w.webContents, frameRoutingId, `(() => { const a = document.getElementById('all_frames_enabled') const b = document.getElementById('all_frames_disabled') return { enabledColor: getComputedStyle(a).backgroundColor, disabledColor: getComputedStyle(b).backgroundColor } })()` ); expect(result.enabledColor).to.equal(COLOR_RED); expect(result.disabledColor).to.equal(isMainFrame ? COLOR_BLUE : COLOR_TRANSPARENT); }) ); }); }); }); }; generateTests(false, false); generateTests(false, true); generateTests(true, false); generateTests(true, true); }); describe('extension ui pages', () => { afterEach(() => { session.defaultSession.getAllExtensions().forEach(e => { session.defaultSession.removeExtension(e.id); }); }); it('loads a ui page of an extension', async () => { const { id } = await session.defaultSession.loadExtension(path.join(fixtures, 'extensions', 'ui-page')); const w = new BrowserWindow({ show: false }); await w.loadURL(`chrome-extension://${id}/bare-page.html`); const textContent = await w.webContents.executeJavaScript('document.body.textContent'); expect(textContent).to.equal('ui page loaded ok\n'); }); it('can load resources', async () => { const { id } = await session.defaultSession.loadExtension(path.join(fixtures, 'extensions', 'ui-page')); const w = new BrowserWindow({ show: false }); await w.loadURL(`chrome-extension://${id}/page-script-load.html`); const textContent = await w.webContents.executeJavaScript('document.body.textContent'); expect(textContent).to.equal('script loaded ok\n'); }); }); describe('manifest v3', () => { it('registers background service worker', async () => { const customSession = session.fromPartition(`persist:${uuid.v4()}`); const registrationPromise = new Promise<string>(resolve => { customSession.serviceWorkers.once('registration-completed', (event, { scope }) => resolve(scope)); }); const extension = await customSession.loadExtension(path.join(fixtures, 'extensions', 'mv3-service-worker')); const scope = await registrationPromise; expect(scope).equals(extension.url); }); }); });
closed
electron/electron
https://github.com/electron/electron
34,178
[Bug]: Chrome Extension V3 service_worker - Supported APIs do not function
### 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 13.6.9, 18.2.0, 20.0.0-nightly.20220505 ### What operating system are you using? macOS ### Operating System Version macOS Monterey 12.3.1 ### What arch are you using? x64 ### Last Known Working Electron version N/A ### Expected Behavior For successful messages to be sent to and from the Service Worker in the extension. The test case provided uses Electron's supported Chrome APIs as defined here: https://www.electronjs.org/docs/latest/api/extensions#loading-extensions - A content page is supplied by this extension which simply calls "chrome.runtime.sendMessage" to send a message. - A service worker is supplied by this extension which calls - "chrome.runtime.onInstalled" to print a logging statement - "chrome.runtime.onMessage.addListener" to listen for messages, and to send a response. Expected to see the log message show up on any web page: `I'm a content script, and I'm going to try to send a message to anyone that is listening.` `Hello sender, I received your message.` With the ELECTRON_ENABLE_LOGGING=1 env set, expected to see: `[xxx:INFO:CONSOLE(1)] "Hello, I'm a service worker", source: chrome-extension:///<some_chrome_extension_id>/background.js` `[xxx:INFO:CONSOLE(1)] "Hello, I was just installed.", source: chrome-extension:///<some_chrome_extension_id>/background.js` `[xxx:INFO:CONSOLE(1)] "Hello, I'm a service worker and I just received a message.", source: chrome-extension:///<some_chrome_extension_id>/background.js` ### Actual Behavior Actual logs seen on any web page: `I'm a content script, and I'm going to try to send a message to anyone that is listening.` Actual logs seen in terminal: With the ELECTRON_ENABLE_LOGGING=1 env set, expected to see: `[xxx:INFO:CONSOLE(1)] "Hello, I'm a service worker", source: chrome-extension:///<some_chrome_extension_id>/background.js` ### Testcase Gist URL https://gist.github.com/schetle/8ea7451215b89c4cc28506f96e9f384a ### Additional Information By January of this upcoming year, Manifest V2 extensions will cease to function (please see: https://developer.chrome.com/docs/extensions/mv3/mv2-sunset/) Part of the migration process to get from a V2 -> V3 extension requires that background pages are replaced with service workers (please see: https://developer.chrome.com/docs/extensions/mv3/intro/mv3-migration/#background-service-workers)
https://github.com/electron/electron/issues/34178
https://github.com/electron/electron/pull/39290
b2c62d6ad1fb0745544a20c85abef312c7196d14
c8f7a0e0522b0527082a23438da11bf6f148825c
2022-05-11T16:10:16Z
c++
2023-08-01T06:04:38Z
spec/fixtures/extensions/mv3-service-worker/background.js
console.log('service worker installed');
closed
electron/electron
https://github.com/electron/electron
34,178
[Bug]: Chrome Extension V3 service_worker - Supported APIs do not function
### 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 13.6.9, 18.2.0, 20.0.0-nightly.20220505 ### What operating system are you using? macOS ### Operating System Version macOS Monterey 12.3.1 ### What arch are you using? x64 ### Last Known Working Electron version N/A ### Expected Behavior For successful messages to be sent to and from the Service Worker in the extension. The test case provided uses Electron's supported Chrome APIs as defined here: https://www.electronjs.org/docs/latest/api/extensions#loading-extensions - A content page is supplied by this extension which simply calls "chrome.runtime.sendMessage" to send a message. - A service worker is supplied by this extension which calls - "chrome.runtime.onInstalled" to print a logging statement - "chrome.runtime.onMessage.addListener" to listen for messages, and to send a response. Expected to see the log message show up on any web page: `I'm a content script, and I'm going to try to send a message to anyone that is listening.` `Hello sender, I received your message.` With the ELECTRON_ENABLE_LOGGING=1 env set, expected to see: `[xxx:INFO:CONSOLE(1)] "Hello, I'm a service worker", source: chrome-extension:///<some_chrome_extension_id>/background.js` `[xxx:INFO:CONSOLE(1)] "Hello, I was just installed.", source: chrome-extension:///<some_chrome_extension_id>/background.js` `[xxx:INFO:CONSOLE(1)] "Hello, I'm a service worker and I just received a message.", source: chrome-extension:///<some_chrome_extension_id>/background.js` ### Actual Behavior Actual logs seen on any web page: `I'm a content script, and I'm going to try to send a message to anyone that is listening.` Actual logs seen in terminal: With the ELECTRON_ENABLE_LOGGING=1 env set, expected to see: `[xxx:INFO:CONSOLE(1)] "Hello, I'm a service worker", source: chrome-extension:///<some_chrome_extension_id>/background.js` ### Testcase Gist URL https://gist.github.com/schetle/8ea7451215b89c4cc28506f96e9f384a ### Additional Information By January of this upcoming year, Manifest V2 extensions will cease to function (please see: https://developer.chrome.com/docs/extensions/mv3/mv2-sunset/) Part of the migration process to get from a V2 -> V3 extension requires that background pages are replaced with service workers (please see: https://developer.chrome.com/docs/extensions/mv3/intro/mv3-migration/#background-service-workers)
https://github.com/electron/electron/issues/34178
https://github.com/electron/electron/pull/39290
b2c62d6ad1fb0745544a20c85abef312c7196d14
c8f7a0e0522b0527082a23438da11bf6f148825c
2022-05-11T16:10:16Z
c++
2023-08-01T06:04:38Z
spec/fixtures/extensions/mv3-service-worker/main.js
closed
electron/electron
https://github.com/electron/electron
34,178
[Bug]: Chrome Extension V3 service_worker - Supported APIs do not function
### 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 13.6.9, 18.2.0, 20.0.0-nightly.20220505 ### What operating system are you using? macOS ### Operating System Version macOS Monterey 12.3.1 ### What arch are you using? x64 ### Last Known Working Electron version N/A ### Expected Behavior For successful messages to be sent to and from the Service Worker in the extension. The test case provided uses Electron's supported Chrome APIs as defined here: https://www.electronjs.org/docs/latest/api/extensions#loading-extensions - A content page is supplied by this extension which simply calls "chrome.runtime.sendMessage" to send a message. - A service worker is supplied by this extension which calls - "chrome.runtime.onInstalled" to print a logging statement - "chrome.runtime.onMessage.addListener" to listen for messages, and to send a response. Expected to see the log message show up on any web page: `I'm a content script, and I'm going to try to send a message to anyone that is listening.` `Hello sender, I received your message.` With the ELECTRON_ENABLE_LOGGING=1 env set, expected to see: `[xxx:INFO:CONSOLE(1)] "Hello, I'm a service worker", source: chrome-extension:///<some_chrome_extension_id>/background.js` `[xxx:INFO:CONSOLE(1)] "Hello, I was just installed.", source: chrome-extension:///<some_chrome_extension_id>/background.js` `[xxx:INFO:CONSOLE(1)] "Hello, I'm a service worker and I just received a message.", source: chrome-extension:///<some_chrome_extension_id>/background.js` ### Actual Behavior Actual logs seen on any web page: `I'm a content script, and I'm going to try to send a message to anyone that is listening.` Actual logs seen in terminal: With the ELECTRON_ENABLE_LOGGING=1 env set, expected to see: `[xxx:INFO:CONSOLE(1)] "Hello, I'm a service worker", source: chrome-extension:///<some_chrome_extension_id>/background.js` ### Testcase Gist URL https://gist.github.com/schetle/8ea7451215b89c4cc28506f96e9f384a ### Additional Information By January of this upcoming year, Manifest V2 extensions will cease to function (please see: https://developer.chrome.com/docs/extensions/mv3/mv2-sunset/) Part of the migration process to get from a V2 -> V3 extension requires that background pages are replaced with service workers (please see: https://developer.chrome.com/docs/extensions/mv3/intro/mv3-migration/#background-service-workers)
https://github.com/electron/electron/issues/34178
https://github.com/electron/electron/pull/39290
b2c62d6ad1fb0745544a20c85abef312c7196d14
c8f7a0e0522b0527082a23438da11bf6f148825c
2022-05-11T16:10:16Z
c++
2023-08-01T06:04:38Z
spec/fixtures/extensions/mv3-service-worker/manifest.json
{ "name": "MV3 Service Worker", "description": "Test for extension service worker support.", "version": "1.0", "manifest_version": 3, "background": { "service_worker": "background.js" } }
closed
electron/electron
https://github.com/electron/electron
34,178
[Bug]: Chrome Extension V3 service_worker - Supported APIs do not function
### 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 13.6.9, 18.2.0, 20.0.0-nightly.20220505 ### What operating system are you using? macOS ### Operating System Version macOS Monterey 12.3.1 ### What arch are you using? x64 ### Last Known Working Electron version N/A ### Expected Behavior For successful messages to be sent to and from the Service Worker in the extension. The test case provided uses Electron's supported Chrome APIs as defined here: https://www.electronjs.org/docs/latest/api/extensions#loading-extensions - A content page is supplied by this extension which simply calls "chrome.runtime.sendMessage" to send a message. - A service worker is supplied by this extension which calls - "chrome.runtime.onInstalled" to print a logging statement - "chrome.runtime.onMessage.addListener" to listen for messages, and to send a response. Expected to see the log message show up on any web page: `I'm a content script, and I'm going to try to send a message to anyone that is listening.` `Hello sender, I received your message.` With the ELECTRON_ENABLE_LOGGING=1 env set, expected to see: `[xxx:INFO:CONSOLE(1)] "Hello, I'm a service worker", source: chrome-extension:///<some_chrome_extension_id>/background.js` `[xxx:INFO:CONSOLE(1)] "Hello, I was just installed.", source: chrome-extension:///<some_chrome_extension_id>/background.js` `[xxx:INFO:CONSOLE(1)] "Hello, I'm a service worker and I just received a message.", source: chrome-extension:///<some_chrome_extension_id>/background.js` ### Actual Behavior Actual logs seen on any web page: `I'm a content script, and I'm going to try to send a message to anyone that is listening.` Actual logs seen in terminal: With the ELECTRON_ENABLE_LOGGING=1 env set, expected to see: `[xxx:INFO:CONSOLE(1)] "Hello, I'm a service worker", source: chrome-extension:///<some_chrome_extension_id>/background.js` ### Testcase Gist URL https://gist.github.com/schetle/8ea7451215b89c4cc28506f96e9f384a ### Additional Information By January of this upcoming year, Manifest V2 extensions will cease to function (please see: https://developer.chrome.com/docs/extensions/mv3/mv2-sunset/) Part of the migration process to get from a V2 -> V3 extension requires that background pages are replaced with service workers (please see: https://developer.chrome.com/docs/extensions/mv3/intro/mv3-migration/#background-service-workers)
https://github.com/electron/electron/issues/34178
https://github.com/electron/electron/pull/39290
b2c62d6ad1fb0745544a20c85abef312c7196d14
c8f7a0e0522b0527082a23438da11bf6f148825c
2022-05-11T16:10:16Z
c++
2023-08-01T06:04:38Z
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/escape.h" #include "base/strings/strcat.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.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/embedder_support/user_agent_utils.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/browser/url_loader_request_interceptor.h" #include "content/public/browser/weak_document_ptr.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/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/ssl/ssl_cert_request_info.h" #include "net/ssl/ssl_private_key.h" #include "ppapi/buildflags/buildflags.h" #include "ppapi/host/ppapi_host.h" #include "printing/buildflags/buildflags.h" #include "services/device/public/cpp/geolocation/geolocation_manager.h" #include "services/device/public/cpp/geolocation/location_provider.h" #include "services/network/public/cpp/features.h" #include "services/network/public/cpp/is_potentially_trustworthy.h" #include "services/network/public/cpp/network_switches.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_api_ipc_handler_impl.h" #include "shell/browser/electron_autofill_driver_factory.h" #include "shell/browser/electron_browser_context.h" #include "shell/browser/electron_browser_main_parts.h" #include "shell/browser/electron_navigation_throttle.h" #include "shell/browser/electron_speech_recognition_manager_delegate.h" #include "shell/browser/electron_web_contents_utility_handler_impl.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/webauthn/electron_authenticator_request_delegate.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 "shell/common/thread_restrictions.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(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/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/browser/mac_helpers.h" #include "content/public/browser/child_process_host.h" #endif #if BUILDFLAG(IS_LINUX) #include "components/crash/core/app/crash_switches.h" // nogncheck #include "components/crash/core/app/crashpad.h" // nogncheck #endif #if BUILDFLAG(IS_WIN) #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 "chrome/browser/pdf/chrome_pdf_stream_delegate.h" #include "chrome/browser/plugins/pdf_iframe_navigation_throttle.h" // nogncheck #include "components/pdf/browser/pdf_navigation_throttle.h" #include "components/pdf/browser/pdf_url_loader_request_interceptor.h" #include "components/pdf/browser/pdf_web_contents_helper.h" // nogncheck #include "components/pdf/common/internal_plugin_helpers.h" #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( extensions::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) int GetCrashSignalFD(const base::CommandLine& command_line) { int fd; return crash_reporter::GetHandlerSocket(&fd, nullptr) ? fd : -1; } #endif // BUILDFLAG(IS_LINUX) void MaybeAppendSecureOriginsAllowlistSwitch(base::CommandLine* cmdline) { // |allowlist| combines pref/policy + cmdline switch in the browser process. // For renderer and utility (e.g. NetworkService) processes the switch is the // only available source, so below the combined (pref/policy + cmdline) // allowlist of secure origins is injected into |cmdline| for these other // processes. std::vector<std::string> allowlist = network::SecureOriginAllowlist::GetInstance().GetCurrentAllowlist(); if (!allowlist.empty()) { cmdline->AppendSwitchASCII( network::switches::kUnsafelyTreatInsecureOriginAsSecure, base::JoinString(allowlist, ",")); } } } // namespace // static ElectronBrowserClient* ElectronBrowserClient::Get() { return g_browser_client; } // static void ElectronBrowserClient::SetApplicationLocale(const std::string& locale) { if (!BrowserThread::IsThreadInitialized(BrowserThread::IO) || !content::GetIOThreadTaskRunner({})->PostTask( FROM_HERE, 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 // Remove in case the host is reused after a crash, otherwise noop. host->RemoveObserver(this); // 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; ui::NativeTheme* native_theme = ui::NativeTheme::GetInstanceForNativeUi(); prefs->preferred_color_scheme = native_theme->ShouldUseDarkColors() ? blink::mojom::PreferredColorScheme::kDark : blink::mojom::PreferredColorScheme::kLight; 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 { ScopedAllowBlockingForElectron allow_blocking; 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); auto plugin_child_path = content::ChildProcessHost::GetChildPath( content::ChildProcessHost::CHILD_PLUGIN); if (program != renderer_child_path && program != gpu_child_path && program != plugin_child_path) { 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) pid_t pid; if (crash_reporter::GetHandlerSocket(nullptr, &pid)) { command_line->AppendSwitchASCII( crash_reporter::switches::kCrashpadHandlerPid, base::NumberToString(pid)); } // 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 (process_type != ::switches::kZygoteProcess) { std::string switch_value = api::crash_reporter::GetClientId() + ",no_channel"; command_line->AppendSwitchASCII(::switches::kEnableCrashReporter, 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); if (process_type == ::switches::kUtilityProcess || content::RenderProcessHost::FromID(process_id)) { MaybeAppendSecureOriginsAllowlistSwitch(command_line); } } 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; } 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::BrowserContext* browser_context, content::WebContents* web_contents, net::SSLCertRequestInfo* cert_request_info, net::ClientCertIdentityList client_certs, std::unique_ptr<content::ClientCertificateDelegate> delegate) { if (client_certs.empty()) { delegate->ContinueWithCertificate(nullptr, nullptr); } else if (delegate_) { delegate_->SelectClientCertificate( browser_context, 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; } 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; } 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()); } #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 } void ElectronBrowserClient::GetMediaDeviceIDSalt( content::RenderFrameHost* rfh, const net::SiteForCookies& site_for_cookies, const blink::StorageKey& storage_key, base::OnceCallback<void(bool, const std::string&)> callback) { constexpr bool persistent_media_device_id_allowed = true; std::string persistent_media_device_id_salt = static_cast<ElectronBrowserContext*>(rfh->GetBrowserContext()) ->GetMediaDeviceIDSalt(); std::move(callback).Run(persistent_media_device_id_allowed, persistent_media_device_id_salt); } base::FilePath ElectronBrowserClient::GetLoggingFileName( const base::CommandLine& cmd_line) { return logging::GetLogFileName(cmd_line); } 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(bool /* is_integration_test */) { auto browser_main_parts = std::make_unique<ElectronBrowserMainParts>(); #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( rfh, 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::WeakDocumentPtr document_ptr, 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; content::RenderFrameHost* rfh = document_ptr.AsRenderFrameHostIfValid(); if (!rfh) { // If the render frame host is not valid it means it was a top level // navigation and the frame has already been disposed of. In this case we // take the current main frame and declare it responsible for the // transition. rfh = web_contents->GetPrimaryMainFrame(); } GURL escaped_url(base::EscapeExternalHandlerValue(url.spec())); auto callback = base::BindOnce(&OnOpenExternal, escaped_url); permission_helper->RequestOpenExternalPermission(rfh, std::move(callback), has_user_gesture, url); } bool ElectronBrowserClient::HandleExternalProtocol( const GURL& url, content::WebContents::Getter web_contents_getter, int frame_tree_node_id, content::NavigationUIData* navigation_data, bool is_primary_main_frame, bool is_in_fenced_frame_tree, 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) { content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&HandleExternalProtocolInUI, url, initiator_document ? initiator_document->GetWeakDocumentPtr() : content::WeakDocumentPtr(), 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 #if BUILDFLAG(ENABLE_PDF_VIEWER) std::unique_ptr<content::NavigationThrottle> pdf_iframe_throttle = PDFIFrameNavigationThrottle::MaybeCreateThrottleFor(handle); if (pdf_iframe_throttle) throttles.push_back(std::move(pdf_iframe_throttle)); std::unique_ptr<content::NavigationThrottle> pdf_throttle = pdf::PdfNavigationThrottle::MaybeCreateThrottleFor( handle, std::make_unique<ChromePdfStreamDelegate>()); if (pdf_throttle) throttles.push_back(std::move(pdf_throttle)); #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 session_data; base::PathService::Get(DIR_SESSION_DATA, &session_data); DCHECK(!session_data.empty()); return {session_data}; } 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; } blink::UserAgentMetadata ElectronBrowserClient::GetUserAgentMetadata() { return embedder_support::GetUserAgentMetadata(); } 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); auto* protocol_registry = ProtocolRegistry::FromBrowserContext(browser_context); protocol_registry->RegisterURLLoaderFactories(factories, false /* allow_file_access */); #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, scoped_refptr<base::SequencedTaskRunner> navigation_response_task_runner) { 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, navigation_response_task_runner); 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, &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); return true; } std::vector<std::unique_ptr<content::URLLoaderRequestInterceptor>> ElectronBrowserClient::WillCreateURLLoaderRequestInterceptors( content::NavigationUIData* navigation_ui_data, int frame_tree_node_id, int64_t navigation_id, scoped_refptr<base::SequencedTaskRunner> navigation_response_task_runner) { std::vector<std::unique_ptr<content::URLLoaderRequestInterceptor>> interceptors; #if BUILDFLAG(ENABLE_PDF_VIEWER) { std::unique_ptr<content::URLLoaderRequestInterceptor> pdf_interceptor = pdf::PdfURLLoaderRequestInterceptor::MaybeCreateInterceptor( frame_tree_node_id, std::make_unique<ChromePdfStreamDelegate>()); if (pdf_interceptor) interceptors.push_back(std::move(pdf_interceptor)); } #endif return interceptors; } 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); } void ElectronBrowserClient:: RegisterAssociatedInterfaceBindersForRenderFrameHost( content::RenderFrameHost& render_frame_host, // NOLINT(runtime/references) blink::AssociatedInterfaceRegistry& associated_registry) { // NOLINT(runtime/references) auto* contents = content::WebContents::FromRenderFrameHost(&render_frame_host); if (contents) { auto* prefs = WebContentsPreferences::From(contents); if (render_frame_host.GetFrameTreeNodeId() == contents->GetPrimaryMainFrame()->GetFrameTreeNodeId() || (prefs && prefs->AllowsNodeIntegrationInSubFrames())) { associated_registry.AddInterface<mojom::ElectronApiIPC>( base::BindRepeating( [](content::RenderFrameHost* render_frame_host, mojo::PendingAssociatedReceiver<mojom::ElectronApiIPC> receiver) { ElectronApiIPCHandlerImpl::Create(render_frame_host, std::move(receiver)); }, &render_frame_host)); } } associated_registry.AddInterface<mojom::ElectronWebContentsUtility>( base::BindRepeating( [](content::RenderFrameHost* render_frame_host, mojo::PendingAssociatedReceiver<mojom::ElectronWebContentsUtility> receiver) { ElectronWebContentsUtilityHandlerImpl::Create(render_frame_host, std::move(receiver)); }, &render_frame_host)); associated_registry.AddInterface<mojom::ElectronAutofillDriver>( 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<printing::mojom::PrintManagerHost>( 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<extensions::mojom::LocalFrameHost>( 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<pdf::mojom::PdfService>(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; } 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<extensions::mojom::EventRouter>( base::BindRepeating(&extensions::EventRouter::BindForRenderer, render_process_host->GetID())); associated_registry->AddInterface<extensions::mojom::GuestView>( 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 #if BUILDFLAG(ENABLE_PDF_VIEWER) mime_types.insert(pdf::kInternalPluginMimeType); #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(); } content::UsbDelegate* ElectronBrowserClient::GetUsbDelegate() { if (!usb_delegate_) usb_delegate_ = std::make_unique<ElectronUsbDelegate>(); return usb_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( content::BrowserContext* browser_context, const content::ServiceWorkerVersionBaseInfo& service_worker_version_info, mojo::BinderMapWithContext<const content::ServiceWorkerVersionBaseInfo&>* map) { map->Add<blink::mojom::BadgeService>( base::BindRepeating(&BindBadgeServiceForServiceWorker)); } #if BUILDFLAG(IS_MAC) device::GeolocationManager* ElectronBrowserClient::GetGeolocationManager() { return device::GeolocationManager::GetInstance(); } #endif content::HidDelegate* ElectronBrowserClient::GetHidDelegate() { if (!hid_delegate_) hid_delegate_ = std::make_unique<ElectronHidDelegate>(); return hid_delegate_.get(); } content::WebAuthenticationDelegate* ElectronBrowserClient::GetWebAuthenticationDelegate() { if (!web_authentication_delegate_) { web_authentication_delegate_ = std::make_unique<ElectronWebAuthenticationDelegate>(); } return web_authentication_delegate_.get(); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
34,178
[Bug]: Chrome Extension V3 service_worker - Supported APIs do not function
### 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 13.6.9, 18.2.0, 20.0.0-nightly.20220505 ### What operating system are you using? macOS ### Operating System Version macOS Monterey 12.3.1 ### What arch are you using? x64 ### Last Known Working Electron version N/A ### Expected Behavior For successful messages to be sent to and from the Service Worker in the extension. The test case provided uses Electron's supported Chrome APIs as defined here: https://www.electronjs.org/docs/latest/api/extensions#loading-extensions - A content page is supplied by this extension which simply calls "chrome.runtime.sendMessage" to send a message. - A service worker is supplied by this extension which calls - "chrome.runtime.onInstalled" to print a logging statement - "chrome.runtime.onMessage.addListener" to listen for messages, and to send a response. Expected to see the log message show up on any web page: `I'm a content script, and I'm going to try to send a message to anyone that is listening.` `Hello sender, I received your message.` With the ELECTRON_ENABLE_LOGGING=1 env set, expected to see: `[xxx:INFO:CONSOLE(1)] "Hello, I'm a service worker", source: chrome-extension:///<some_chrome_extension_id>/background.js` `[xxx:INFO:CONSOLE(1)] "Hello, I was just installed.", source: chrome-extension:///<some_chrome_extension_id>/background.js` `[xxx:INFO:CONSOLE(1)] "Hello, I'm a service worker and I just received a message.", source: chrome-extension:///<some_chrome_extension_id>/background.js` ### Actual Behavior Actual logs seen on any web page: `I'm a content script, and I'm going to try to send a message to anyone that is listening.` Actual logs seen in terminal: With the ELECTRON_ENABLE_LOGGING=1 env set, expected to see: `[xxx:INFO:CONSOLE(1)] "Hello, I'm a service worker", source: chrome-extension:///<some_chrome_extension_id>/background.js` ### Testcase Gist URL https://gist.github.com/schetle/8ea7451215b89c4cc28506f96e9f384a ### Additional Information By January of this upcoming year, Manifest V2 extensions will cease to function (please see: https://developer.chrome.com/docs/extensions/mv3/mv2-sunset/) Part of the migration process to get from a V2 -> V3 extension requires that background pages are replaced with service workers (please see: https://developer.chrome.com/docs/extensions/mv3/intro/mv3-migration/#background-service-workers)
https://github.com/electron/electron/issues/34178
https://github.com/electron/electron/pull/39290
b2c62d6ad1fb0745544a20c85abef312c7196d14
c8f7a0e0522b0527082a23438da11bf6f148825c
2022-05-11T16:10:16Z
c++
2023-08-01T06:04:38Z
spec/extensions-spec.ts
import { expect } from 'chai'; import { app, session, BrowserWindow, ipcMain, WebContents, Extension, Session } from 'electron/main'; import { closeAllWindows, closeWindow } from './lib/window-helpers'; import * as http from 'node:http'; import * as path from 'node:path'; import * as fs from 'node:fs'; import * as WebSocket from 'ws'; import { emittedNTimes, emittedUntil } from './lib/events-helpers'; import { ifit, listen } from './lib/spec-helpers'; import { once } from 'node:events'; const uuid = require('uuid'); const fixtures = path.join(__dirname, 'fixtures'); describe('chrome extensions', () => { const emptyPage = '<script>console.log("loaded")</script>'; // NB. extensions are only allowed on http://, https:// and ftp:// (!) urls by default. let server: http.Server; let url: string; let port: number; before(async () => { server = http.createServer((req, res) => { if (req.url === '/cors') { res.setHeader('Access-Control-Allow-Origin', 'http://example.com'); } res.end(emptyPage); }); const wss = new WebSocket.Server({ noServer: true }); wss.on('connection', function connection (ws) { ws.on('message', function incoming (message) { if (message === 'foo') { ws.send('bar'); } }); }); ({ port, url } = await listen(server)); }); after(() => { server.close(); }); afterEach(closeAllWindows); afterEach(() => { session.defaultSession.getAllExtensions().forEach((e: any) => { session.defaultSession.removeExtension(e.id); }); }); it('does not crash when using chrome.management', async () => { const customSession = session.fromPartition(`persist:${require('uuid').v4()}`); const w = new BrowserWindow({ show: false, webPreferences: { session: customSession, sandbox: true } }); await w.loadURL('about:blank'); const promise = once(app, 'web-contents-created') as Promise<[any, WebContents]>; await customSession.loadExtension(path.join(fixtures, 'extensions', 'persistent-background-page')); const args: any = await promise; const wc: Electron.WebContents = args[1]; await expect(wc.executeJavaScript(` (() => { return new Promise((resolve) => { chrome.management.getSelf((info) => { resolve(info); }); }) })(); `)).to.eventually.have.property('id'); }); it('can open WebSQLDatabase in a background page', async () => { const customSession = session.fromPartition(`persist:${require('uuid').v4()}`); const w = new BrowserWindow({ show: false, webPreferences: { session: customSession, sandbox: true } }); await w.loadURL('about:blank'); const promise = once(app, 'web-contents-created') as Promise<[any, WebContents]>; await customSession.loadExtension(path.join(fixtures, 'extensions', 'persistent-background-page')); const args: any = await promise; const wc: Electron.WebContents = args[1]; await expect(wc.executeJavaScript('(()=>{try{openDatabase("t", "1.0", "test", 2e5);return true;}catch(e){throw e}})()')).to.not.be.rejected(); }); function fetch (contents: WebContents, url: string) { return contents.executeJavaScript(`fetch(${JSON.stringify(url)})`); } it('bypasses CORS in requests made from extensions', async () => { const customSession = session.fromPartition(`persist:${require('uuid').v4()}`); const w = new BrowserWindow({ show: false, webPreferences: { session: customSession, sandbox: true } }); const extension = await customSession.loadExtension(path.join(fixtures, 'extensions', 'ui-page')); await w.loadURL(`${extension.url}bare-page.html`); await expect(fetch(w.webContents, `${url}/cors`)).to.not.be.rejectedWith(TypeError); }); it('loads an extension', async () => { // NB. we have to use a persist: session (i.e. non-OTR) because the // extension registry is redirected to the main session. so installing an // extension in an in-memory session results in it being installed in the // default session. const customSession = session.fromPartition(`persist:${uuid.v4()}`); await customSession.loadExtension(path.join(fixtures, 'extensions', 'red-bg')); const w = new BrowserWindow({ show: false, webPreferences: { session: customSession } }); await w.loadURL(url); const bg = await w.webContents.executeJavaScript('document.documentElement.style.backgroundColor'); expect(bg).to.equal('red'); }); it('does not crash when loading an extension with missing manifest', async () => { const customSession = session.fromPartition(`persist:${uuid.v4()}`); const promise = customSession.loadExtension(path.join(fixtures, 'extensions', 'missing-manifest')); await expect(promise).to.eventually.be.rejectedWith(/Manifest file is missing or unreadable/); }); it('does not crash when failing to load an extension', async () => { const customSession = session.fromPartition(`persist:${uuid.v4()}`); const promise = customSession.loadExtension(path.join(fixtures, 'extensions', 'load-error')); await expect(promise).to.eventually.be.rejected(); }); it('serializes a loaded extension', async () => { const extensionPath = path.join(fixtures, 'extensions', 'red-bg'); const manifest = JSON.parse(fs.readFileSync(path.join(extensionPath, 'manifest.json'), 'utf-8')); const customSession = session.fromPartition(`persist:${uuid.v4()}`); const extension = await customSession.loadExtension(extensionPath); expect(extension.id).to.be.a('string'); expect(extension.name).to.be.a('string'); expect(extension.path).to.be.a('string'); expect(extension.version).to.be.a('string'); expect(extension.url).to.be.a('string'); expect(extension.manifest).to.deep.equal(manifest); }); it('removes an extension', async () => { const customSession = session.fromPartition(`persist:${uuid.v4()}`); const { id } = await customSession.loadExtension(path.join(fixtures, 'extensions', 'red-bg')); { const w = new BrowserWindow({ show: false, webPreferences: { session: customSession } }); await w.loadURL(url); const bg = await w.webContents.executeJavaScript('document.documentElement.style.backgroundColor'); expect(bg).to.equal('red'); } customSession.removeExtension(id); { const w = new BrowserWindow({ show: false, webPreferences: { session: customSession } }); await w.loadURL(url); const bg = await w.webContents.executeJavaScript('document.documentElement.style.backgroundColor'); expect(bg).to.equal(''); } }); it('emits extension lifecycle events', async () => { const customSession = session.fromPartition(`persist:${require('uuid').v4()}`); const loadedPromise = once(customSession, 'extension-loaded'); const readyPromise = emittedUntil(customSession, 'extension-ready', (event: Event, extension: Extension) => { return extension.name !== 'Chromium PDF Viewer'; }); const extension = await customSession.loadExtension(path.join(fixtures, 'extensions', 'red-bg')); const [, loadedExtension] = await loadedPromise; const [, readyExtension] = await readyPromise; expect(loadedExtension).to.deep.equal(extension); expect(readyExtension).to.deep.equal(extension); const unloadedPromise = once(customSession, 'extension-unloaded'); await customSession.removeExtension(extension.id); const [, unloadedExtension] = await unloadedPromise; expect(unloadedExtension).to.deep.equal(extension); }); it('lists loaded extensions in getAllExtensions', async () => { const customSession = session.fromPartition(`persist:${uuid.v4()}`); const e = await customSession.loadExtension(path.join(fixtures, 'extensions', 'red-bg')); expect(customSession.getAllExtensions()).to.deep.equal([e]); customSession.removeExtension(e.id); expect(customSession.getAllExtensions()).to.deep.equal([]); }); it('gets an extension by id', async () => { const customSession = session.fromPartition(`persist:${uuid.v4()}`); const e = await customSession.loadExtension(path.join(fixtures, 'extensions', 'red-bg')); expect(customSession.getExtension(e.id)).to.deep.equal(e); }); it('confines an extension to the session it was loaded in', async () => { const customSession = session.fromPartition(`persist:${uuid.v4()}`); await customSession.loadExtension(path.join(fixtures, 'extensions', 'red-bg')); const w = new BrowserWindow({ show: false }); // not in the session await w.loadURL(url); const bg = await w.webContents.executeJavaScript('document.documentElement.style.backgroundColor'); expect(bg).to.equal(''); }); it('loading an extension in a temporary session throws an error', async () => { const customSession = session.fromPartition(uuid.v4()); await expect(customSession.loadExtension(path.join(fixtures, 'extensions', 'red-bg'))).to.eventually.be.rejectedWith('Extensions cannot be loaded in a temporary session'); }); describe('chrome.i18n', () => { let w: BrowserWindow; let extension: Extension; const exec = async (name: string) => { const p = once(ipcMain, 'success'); await w.webContents.executeJavaScript(`exec('${name}')`); const [, result] = await p; return result; }; beforeEach(async () => { const customSession = session.fromPartition(`persist:${uuid.v4()}`); extension = await customSession.loadExtension(path.join(fixtures, 'extensions', 'chrome-i18n')); w = new BrowserWindow({ show: false, webPreferences: { session: customSession, nodeIntegration: true, contextIsolation: false } }); await w.loadURL(url); }); it('getAcceptLanguages()', async () => { const result = await exec('getAcceptLanguages'); expect(result).to.be.an('array').and.deep.equal(['en-US', 'en']); }); it('getMessage()', async () => { const result = await exec('getMessage'); expect(result.id).to.be.a('string').and.equal(extension.id); expect(result.name).to.be.a('string').and.equal('chrome-i18n'); }); }); describe('chrome.runtime', () => { let w: BrowserWindow; const exec = async (name: string) => { const p = once(ipcMain, 'success'); await w.webContents.executeJavaScript(`exec('${name}')`); const [, result] = await p; return result; }; beforeEach(async () => { const customSession = session.fromPartition(`persist:${uuid.v4()}`); await customSession.loadExtension(path.join(fixtures, 'extensions', 'chrome-runtime')); w = new BrowserWindow({ show: false, webPreferences: { session: customSession, nodeIntegration: true, contextIsolation: false } }); await w.loadURL(url); }); it('getManifest()', async () => { const result = await exec('getManifest'); expect(result).to.be.an('object').with.property('name', 'chrome-runtime'); }); it('id', async () => { const result = await exec('id'); expect(result).to.be.a('string').with.lengthOf(32); }); it('getURL()', async () => { const result = await exec('getURL'); expect(result).to.be.a('string').and.match(/^chrome-extension:\/\/.*main.js$/); }); it('getPlatformInfo()', async () => { const result = await exec('getPlatformInfo'); expect(result).to.be.an('object'); expect(result.os).to.be.a('string'); expect(result.arch).to.be.a('string'); expect(result.nacl_arch).to.be.a('string'); }); }); describe('chrome.storage', () => { it('stores and retrieves a key', async () => { const customSession = session.fromPartition(`persist:${uuid.v4()}`); await customSession.loadExtension(path.join(fixtures, 'extensions', 'chrome-storage')); const w = new BrowserWindow({ show: false, webPreferences: { session: customSession, nodeIntegration: true, contextIsolation: false } }); try { const p = once(ipcMain, 'storage-success'); await w.loadURL(url); const [, v] = await p; expect(v).to.equal('value'); } finally { w.destroy(); } }); }); describe('chrome.webRequest', () => { function fetch (contents: WebContents, url: string) { return contents.executeJavaScript(`fetch(${JSON.stringify(url)})`); } let customSession: Session; let w: BrowserWindow; beforeEach(() => { customSession = session.fromPartition(`persist:${uuid.v4()}`); w = new BrowserWindow({ show: false, webPreferences: { session: customSession, sandbox: true, contextIsolation: true } }); }); describe('onBeforeRequest', () => { it('can cancel http requests', async () => { await w.loadURL(url); await customSession.loadExtension(path.join(fixtures, 'extensions', 'chrome-webRequest')); await expect(fetch(w.webContents, url)).to.eventually.be.rejectedWith('Failed to fetch'); }); it('does not cancel http requests when no extension loaded', async () => { await w.loadURL(url); await expect(fetch(w.webContents, url)).to.not.be.rejectedWith('Failed to fetch'); }); }); it('does not take precedence over Electron webRequest - http', async () => { return new Promise<void>((resolve) => { (async () => { customSession.webRequest.onBeforeRequest((details, callback) => { resolve(); callback({ cancel: true }); }); await w.loadURL(url); await customSession.loadExtension(path.join(fixtures, 'extensions', 'chrome-webRequest')); fetch(w.webContents, url); })(); }); }); it('does not take precedence over Electron webRequest - WebSocket', () => { return new Promise<void>((resolve) => { (async () => { customSession.webRequest.onBeforeSendHeaders(() => { resolve(); }); await w.loadFile(path.join(fixtures, 'api', 'webrequest.html'), { query: { port: `${port}` } }); await customSession.loadExtension(path.join(fixtures, 'extensions', 'chrome-webRequest-wss')); })(); }); }); describe('WebSocket', () => { it('can be proxied', async () => { await w.loadFile(path.join(fixtures, 'api', 'webrequest.html'), { query: { port: `${port}` } }); await customSession.loadExtension(path.join(fixtures, 'extensions', 'chrome-webRequest-wss')); customSession.webRequest.onSendHeaders((details) => { if (details.url.startsWith('ws://')) { expect(details.requestHeaders.foo).be.equal('bar'); } }); }); }); }); describe('chrome.tabs', () => { let customSession: Session; before(async () => { customSession = session.fromPartition(`persist:${uuid.v4()}`); await customSession.loadExtension(path.join(fixtures, 'extensions', 'chrome-api')); }); it('executeScript', async () => { const w = new BrowserWindow({ show: false, webPreferences: { session: customSession, nodeIntegration: true } }); await w.loadURL(url); const message = { method: 'executeScript', args: ['1 + 2'] }; w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`); const [,, responseString] = await once(w.webContents, 'console-message'); const response = JSON.parse(responseString); expect(response).to.equal(3); }); it('connect', async () => { const w = new BrowserWindow({ show: false, webPreferences: { session: customSession, nodeIntegration: true } }); await w.loadURL(url); const portName = uuid.v4(); const message = { method: 'connectTab', args: [portName] }; w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`); const [,, responseString] = await once(w.webContents, 'console-message'); const response = responseString.split(','); expect(response[0]).to.equal(portName); expect(response[1]).to.equal('howdy'); }); it('sendMessage receives the response', async () => { const w = new BrowserWindow({ show: false, webPreferences: { session: customSession, nodeIntegration: true } }); await w.loadURL(url); const message = { method: 'sendMessage', args: ['Hello World!'] }; w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`); const [,, responseString] = await once(w.webContents, 'console-message'); const response = JSON.parse(responseString); expect(response.message).to.equal('Hello World!'); expect(response.tabId).to.equal(w.webContents.id); }); it('update', async () => { const w = new BrowserWindow({ show: false, webPreferences: { session: customSession, nodeIntegration: true } }); await w.loadURL(url); const w2 = new BrowserWindow({ show: false, webPreferences: { session: customSession } }); await w2.loadURL('about:blank'); const w2Navigated = once(w2.webContents, 'did-navigate'); const message = { method: 'update', args: [w2.webContents.id, { url }] }; w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`); const [,, responseString] = await once(w.webContents, 'console-message'); const response = JSON.parse(responseString); await w2Navigated; expect(new URL(w2.getURL()).toString()).to.equal(new URL(url).toString()); expect(response.id).to.equal(w2.webContents.id); }); }); describe('background pages', () => { it('loads a lazy background page when sending a message', async () => { const customSession = session.fromPartition(`persist:${uuid.v4()}`); await customSession.loadExtension(path.join(fixtures, 'extensions', 'lazy-background-page')); const w = new BrowserWindow({ show: false, webPreferences: { session: customSession, nodeIntegration: true, contextIsolation: false } }); try { w.loadURL(url); const [, resp] = await once(ipcMain, 'bg-page-message-response'); expect(resp.message).to.deep.equal({ some: 'message' }); expect(resp.sender.id).to.be.a('string'); expect(resp.sender.origin).to.equal(url); expect(resp.sender.url).to.equal(url + '/'); } finally { w.destroy(); } }); it('can use extension.getBackgroundPage from a ui page', async () => { const customSession = session.fromPartition(`persist:${uuid.v4()}`); const { id } = await customSession.loadExtension(path.join(fixtures, 'extensions', 'lazy-background-page')); const w = new BrowserWindow({ show: false, webPreferences: { session: customSession } }); await w.loadURL(`chrome-extension://${id}/page-get-background.html`); const receivedMessage = await w.webContents.executeJavaScript('window.completionPromise'); expect(receivedMessage).to.deep.equal({ some: 'message' }); }); it('can use extension.getBackgroundPage from a ui page', async () => { const customSession = session.fromPartition(`persist:${uuid.v4()}`); const { id } = await customSession.loadExtension(path.join(fixtures, 'extensions', 'lazy-background-page')); const w = new BrowserWindow({ show: false, webPreferences: { session: customSession } }); await w.loadURL(`chrome-extension://${id}/page-get-background.html`); const receivedMessage = await w.webContents.executeJavaScript('window.completionPromise'); expect(receivedMessage).to.deep.equal({ some: 'message' }); }); it('can use runtime.getBackgroundPage from a ui page', async () => { const customSession = session.fromPartition(`persist:${uuid.v4()}`); const { id } = await customSession.loadExtension(path.join(fixtures, 'extensions', 'lazy-background-page')); const w = new BrowserWindow({ show: false, webPreferences: { session: customSession } }); await w.loadURL(`chrome-extension://${id}/page-runtime-get-background.html`); const receivedMessage = await w.webContents.executeJavaScript('window.completionPromise'); expect(receivedMessage).to.deep.equal({ some: 'message' }); }); it('has session in background page', async () => { const customSession = session.fromPartition(`persist:${require('uuid').v4()}`); const promise = once(app, 'web-contents-created') as Promise<[any, WebContents]>; const { id } = await customSession.loadExtension(path.join(fixtures, 'extensions', 'persistent-background-page')); const [, bgPageContents] = await promise; expect(bgPageContents.getType()).to.equal('backgroundPage'); await once(bgPageContents, 'did-finish-load'); expect(bgPageContents.getURL()).to.equal(`chrome-extension://${id}/_generated_background_page.html`); expect(bgPageContents.session).to.not.equal(undefined); }); it('can open devtools of background page', async () => { const customSession = session.fromPartition(`persist:${require('uuid').v4()}`); const promise = once(app, 'web-contents-created') as Promise<[any, WebContents]>; await customSession.loadExtension(path.join(fixtures, 'extensions', 'persistent-background-page')); const [, bgPageContents] = await promise; expect(bgPageContents.getType()).to.equal('backgroundPage'); bgPageContents.openDevTools(); bgPageContents.closeDevTools(); }); }); describe('devtools extensions', () => { let showPanelTimeoutId: any = null; afterEach(() => { if (showPanelTimeoutId) clearTimeout(showPanelTimeoutId); }); const showLastDevToolsPanel = (w: BrowserWindow) => { w.webContents.once('devtools-opened', () => { const show = () => { if (w == null || w.isDestroyed()) return; const { devToolsWebContents } = w as unknown as { devToolsWebContents: WebContents | undefined }; if (devToolsWebContents == null || devToolsWebContents.isDestroyed()) { return; } const showLastPanel = () => { // this is executed in the devtools context, where UI is a global const { UI } = (window as any); const tabs = UI.inspectorView.tabbedPane.tabs; const lastPanelId = tabs[tabs.length - 1].id; UI.inspectorView.showPanel(lastPanelId); }; devToolsWebContents.executeJavaScript(`(${showLastPanel})()`, false).then(() => { showPanelTimeoutId = setTimeout(show, 100); }); }; showPanelTimeoutId = setTimeout(show, 100); }); }; // TODO(jkleinsc) fix this flaky test on WOA ifit(process.platform !== 'win32' || process.arch !== 'arm64')('loads a devtools extension', async () => { const customSession = session.fromPartition(`persist:${uuid.v4()}`); customSession.loadExtension(path.join(fixtures, 'extensions', 'devtools-extension')); const winningMessage = once(ipcMain, 'winning'); const w = new BrowserWindow({ show: true, webPreferences: { session: customSession, nodeIntegration: true, contextIsolation: false } }); await w.loadURL(url); w.webContents.openDevTools(); showLastDevToolsPanel(w); await winningMessage; }); }); describe('chrome extension content scripts', () => { const fixtures = path.resolve(__dirname, 'fixtures'); const extensionPath = path.resolve(fixtures, 'extensions'); const addExtension = (name: string) => session.defaultSession.loadExtension(path.resolve(extensionPath, name)); const removeAllExtensions = () => { Object.keys(session.defaultSession.getAllExtensions()).map(extName => { session.defaultSession.removeExtension(extName); }); }; let responseIdCounter = 0; const executeJavaScriptInFrame = (webContents: WebContents, frameRoutingId: number, code: string) => { return new Promise(resolve => { const responseId = responseIdCounter++; ipcMain.once(`executeJavaScriptInFrame_${responseId}`, (event, result) => { resolve(result); }); webContents.send('executeJavaScriptInFrame', frameRoutingId, code, responseId); }); }; const generateTests = (sandboxEnabled: boolean, contextIsolationEnabled: boolean) => { describe(`with sandbox ${sandboxEnabled ? 'enabled' : 'disabled'} and context isolation ${contextIsolationEnabled ? 'enabled' : 'disabled'}`, () => { let w: BrowserWindow; describe('supports "run_at" option', () => { beforeEach(async () => { await closeWindow(w); w = new BrowserWindow({ show: false, width: 400, height: 400, webPreferences: { contextIsolation: contextIsolationEnabled, sandbox: sandboxEnabled } }); }); afterEach(async () => { removeAllExtensions(); await closeWindow(w); w = null as unknown as BrowserWindow; }); it('should run content script at document_start', async () => { await addExtension('content-script-document-start'); w.webContents.once('dom-ready', async () => { const result = await w.webContents.executeJavaScript('document.documentElement.style.backgroundColor'); expect(result).to.equal('red'); }); w.loadURL(url); }); it('should run content script at document_idle', async () => { await addExtension('content-script-document-idle'); w.loadURL(url); const result = await w.webContents.executeJavaScript('document.body.style.backgroundColor'); expect(result).to.equal('red'); }); it('should run content script at document_end', async () => { await addExtension('content-script-document-end'); w.webContents.once('did-finish-load', async () => { const result = await w.webContents.executeJavaScript('document.documentElement.style.backgroundColor'); expect(result).to.equal('red'); }); w.loadURL(url); }); }); describe('supports "all_frames" option', () => { const contentScript = path.resolve(fixtures, 'extensions/content-script'); const contentPath = path.join(contentScript, 'frame-with-frame.html'); // Computed style values const COLOR_RED = 'rgb(255, 0, 0)'; const COLOR_BLUE = 'rgb(0, 0, 255)'; const COLOR_TRANSPARENT = 'rgba(0, 0, 0, 0)'; let server: http.Server; let port: number; before(async () => { server = http.createServer((_, res) => { fs.readFile(contentPath, (error, content) => { if (error) { res.writeHead(500); res.end(`Failed to load ${contentPath} : ${error.code}`); } else { res.writeHead(200, { 'Content-Type': 'text/html' }); res.end(content, 'utf-8'); } }); }); ({ port, url } = await listen(server)); session.defaultSession.loadExtension(contentScript); }); after(() => { session.defaultSession.removeExtension('content-script-test'); }); beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { // enable content script injection in subframes nodeIntegrationInSubFrames: true, preload: path.join(contentScript, 'all_frames-preload.js') } }); }); afterEach(() => closeWindow(w).then(() => { w = null as unknown as BrowserWindow; }) ); it('applies matching rules in subframes', async () => { const detailsPromise = emittedNTimes(w.webContents, 'did-frame-finish-load', 2); w.loadURL(`http://127.0.0.1:${port}`); const frameEvents = await detailsPromise; await Promise.all( frameEvents.map(async frameEvent => { const [, isMainFrame, , frameRoutingId] = frameEvent; const result: any = await executeJavaScriptInFrame( w.webContents, frameRoutingId, `(() => { const a = document.getElementById('all_frames_enabled') const b = document.getElementById('all_frames_disabled') return { enabledColor: getComputedStyle(a).backgroundColor, disabledColor: getComputedStyle(b).backgroundColor } })()` ); expect(result.enabledColor).to.equal(COLOR_RED); expect(result.disabledColor).to.equal(isMainFrame ? COLOR_BLUE : COLOR_TRANSPARENT); }) ); }); }); }); }; generateTests(false, false); generateTests(false, true); generateTests(true, false); generateTests(true, true); }); describe('extension ui pages', () => { afterEach(() => { session.defaultSession.getAllExtensions().forEach(e => { session.defaultSession.removeExtension(e.id); }); }); it('loads a ui page of an extension', async () => { const { id } = await session.defaultSession.loadExtension(path.join(fixtures, 'extensions', 'ui-page')); const w = new BrowserWindow({ show: false }); await w.loadURL(`chrome-extension://${id}/bare-page.html`); const textContent = await w.webContents.executeJavaScript('document.body.textContent'); expect(textContent).to.equal('ui page loaded ok\n'); }); it('can load resources', async () => { const { id } = await session.defaultSession.loadExtension(path.join(fixtures, 'extensions', 'ui-page')); const w = new BrowserWindow({ show: false }); await w.loadURL(`chrome-extension://${id}/page-script-load.html`); const textContent = await w.webContents.executeJavaScript('document.body.textContent'); expect(textContent).to.equal('script loaded ok\n'); }); }); describe('manifest v3', () => { it('registers background service worker', async () => { const customSession = session.fromPartition(`persist:${uuid.v4()}`); const registrationPromise = new Promise<string>(resolve => { customSession.serviceWorkers.once('registration-completed', (event, { scope }) => resolve(scope)); }); const extension = await customSession.loadExtension(path.join(fixtures, 'extensions', 'mv3-service-worker')); const scope = await registrationPromise; expect(scope).equals(extension.url); }); }); });
closed
electron/electron
https://github.com/electron/electron
34,178
[Bug]: Chrome Extension V3 service_worker - Supported APIs do not function
### 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 13.6.9, 18.2.0, 20.0.0-nightly.20220505 ### What operating system are you using? macOS ### Operating System Version macOS Monterey 12.3.1 ### What arch are you using? x64 ### Last Known Working Electron version N/A ### Expected Behavior For successful messages to be sent to and from the Service Worker in the extension. The test case provided uses Electron's supported Chrome APIs as defined here: https://www.electronjs.org/docs/latest/api/extensions#loading-extensions - A content page is supplied by this extension which simply calls "chrome.runtime.sendMessage" to send a message. - A service worker is supplied by this extension which calls - "chrome.runtime.onInstalled" to print a logging statement - "chrome.runtime.onMessage.addListener" to listen for messages, and to send a response. Expected to see the log message show up on any web page: `I'm a content script, and I'm going to try to send a message to anyone that is listening.` `Hello sender, I received your message.` With the ELECTRON_ENABLE_LOGGING=1 env set, expected to see: `[xxx:INFO:CONSOLE(1)] "Hello, I'm a service worker", source: chrome-extension:///<some_chrome_extension_id>/background.js` `[xxx:INFO:CONSOLE(1)] "Hello, I was just installed.", source: chrome-extension:///<some_chrome_extension_id>/background.js` `[xxx:INFO:CONSOLE(1)] "Hello, I'm a service worker and I just received a message.", source: chrome-extension:///<some_chrome_extension_id>/background.js` ### Actual Behavior Actual logs seen on any web page: `I'm a content script, and I'm going to try to send a message to anyone that is listening.` Actual logs seen in terminal: With the ELECTRON_ENABLE_LOGGING=1 env set, expected to see: `[xxx:INFO:CONSOLE(1)] "Hello, I'm a service worker", source: chrome-extension:///<some_chrome_extension_id>/background.js` ### Testcase Gist URL https://gist.github.com/schetle/8ea7451215b89c4cc28506f96e9f384a ### Additional Information By January of this upcoming year, Manifest V2 extensions will cease to function (please see: https://developer.chrome.com/docs/extensions/mv3/mv2-sunset/) Part of the migration process to get from a V2 -> V3 extension requires that background pages are replaced with service workers (please see: https://developer.chrome.com/docs/extensions/mv3/intro/mv3-migration/#background-service-workers)
https://github.com/electron/electron/issues/34178
https://github.com/electron/electron/pull/39290
b2c62d6ad1fb0745544a20c85abef312c7196d14
c8f7a0e0522b0527082a23438da11bf6f148825c
2022-05-11T16:10:16Z
c++
2023-08-01T06:04:38Z
spec/fixtures/extensions/mv3-service-worker/background.js
console.log('service worker installed');
closed
electron/electron
https://github.com/electron/electron
34,178
[Bug]: Chrome Extension V3 service_worker - Supported APIs do not function
### 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 13.6.9, 18.2.0, 20.0.0-nightly.20220505 ### What operating system are you using? macOS ### Operating System Version macOS Monterey 12.3.1 ### What arch are you using? x64 ### Last Known Working Electron version N/A ### Expected Behavior For successful messages to be sent to and from the Service Worker in the extension. The test case provided uses Electron's supported Chrome APIs as defined here: https://www.electronjs.org/docs/latest/api/extensions#loading-extensions - A content page is supplied by this extension which simply calls "chrome.runtime.sendMessage" to send a message. - A service worker is supplied by this extension which calls - "chrome.runtime.onInstalled" to print a logging statement - "chrome.runtime.onMessage.addListener" to listen for messages, and to send a response. Expected to see the log message show up on any web page: `I'm a content script, and I'm going to try to send a message to anyone that is listening.` `Hello sender, I received your message.` With the ELECTRON_ENABLE_LOGGING=1 env set, expected to see: `[xxx:INFO:CONSOLE(1)] "Hello, I'm a service worker", source: chrome-extension:///<some_chrome_extension_id>/background.js` `[xxx:INFO:CONSOLE(1)] "Hello, I was just installed.", source: chrome-extension:///<some_chrome_extension_id>/background.js` `[xxx:INFO:CONSOLE(1)] "Hello, I'm a service worker and I just received a message.", source: chrome-extension:///<some_chrome_extension_id>/background.js` ### Actual Behavior Actual logs seen on any web page: `I'm a content script, and I'm going to try to send a message to anyone that is listening.` Actual logs seen in terminal: With the ELECTRON_ENABLE_LOGGING=1 env set, expected to see: `[xxx:INFO:CONSOLE(1)] "Hello, I'm a service worker", source: chrome-extension:///<some_chrome_extension_id>/background.js` ### Testcase Gist URL https://gist.github.com/schetle/8ea7451215b89c4cc28506f96e9f384a ### Additional Information By January of this upcoming year, Manifest V2 extensions will cease to function (please see: https://developer.chrome.com/docs/extensions/mv3/mv2-sunset/) Part of the migration process to get from a V2 -> V3 extension requires that background pages are replaced with service workers (please see: https://developer.chrome.com/docs/extensions/mv3/intro/mv3-migration/#background-service-workers)
https://github.com/electron/electron/issues/34178
https://github.com/electron/electron/pull/39290
b2c62d6ad1fb0745544a20c85abef312c7196d14
c8f7a0e0522b0527082a23438da11bf6f148825c
2022-05-11T16:10:16Z
c++
2023-08-01T06:04:38Z
spec/fixtures/extensions/mv3-service-worker/main.js
closed
electron/electron
https://github.com/electron/electron
34,178
[Bug]: Chrome Extension V3 service_worker - Supported APIs do not function
### 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 13.6.9, 18.2.0, 20.0.0-nightly.20220505 ### What operating system are you using? macOS ### Operating System Version macOS Monterey 12.3.1 ### What arch are you using? x64 ### Last Known Working Electron version N/A ### Expected Behavior For successful messages to be sent to and from the Service Worker in the extension. The test case provided uses Electron's supported Chrome APIs as defined here: https://www.electronjs.org/docs/latest/api/extensions#loading-extensions - A content page is supplied by this extension which simply calls "chrome.runtime.sendMessage" to send a message. - A service worker is supplied by this extension which calls - "chrome.runtime.onInstalled" to print a logging statement - "chrome.runtime.onMessage.addListener" to listen for messages, and to send a response. Expected to see the log message show up on any web page: `I'm a content script, and I'm going to try to send a message to anyone that is listening.` `Hello sender, I received your message.` With the ELECTRON_ENABLE_LOGGING=1 env set, expected to see: `[xxx:INFO:CONSOLE(1)] "Hello, I'm a service worker", source: chrome-extension:///<some_chrome_extension_id>/background.js` `[xxx:INFO:CONSOLE(1)] "Hello, I was just installed.", source: chrome-extension:///<some_chrome_extension_id>/background.js` `[xxx:INFO:CONSOLE(1)] "Hello, I'm a service worker and I just received a message.", source: chrome-extension:///<some_chrome_extension_id>/background.js` ### Actual Behavior Actual logs seen on any web page: `I'm a content script, and I'm going to try to send a message to anyone that is listening.` Actual logs seen in terminal: With the ELECTRON_ENABLE_LOGGING=1 env set, expected to see: `[xxx:INFO:CONSOLE(1)] "Hello, I'm a service worker", source: chrome-extension:///<some_chrome_extension_id>/background.js` ### Testcase Gist URL https://gist.github.com/schetle/8ea7451215b89c4cc28506f96e9f384a ### Additional Information By January of this upcoming year, Manifest V2 extensions will cease to function (please see: https://developer.chrome.com/docs/extensions/mv3/mv2-sunset/) Part of the migration process to get from a V2 -> V3 extension requires that background pages are replaced with service workers (please see: https://developer.chrome.com/docs/extensions/mv3/intro/mv3-migration/#background-service-workers)
https://github.com/electron/electron/issues/34178
https://github.com/electron/electron/pull/39290
b2c62d6ad1fb0745544a20c85abef312c7196d14
c8f7a0e0522b0527082a23438da11bf6f148825c
2022-05-11T16:10:16Z
c++
2023-08-01T06:04:38Z
spec/fixtures/extensions/mv3-service-worker/manifest.json
{ "name": "MV3 Service Worker", "description": "Test for extension service worker support.", "version": "1.0", "manifest_version": 3, "background": { "service_worker": "background.js" } }
closed
electron/electron
https://github.com/electron/electron
39,322
[Bug]: --trace-warnings option not doing anything
### 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 25.3.2 ### What operating system are you using? Other (specify below) ### Operating System Version any OS ### What arch are you using? Other (specify below) ### Last Known Working Electron version _No response_ ### Expected Behavior I expect to get some more information about warning when using `--trace-warnings` ### Actual Behavior Same behavior as without `--trace-warnings` ` "start": "electron --trace-warnings ."` ``` electron-quick-start git:(main) npm start > [email protected] start > electron . --trace-warnings (node:22471) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 window-all-closed listeners added to [App]. Use emitter.setMaxListeners() to increase limit (Use `electron --trace-warnings ...` to show where the warning was created) ``` ` "start": "electron ."` ``` electron-quick-start git:(main) ✗ npm start > [email protected] start > electron . (node:22616) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 window-all-closed listeners added to [App]. Use emitter.setMaxListeners() to increase limit (Use `electron --trace-warnings ...` to show where the warning was created) ``` ### Testcase Gist URL https://github.com/hovancik/electron-trace-warnings-isssue ### Additional Information _No response_
https://github.com/electron/electron/issues/39322
https://github.com/electron/electron/pull/39344
c5b9f766f373f4d403a8af2f75e28ca2d901cc32
2e0517c0addc05678e59906d91d72cc8f4860547
2023-08-01T15:47:31Z
c++
2023-08-04T10:59:40Z
docs/api/command-line-switches.md
# Supported Command Line Switches > Command line switches supported by Electron. You can use [app.commandLine.appendSwitch][append-switch] to append them in your app's main script before the [ready][ready] event of the [app][app] module is emitted: ```javascript const { app } = require('electron') app.commandLine.appendSwitch('remote-debugging-port', '8315') app.commandLine.appendSwitch('host-rules', 'MAP * 127.0.0.1') app.whenReady().then(() => { // Your code here }) ``` ## Electron CLI Flags ### --auth-server-whitelist=`url` A comma-separated list of servers for which integrated authentication is enabled. For example: ```sh --auth-server-whitelist='*example.com, *foobar.com, *baz' ``` then any `url` ending with `example.com`, `foobar.com`, `baz` will be considered for integrated authentication. Without `*` prefix the URL has to match exactly. ### --auth-negotiate-delegate-whitelist=`url` A comma-separated list of servers for which delegation of user credentials is required. Without `*` prefix the URL has to match exactly. ### --disable-ntlm-v2 Disables NTLM v2 for posix platforms, no effect elsewhere. ### --disable-http-cache Disables the disk cache for HTTP requests. ### --disable-http2 Disable HTTP/2 and SPDY/3.1 protocols. ### --disable-renderer-backgrounding Prevents Chromium from lowering the priority of invisible pages' renderer processes. This flag is global to all renderer processes, if you only want to disable throttling in one window, you can take the hack of [playing silent audio][play-silent-audio]. ### --disk-cache-size=`size` Forces the maximum disk space to be used by the disk cache, in bytes. ### --enable-logging\[=file] Prints Chromium's logging to stderr (or a log file). The `ELECTRON_ENABLE_LOGGING` environment variable has the same effect as passing `--enable-logging`. Passing `--enable-logging` will result in logs being printed on stderr. Passing `--enable-logging=file` will result in logs being saved to the file specified by `--log-file=...`, or to `electron_debug.log` in the user-data directory if `--log-file` is not specified. > **Note:** On Windows, logs from child processes cannot be sent to stderr. > Logging to a file is the most reliable way to collect logs on Windows. See also `--log-file`, `--log-level`, `--v`, and `--vmodule`. ### --force-fieldtrials=`trials` Field trials to be forcefully enabled or disabled. For example: `WebRTC-Audio-Red-For-Opus/Enabled/` ### --host-rules=`rules` A comma-separated list of `rules` that control how hostnames are mapped. For example: * `MAP * 127.0.0.1` Forces all hostnames to be mapped to 127.0.0.1 * `MAP *.google.com proxy` Forces all google.com subdomains to be resolved to "proxy". * `MAP test.com [::1]:77` Forces "test.com" to resolve to IPv6 loopback. Will also force the port of the resulting socket address to be 77. * `MAP * baz, EXCLUDE www.google.com` Remaps everything to "baz", except for "www.google.com". These mappings apply to the endpoint host in a net request (the TCP connect and host resolver in a direct connection, and the `CONNECT` in an HTTP proxy connection, and the endpoint host in a `SOCKS` proxy connection). ### --host-resolver-rules=`rules` Like `--host-rules` but these `rules` only apply to the host resolver. ### --ignore-certificate-errors Ignores certificate related errors. ### --ignore-connections-limit=`domains` Ignore the connections limit for `domains` list separated by `,`. ### --js-flags=`flags` Specifies the flags passed to the Node.js engine. It has to be passed when starting Electron if you want to enable the `flags` in the main process. ```sh $ electron --js-flags="--harmony_proxies --harmony_collections" your-app ``` See the [Node.js documentation][node-cli] or run `node --help` in your terminal for a list of available flags. Additionally, run `node --v8-options` to see a list of flags that specifically refer to Node.js's V8 JavaScript engine. ### --lang Set a custom locale. ### --log-file=`path` If `--enable-logging` is specified, logs will be written to the given path. The parent directory must exist. Setting the `ELECTRON_LOG_FILE` environment variable is equivalent to passing this flag. If both are present, the command-line switch takes precedence. ### --log-net-log=`path` Enables net log events to be saved and writes them to `path`. ### --log-level=`N` Sets the verbosity of logging when used together with `--enable-logging`. `N` should be one of [Chrome's LogSeverities][severities]. Note that two complimentary logging mechanisms in Chromium -- `LOG()` and `VLOG()` -- are controlled by different switches. `--log-level` controls `LOG()` messages, while `--v` and `--vmodule` control `VLOG()` messages. So you may want to use a combination of these three switches depending on the granularity you want and what logging calls are made by the code you're trying to watch. See [Chromium Logging source][logging] for more information on how `LOG()` and `VLOG()` interact. Loosely speaking, `VLOG()` can be thought of as sub-levels / per-module levels inside `LOG(INFO)` to control the firehose of `LOG(INFO)` data. See also `--enable-logging`, `--log-level`, `--v`, and `--vmodule`. ### --no-proxy-server Don't use a proxy server and always make direct connections. Overrides any other proxy server flags that are passed. ### --no-sandbox Disables the Chromium [sandbox](https://www.chromium.org/developers/design-documents/sandbox). Forces renderer process and Chromium helper processes to run un-sandboxed. Should only be used for testing. ### --proxy-bypass-list=`hosts` Instructs Electron to bypass the proxy server for the given semi-colon-separated list of hosts. This flag has an effect only if used in tandem with `--proxy-server`. For example: ```javascript const { app } = require('electron') app.commandLine.appendSwitch('proxy-bypass-list', '<local>;*.google.com;*foo.com;1.2.3.4:5678') ``` Will use the proxy server for all hosts except for local addresses (`localhost`, `127.0.0.1` etc.), `google.com` subdomains, hosts that contain the suffix `foo.com` and anything at `1.2.3.4:5678`. ### --proxy-pac-url=`url` Uses the PAC script at the specified `url`. ### --proxy-server=`address:port` Use a specified proxy server, which overrides the system setting. This switch only affects requests with HTTP protocol, including HTTPS and WebSocket requests. It is also noteworthy that not all proxy servers support HTTPS and WebSocket requests. The proxy URL does not support username and password authentication [per Chromium issue](https://bugs.chromium.org/p/chromium/issues/detail?id=615947). ### --remote-debugging-port=`port` Enables remote debugging over HTTP on the specified `port`. ### --v=`log_level` Gives the default maximal active V-logging level; 0 is the default. Normally positive values are used for V-logging levels. This switch only works when `--enable-logging` is also passed. See also `--enable-logging`, `--log-level`, and `--vmodule`. ### --vmodule=`pattern` Gives the per-module maximal V-logging levels to override the value given by `--v`. E.g. `my_module=2,foo*=3` would change the logging level for all code in source files `my_module.*` and `foo*.*`. Any pattern containing a forward or backward slash will be tested against the whole pathname and not only the module. E.g. `*/foo/bar/*=2` would change the logging level for all code in the source files under a `foo/bar` directory. This switch only works when `--enable-logging` is also passed. See also `--enable-logging`, `--log-level`, and `--v`. ### --force_high_performance_gpu Force using discrete GPU when there are multiple GPUs available. ### --force_low_power_gpu Force using integrated GPU when there are multiple GPUs available. ## Node.js Flags Electron supports some of the [CLI flags][node-cli] supported by Node.js. **Note:** Passing unsupported command line switches to Electron when it is not running in `ELECTRON_RUN_AS_NODE` will have no effect. ### --inspect-brk\[=\[host:]port] Activate inspector on host:port and break at start of user script. Default host:port is 127.0.0.1:9229. Aliased to `--debug-brk=[host:]port`. ### --inspect-port=\[host:]port Set the `host:port` to be used when the inspector is activated. Useful when activating the inspector by sending the SIGUSR1 signal. Default host is `127.0.0.1`. Aliased to `--debug-port=[host:]port`. ### --inspect\[=\[host:]port] Activate inspector on `host:port`. Default is `127.0.0.1:9229`. V8 inspector integration allows tools such as Chrome DevTools and IDEs to debug and profile Electron instances. The tools attach to Electron instances via a TCP port and communicate using the [Chrome DevTools Protocol](https://chromedevtools.github.io/devtools-protocol/). See the [Debugging the Main Process][debugging-main-process] guide for more details. Aliased to `--debug[=[host:]port`. ### --inspect-publish-uid=stderr,http Specify ways of the inspector web socket url exposure. By default inspector websocket url is available in stderr and under /json/list endpoint on http://host:port/json/list. [app]: app.md [append-switch]: command-line.md#commandlineappendswitchswitch-value [debugging-main-process]: ../tutorial/debugging-main-process.md [logging]: https://source.chromium.org/chromium/chromium/src/+/main:base/logging.h [node-cli]: https://nodejs.org/api/cli.html [play-silent-audio]: https://github.com/atom/atom/pull/9485/files [ready]: app.md#event-ready [severities]: https://source.chromium.org/chromium/chromium/src/+/main:base/logging.h?q=logging::LogSeverity&ss=chromium
closed
electron/electron
https://github.com/electron/electron
39,322
[Bug]: --trace-warnings option not doing anything
### 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 25.3.2 ### What operating system are you using? Other (specify below) ### Operating System Version any OS ### What arch are you using? Other (specify below) ### Last Known Working Electron version _No response_ ### Expected Behavior I expect to get some more information about warning when using `--trace-warnings` ### Actual Behavior Same behavior as without `--trace-warnings` ` "start": "electron --trace-warnings ."` ``` electron-quick-start git:(main) npm start > [email protected] start > electron . --trace-warnings (node:22471) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 window-all-closed listeners added to [App]. Use emitter.setMaxListeners() to increase limit (Use `electron --trace-warnings ...` to show where the warning was created) ``` ` "start": "electron ."` ``` electron-quick-start git:(main) ✗ npm start > [email protected] start > electron . (node:22616) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 window-all-closed listeners added to [App]. Use emitter.setMaxListeners() to increase limit (Use `electron --trace-warnings ...` to show where the warning was created) ``` ### Testcase Gist URL https://github.com/hovancik/electron-trace-warnings-isssue ### Additional Information _No response_
https://github.com/electron/electron/issues/39322
https://github.com/electron/electron/pull/39344
c5b9f766f373f4d403a8af2f75e28ca2d901cc32
2e0517c0addc05678e59906d91d72cc8f4860547
2023-08-01T15:47:31Z
c++
2023-08-04T10:59:40Z
shell/common/node_bindings.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/common/node_bindings.h" #include <algorithm> #include <string> #include <utility> #include <vector> #include "base/base_paths.h" #include "base/command_line.h" #include "base/containers/fixed_flat_set.h" #include "base/environment.h" #include "base/path_service.h" #include "base/run_loop.h" #include "base/strings/string_split.h" #include "base/strings/utf_string_conversions.h" #include "base/task/single_thread_task_runner.h" #include "base/trace_event/trace_event.h" #include "content/public/browser/browser_thread.h" #include "content/public/common/content_paths.h" #include "electron/buildflags/buildflags.h" #include "electron/fuses.h" #include "shell/browser/api/electron_api_app.h" #include "shell/common/api/electron_bindings.h" #include "shell/common/electron_command_line.h" #include "shell/common/gin_converters/file_path_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/gin_helper/event.h" #include "shell/common/gin_helper/event_emitter_caller.h" #include "shell/common/gin_helper/locker.h" #include "shell/common/gin_helper/microtasks_scope.h" #include "shell/common/mac/main_application_bundle.h" #include "third_party/blink/renderer/bindings/core/v8/v8_initializer.h" // nogncheck #include "third_party/electron_node/src/debug_utils.h" #if !IS_MAS_BUILD() #include "shell/common/crash_keys.h" #endif #define ELECTRON_BROWSER_BINDINGS(V) \ V(electron_browser_app) \ V(electron_browser_auto_updater) \ V(electron_browser_browser_view) \ V(electron_browser_content_tracing) \ V(electron_browser_crash_reporter) \ V(electron_browser_desktop_capturer) \ V(electron_browser_dialog) \ V(electron_browser_event_emitter) \ V(electron_browser_global_shortcut) \ V(electron_browser_in_app_purchase) \ V(electron_browser_menu) \ V(electron_browser_message_port) \ V(electron_browser_native_theme) \ V(electron_browser_net) \ V(electron_browser_notification) \ V(electron_browser_power_monitor) \ V(electron_browser_power_save_blocker) \ V(electron_browser_protocol) \ V(electron_browser_printing) \ V(electron_browser_push_notifications) \ V(electron_browser_safe_storage) \ V(electron_browser_session) \ V(electron_browser_screen) \ V(electron_browser_system_preferences) \ V(electron_browser_base_window) \ V(electron_browser_tray) \ V(electron_browser_utility_process) \ V(electron_browser_view) \ V(electron_browser_web_contents) \ V(electron_browser_web_contents_view) \ V(electron_browser_web_frame_main) \ V(electron_browser_web_view_manager) \ V(electron_browser_window) #define ELECTRON_COMMON_BINDINGS(V) \ V(electron_common_asar) \ V(electron_common_clipboard) \ V(electron_common_command_line) \ V(electron_common_crashpad_support) \ V(electron_common_environment) \ V(electron_common_features) \ V(electron_common_native_image) \ V(electron_common_shell) \ V(electron_common_v8_util) #define ELECTRON_RENDERER_BINDINGS(V) \ V(electron_renderer_context_bridge) \ V(electron_renderer_crash_reporter) \ V(electron_renderer_ipc) \ V(electron_renderer_web_frame) #define ELECTRON_UTILITY_BINDINGS(V) V(electron_utility_parent_port) #define ELECTRON_VIEWS_BINDINGS(V) V(electron_browser_image_view) #define ELECTRON_TESTING_BINDINGS(V) V(electron_common_testing) // This is used to load built-in bindings. Instead of using // __attribute__((constructor)), we call the _register_<modname> // function for each built-in bindings explicitly. This is only // forward declaration. The definitions are in each binding's // implementation when calling the NODE_LINKED_BINDING_CONTEXT_AWARE. #define V(modname) void _register_##modname(); ELECTRON_BROWSER_BINDINGS(V) ELECTRON_COMMON_BINDINGS(V) ELECTRON_RENDERER_BINDINGS(V) ELECTRON_UTILITY_BINDINGS(V) #if BUILDFLAG(ENABLE_VIEWS_API) ELECTRON_VIEWS_BINDINGS(V) #endif #if DCHECK_IS_ON() ELECTRON_TESTING_BINDINGS(V) #endif #undef V namespace { void stop_and_close_uv_loop(uv_loop_t* loop) { uv_stop(loop); auto const ensure_closing = [](uv_handle_t* handle, void*) { // We should be using the UvHandle wrapper everywhere, in which case // all handles should already be in a closing state... DCHECK(uv_is_closing(handle)); // ...but if a raw handle got through, through, do the right thing anyway if (!uv_is_closing(handle)) { uv_close(handle, nullptr); } }; uv_walk(loop, ensure_closing, nullptr); // All remaining handles are in a closing state now. // Pump the event loop so that they can finish closing. for (;;) if (uv_run(loop, UV_RUN_DEFAULT) == 0) break; DCHECK_EQ(0, uv_loop_alive(loop)); node::CheckedUvLoopClose(loop); } bool g_is_initialized = false; void V8FatalErrorCallback(const char* location, const char* message) { LOG(ERROR) << "Fatal error in V8: " << location << " " << message; #if !IS_MAS_BUILD() electron::crash_keys::SetCrashKey("electron.v8-fatal.message", message); electron::crash_keys::SetCrashKey("electron.v8-fatal.location", location); #endif volatile int* zero = nullptr; *zero = 0; } bool AllowWasmCodeGenerationCallback(v8::Local<v8::Context> context, v8::Local<v8::String> source) { // If we're running with contextIsolation enabled in the renderer process, // fall back to Blink's logic. if (node::Environment::GetCurrent(context) == nullptr) { if (!electron::IsRendererProcess()) return false; return blink::V8Initializer::WasmCodeGenerationCheckCallbackInMainThread( context, source); } return node::AllowWasmCodeGenerationCallback(context, source); } v8::ModifyCodeGenerationFromStringsResult ModifyCodeGenerationFromStrings( v8::Local<v8::Context> context, v8::Local<v8::Value> source, bool is_code_like) { if (node::Environment::GetCurrent(context) == nullptr) { // No node environment means we're in the renderer process, either in a // sandboxed renderer or in an unsandboxed renderer with context isolation // enabled. if (!electron::IsRendererProcess()) { NOTREACHED(); return {false, {}}; } return blink::V8Initializer::CodeGenerationCheckCallbackInMainThread( context, source, is_code_like); } // If we get here then we have a node environment, so either a) we're in the // non-rendrer process, or b) we're in the renderer process in a context that // has both node and blink, i.e. contextIsolation disabled. // If we're in the renderer with contextIsolation disabled, ask blink first // (for CSP), and iff that allows codegen, delegate to node. if (electron::IsRendererProcess()) { v8::ModifyCodeGenerationFromStringsResult result = blink::V8Initializer::CodeGenerationCheckCallbackInMainThread( context, source, is_code_like); if (!result.codegen_allowed) return result; } // If we're in the main process or utility process, delegate to node. return node::ModifyCodeGenerationFromStrings(context, source, is_code_like); } void ErrorMessageListener(v8::Local<v8::Message> message, v8::Local<v8::Value> data) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); node::Environment* env = node::Environment::GetCurrent(isolate); if (env) { gin_helper::MicrotasksScope microtasks_scope( isolate, env->context()->GetMicrotaskQueue(), v8::MicrotasksScope::kDoNotRunMicrotasks); // Emit the after() hooks now that the exception has been handled. // Analogous to node/lib/internal/process/execution.js#L176-L180 if (env->async_hooks()->fields()[node::AsyncHooks::kAfter]) { while (env->async_hooks()->fields()[node::AsyncHooks::kStackLength]) { node::AsyncWrap::EmitAfter(env, env->execution_async_id()); env->async_hooks()->pop_async_context(env->execution_async_id()); } } // Ensure that the async id stack is properly cleared so the async // hook stack does not become corrupted. env->async_hooks()->clear_async_id_stack(); } } // Only allow DebugOptions in non-ELECTRON_RUN_AS_NODE mode. // If node CLI inspect support is disabled, allow no debug options. bool IsAllowedDebugOption(base::StringPiece option) { static constexpr auto options = base::MakeFixedFlatSet<base::StringPiece>({ "--debug", "--debug-brk", "--debug-port", "--inspect", "--inspect-brk", "--inspect-brk-node", "--inspect-port", "--inspect-publish-uid", }); return electron::fuses::IsNodeCliInspectEnabled() && options.contains(option); } // Initialize NODE_OPTIONS to pass to Node.js // See https://nodejs.org/api/cli.html#cli_node_options_options void SetNodeOptions(base::Environment* env) { // Options that are unilaterally disallowed static constexpr auto disallowed = base::MakeFixedFlatSet<base::StringPiece>({ "--enable-fips", "--force-fips", "--openssl-config", "--use-bundled-ca", "--use-openssl-ca", }); static constexpr auto pkg_opts = base::MakeFixedFlatSet<base::StringPiece>({ "--http-parser", "--max-http-header-size", }); if (env->HasVar("NODE_OPTIONS")) { if (electron::fuses::IsNodeOptionsEnabled()) { std::string options; env->GetVar("NODE_OPTIONS", &options); std::vector<std::string> parts = base::SplitString( options, " ", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY); bool is_packaged_app = electron::api::App::IsPackaged(); for (const auto& part : parts) { // Strip off values passed to individual NODE_OPTIONs std::string option = part.substr(0, part.find('=')); if (is_packaged_app && !pkg_opts.contains(option)) { // Explicitly disallow majority of NODE_OPTIONS in packaged apps LOG(ERROR) << "Most NODE_OPTIONs are not supported in packaged apps." << " See documentation for more details."; options.erase(options.find(option), part.length()); } else if (disallowed.contains(option)) { // Remove NODE_OPTIONS specifically disallowed for use in Node.js // through Electron owing to constraints like BoringSSL. LOG(ERROR) << "The NODE_OPTION " << option << " is not supported in Electron"; options.erase(options.find(option), part.length()); } } // overwrite new NODE_OPTIONS without unsupported variables env->SetVar("NODE_OPTIONS", options); } else { LOG(ERROR) << "NODE_OPTIONS have been disabled in this app"; env->SetVar("NODE_OPTIONS", ""); } } } } // namespace namespace electron { namespace { base::FilePath GetResourcesPath() { #if BUILDFLAG(IS_MAC) return MainApplicationBundlePath().Append("Contents").Append("Resources"); #else auto* command_line = base::CommandLine::ForCurrentProcess(); base::FilePath exec_path(command_line->GetProgram()); base::PathService::Get(base::FILE_EXE, &exec_path); return exec_path.DirName().Append(FILE_PATH_LITERAL("resources")); #endif } } // namespace NodeBindings::NodeBindings(BrowserEnvironment browser_env) : browser_env_(browser_env) { if (browser_env == BrowserEnvironment::kWorker) { uv_loop_init(&worker_loop_); uv_loop_ = &worker_loop_; } else { uv_loop_ = uv_default_loop(); } // Interrupt embed polling when a handle is started. uv_loop_configure(uv_loop_, UV_LOOP_INTERRUPT_ON_IO_CHANGE); } NodeBindings::~NodeBindings() { // Quit the embed thread. embed_closed_ = true; uv_sem_post(&embed_sem_); WakeupEmbedThread(); // Wait for everything to be done. uv_thread_join(&embed_thread_); // Clear uv. uv_sem_destroy(&embed_sem_); dummy_uv_handle_.reset(); // Clean up worker loop if (in_worker_loop()) stop_and_close_uv_loop(uv_loop_); } void NodeBindings::RegisterBuiltinBindings() { #define V(modname) _register_##modname(); if (IsBrowserProcess()) { ELECTRON_BROWSER_BINDINGS(V) #if BUILDFLAG(ENABLE_VIEWS_API) ELECTRON_VIEWS_BINDINGS(V) #endif } ELECTRON_COMMON_BINDINGS(V) if (IsRendererProcess()) { ELECTRON_RENDERER_BINDINGS(V) } if (IsUtilityProcess()) { ELECTRON_UTILITY_BINDINGS(V) } #if DCHECK_IS_ON() ELECTRON_TESTING_BINDINGS(V) #endif #undef V } bool NodeBindings::IsInitialized() { return g_is_initialized; } // Initialize Node.js cli options to pass to Node.js // See https://nodejs.org/api/cli.html#cli_options void NodeBindings::SetNodeCliFlags() { const auto argv = base::CommandLine::ForCurrentProcess()->argv(); std::vector<std::string> args; // TODO(codebytere): We need to set the first entry in args to the // process name owing to src/node_options-inl.h#L286-L290 but this is // redundant and so should be refactored upstream. args.reserve(argv.size() + 1); args.emplace_back("electron"); for (const auto& arg : argv) { #if BUILDFLAG(IS_WIN) const auto& option = base::WideToUTF8(arg); #else const auto& option = arg; #endif const auto stripped = base::StringPiece(option).substr(0, option.find('=')); // Only allow in no-op (--) option or DebugOptions if (IsAllowedDebugOption(stripped) || stripped == "--") args.push_back(option); } // We need to disable Node.js' fetch implementation to prevent // conflict with Blink's in renderer and worker processes. if (browser_env_ == BrowserEnvironment::kRenderer || browser_env_ == BrowserEnvironment::kWorker) { args.push_back("--no-experimental-fetch"); } std::vector<std::string> errors; const int exit_code = ProcessGlobalArgs(&args, nullptr, &errors, node::kDisallowedInEnvironment); const std::string err_str = "Error parsing Node.js cli flags "; if (exit_code != 0) { LOG(ERROR) << err_str; } else if (!errors.empty()) { LOG(ERROR) << err_str << base::JoinString(errors, " "); } } void NodeBindings::Initialize(v8::Local<v8::Context> context) { TRACE_EVENT0("electron", "NodeBindings::Initialize"); // Open node's error reporting system for browser process. #if BUILDFLAG(IS_LINUX) // Get real command line in renderer process forked by zygote. if (browser_env_ != BrowserEnvironment::kBrowser) ElectronCommandLine::InitializeFromCommandLine(); #endif // Explicitly register electron's builtin bindings. RegisterBuiltinBindings(); // Parse and set Node.js cli flags. SetNodeCliFlags(); auto env = base::Environment::Create(); SetNodeOptions(env.get()); std::vector<std::string> argv = {"electron"}; std::vector<std::string> exec_argv; std::vector<std::string> errors; uint64_t process_flags = node::ProcessFlags::kNoFlags; // We do not want the child processes spawned from the utility process // to inherit the custom stdio handles created for the parent. if (browser_env_ != BrowserEnvironment::kUtility) process_flags |= node::ProcessFlags::kEnableStdioInheritance; if (!fuses::IsNodeOptionsEnabled()) process_flags |= node::ProcessFlags::kDisableNodeOptionsEnv; int exit_code = node::InitializeNodeWithArgs( &argv, &exec_argv, &errors, static_cast<node::ProcessFlags::Flags>(process_flags)); for (const std::string& error : errors) fprintf(stderr, "%s: %s\n", argv[0].c_str(), error.c_str()); if (exit_code != 0) exit(exit_code); #if BUILDFLAG(IS_WIN) // uv_init overrides error mode to suppress the default crash dialog, bring // it back if user wants to show it. if (browser_env_ == BrowserEnvironment::kBrowser || env->HasVar("ELECTRON_DEFAULT_ERROR_MODE")) SetErrorMode(GetErrorMode() & ~SEM_NOGPFAULTERRORBOX); #endif gin_helper::internal::Event::GetConstructor(context); g_is_initialized = true; } node::Environment* NodeBindings::CreateEnvironment( v8::Handle<v8::Context> context, node::MultiIsolatePlatform* platform, std::vector<std::string> args, std::vector<std::string> exec_args) { // Feed node the path to initialization script. std::string process_type; switch (browser_env_) { case BrowserEnvironment::kBrowser: process_type = "browser"; break; case BrowserEnvironment::kRenderer: process_type = "renderer"; break; case BrowserEnvironment::kWorker: process_type = "worker"; break; case BrowserEnvironment::kUtility: process_type = "utility"; break; } v8::Isolate* isolate = context->GetIsolate(); gin_helper::Dictionary global(isolate, context->Global()); if (browser_env_ == BrowserEnvironment::kBrowser) { const std::vector<std::string> search_paths = {"app.asar", "app", "default_app.asar"}; const std::vector<std::string> app_asar_search_paths = {"app.asar"}; context->Global()->SetPrivate( context, v8::Private::ForApi( isolate, gin::ConvertToV8(isolate, "appSearchPaths").As<v8::String>()), gin::ConvertToV8(isolate, electron::fuses::IsOnlyLoadAppFromAsarEnabled() ? app_asar_search_paths : search_paths)); } base::FilePath resources_path = GetResourcesPath(); std::string init_script = "electron/js2c/" + process_type + "_init"; args.insert(args.begin() + 1, init_script); auto* isolate_data = node::CreateIsolateData(isolate, uv_loop_, platform); context->SetAlignedPointerInEmbedderData(kElectronContextEmbedderDataIndex, static_cast<void*>(isolate_data)); node::Environment* env; uint64_t flags = node::EnvironmentFlags::kDefaultFlags | node::EnvironmentFlags::kHideConsoleWindows | node::EnvironmentFlags::kNoGlobalSearchPaths; if (browser_env_ == BrowserEnvironment::kRenderer || browser_env_ == BrowserEnvironment::kWorker) { // Only one ESM loader can be registered per isolate - // in renderer processes this should be blink. We need to tell Node.js // not to register its handler (overriding blinks) in non-browser processes. // We also avoid overriding globals like setImmediate, clearImmediate // queueMicrotask etc during the bootstrap phase of Node.js // for processes that already have these defined by DOM. // Check //third_party/electron_node/lib/internal/bootstrap/node.js // for the list of overrides on globalThis. flags |= node::EnvironmentFlags::kNoRegisterESMLoader | node::EnvironmentFlags::kNoBrowserGlobals | node::EnvironmentFlags::kNoCreateInspector; } if (!electron::fuses::IsNodeCliInspectEnabled()) { // If --inspect and friends are disabled we also shouldn't listen for // SIGUSR1 flags |= node::EnvironmentFlags::kNoStartDebugSignalHandler; } { v8::TryCatch try_catch(isolate); env = node::CreateEnvironment( static_cast<node::IsolateData*>(isolate_data), context, args, exec_args, static_cast<node::EnvironmentFlags::Flags>(flags)); if (try_catch.HasCaught()) { std::string err_msg = "Failed to initialize node environment in process: " + process_type; v8::Local<v8::Message> message = try_catch.Message(); std::string msg; if (!message.IsEmpty() && gin::ConvertFromV8(isolate, message->Get(), &msg)) err_msg += " , with error: " + msg; LOG(ERROR) << err_msg; } } DCHECK(env); node::IsolateSettings is; // Use a custom fatal error callback to allow us to add // crash message and location to CrashReports. is.fatal_error_callback = V8FatalErrorCallback; // We don't want to abort either in the renderer or browser processes. // We already listen for uncaught exceptions and handle them there. // For utility process we expect the process to behave as standard // Node.js runtime and abort the process with appropriate exit // code depending on a handler being set for `uncaughtException` event. if (browser_env_ != BrowserEnvironment::kUtility) { is.should_abort_on_uncaught_exception_callback = [](v8::Isolate*) { return false; }; } // Use a custom callback here to allow us to leverage Blink's logic in the // renderer process. is.allow_wasm_code_generation_callback = AllowWasmCodeGenerationCallback; is.flags |= node::IsolateSettingsFlags:: ALLOW_MODIFY_CODE_GENERATION_FROM_STRINGS_CALLBACK; is.modify_code_generation_from_strings_callback = ModifyCodeGenerationFromStrings; if (browser_env_ == BrowserEnvironment::kBrowser || browser_env_ == BrowserEnvironment::kUtility) { // Node.js requires that microtask checkpoints be explicitly invoked. is.policy = v8::MicrotasksPolicy::kExplicit; } else { // Blink expects the microtasks policy to be kScoped, but Node.js expects it // to be kExplicit. In the renderer, there can be many contexts within the // same isolate, so we don't want to change the existing policy here, which // could be either kExplicit or kScoped depending on whether we're executing // from within a Node.js or a Blink entrypoint. Instead, the policy is // toggled to kExplicit when entering Node.js through UvRunOnce. is.policy = context->GetIsolate()->GetMicrotasksPolicy(); // We do not want to use Node.js' message listener as it interferes with // Blink's. is.flags &= ~node::IsolateSettingsFlags::MESSAGE_LISTENER_WITH_ERROR_LEVEL; // Isolate message listeners are additive (you can add multiple), so instead // we add an extra one here to ensure that the async hook stack is properly // cleared when errors are thrown. context->GetIsolate()->AddMessageListenerWithErrorLevel( ErrorMessageListener, v8::Isolate::kMessageError); // We do not want to use the promise rejection callback that Node.js uses, // because it does not send PromiseRejectionEvents to the global script // context. We need to use the one Blink already provides. is.flags |= node::IsolateSettingsFlags::SHOULD_NOT_SET_PROMISE_REJECTION_CALLBACK; // We do not want to use the stack trace callback that Node.js uses, // because it relies on Node.js being aware of the current Context and // that's not always the case. We need to use the one Blink already // provides. is.flags |= node::IsolateSettingsFlags::SHOULD_NOT_SET_PREPARE_STACK_TRACE_CALLBACK; } node::SetIsolateUpForNode(context->GetIsolate(), is); gin_helper::Dictionary process(context->GetIsolate(), env->process_object()); process.SetReadOnly("type", process_type); process.Set("resourcesPath", resources_path); // The path to helper app. base::FilePath helper_exec_path; base::PathService::Get(content::CHILD_PROCESS_EXE, &helper_exec_path); process.Set("helperExecPath", helper_exec_path); return env; } node::Environment* NodeBindings::CreateEnvironment( v8::Handle<v8::Context> context, node::MultiIsolatePlatform* platform) { #if BUILDFLAG(IS_WIN) auto& electron_args = ElectronCommandLine::argv(); std::vector<std::string> args(electron_args.size()); std::transform(electron_args.cbegin(), electron_args.cend(), args.begin(), [](auto& a) { return base::WideToUTF8(a); }); #else auto args = ElectronCommandLine::argv(); #endif return CreateEnvironment(context, platform, args, {}); } void NodeBindings::LoadEnvironment(node::Environment* env) { node::LoadEnvironment(env, node::StartExecutionCallback{}); gin_helper::EmitEvent(env->isolate(), env->process_object(), "loaded"); } void NodeBindings::PrepareEmbedThread() { // IOCP does not change for the process until the loop is recreated, // we ensure that there is only a single polling thread satisfying // the concurrency limit set from CreateIoCompletionPort call by // uv_loop_init for the lifetime of this process. // More background can be found at: // https://github.com/microsoft/vscode/issues/142786#issuecomment-1061673400 if (initialized_) return; // Add dummy handle for libuv, otherwise libuv would quit when there is // nothing to do. uv_async_init(uv_loop_, dummy_uv_handle_.get(), nullptr); // Start worker that will interrupt main loop when having uv events. uv_sem_init(&embed_sem_, 0); uv_thread_create(&embed_thread_, EmbedThreadRunner, this); } void NodeBindings::StartPolling() { // Avoid calling UvRunOnce if the loop is already active, // otherwise it can lead to situations were the number of active // threads processing on IOCP is greater than the concurrency limit. if (initialized_) return; initialized_ = true; // The MessageLoop should have been created, remember the one in main thread. task_runner_ = base::SingleThreadTaskRunner::GetCurrentDefault(); // Run uv loop for once to give the uv__io_poll a chance to add all events. UvRunOnce(); } void NodeBindings::UvRunOnce() { node::Environment* env = uv_env(); // When doing navigation without restarting renderer process, it may happen // that the node environment is destroyed but the message loop is still there. // In this case we should not run uv loop. if (!env) return; v8::HandleScope handle_scope(env->isolate()); // Enter node context while dealing with uv events. v8::Context::Scope context_scope(env->context()); // Node.js expects `kExplicit` microtasks policy and will run microtasks // checkpoints after every call into JavaScript. Since we use a different // policy in the renderer - switch to `kExplicit` and then drop back to the // previous policy value. v8::MicrotaskQueue* microtask_queue = env->context()->GetMicrotaskQueue(); auto old_policy = microtask_queue->microtasks_policy(); DCHECK_EQ(microtask_queue->GetMicrotasksScopeDepth(), 0); microtask_queue->set_microtasks_policy(v8::MicrotasksPolicy::kExplicit); if (browser_env_ != BrowserEnvironment::kBrowser) TRACE_EVENT_BEGIN0("devtools.timeline", "FunctionCall"); // Deal with uv events. int r = uv_run(uv_loop_, UV_RUN_NOWAIT); if (browser_env_ != BrowserEnvironment::kBrowser) TRACE_EVENT_END0("devtools.timeline", "FunctionCall"); microtask_queue->set_microtasks_policy(old_policy); if (r == 0) base::RunLoop().QuitWhenIdle(); // Quit from uv. // Tell the worker thread to continue polling. uv_sem_post(&embed_sem_); } void NodeBindings::WakeupMainThread() { DCHECK(task_runner_); task_runner_->PostTask(FROM_HERE, base::BindOnce(&NodeBindings::UvRunOnce, weak_factory_.GetWeakPtr())); } void NodeBindings::WakeupEmbedThread() { uv_async_send(dummy_uv_handle_.get()); } // static void NodeBindings::EmbedThreadRunner(void* arg) { auto* self = static_cast<NodeBindings*>(arg); while (true) { // Wait for the main loop to deal with events. uv_sem_wait(&self->embed_sem_); if (self->embed_closed_) break; // Wait for something to happen in uv loop. // Note that the PollEvents() is implemented by derived classes, so when // this class is being destructed the PollEvents() would not be available // anymore. Because of it we must make sure we only invoke PollEvents() // when this class is alive. self->PollEvents(); if (self->embed_closed_) break; // Deal with event in main thread. self->WakeupMainThread(); } } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
39,322
[Bug]: --trace-warnings option not doing anything
### 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 25.3.2 ### What operating system are you using? Other (specify below) ### Operating System Version any OS ### What arch are you using? Other (specify below) ### Last Known Working Electron version _No response_ ### Expected Behavior I expect to get some more information about warning when using `--trace-warnings` ### Actual Behavior Same behavior as without `--trace-warnings` ` "start": "electron --trace-warnings ."` ``` electron-quick-start git:(main) npm start > [email protected] start > electron . --trace-warnings (node:22471) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 window-all-closed listeners added to [App]. Use emitter.setMaxListeners() to increase limit (Use `electron --trace-warnings ...` to show where the warning was created) ``` ` "start": "electron ."` ``` electron-quick-start git:(main) ✗ npm start > [email protected] start > electron . (node:22616) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 window-all-closed listeners added to [App]. Use emitter.setMaxListeners() to increase limit (Use `electron --trace-warnings ...` to show where the warning was created) ``` ### Testcase Gist URL https://github.com/hovancik/electron-trace-warnings-isssue ### Additional Information _No response_
https://github.com/electron/electron/issues/39322
https://github.com/electron/electron/pull/39344
c5b9f766f373f4d403a8af2f75e28ca2d901cc32
2e0517c0addc05678e59906d91d72cc8f4860547
2023-08-01T15:47:31Z
c++
2023-08-04T10:59:40Z
docs/api/command-line-switches.md
# Supported Command Line Switches > Command line switches supported by Electron. You can use [app.commandLine.appendSwitch][append-switch] to append them in your app's main script before the [ready][ready] event of the [app][app] module is emitted: ```javascript const { app } = require('electron') app.commandLine.appendSwitch('remote-debugging-port', '8315') app.commandLine.appendSwitch('host-rules', 'MAP * 127.0.0.1') app.whenReady().then(() => { // Your code here }) ``` ## Electron CLI Flags ### --auth-server-whitelist=`url` A comma-separated list of servers for which integrated authentication is enabled. For example: ```sh --auth-server-whitelist='*example.com, *foobar.com, *baz' ``` then any `url` ending with `example.com`, `foobar.com`, `baz` will be considered for integrated authentication. Without `*` prefix the URL has to match exactly. ### --auth-negotiate-delegate-whitelist=`url` A comma-separated list of servers for which delegation of user credentials is required. Without `*` prefix the URL has to match exactly. ### --disable-ntlm-v2 Disables NTLM v2 for posix platforms, no effect elsewhere. ### --disable-http-cache Disables the disk cache for HTTP requests. ### --disable-http2 Disable HTTP/2 and SPDY/3.1 protocols. ### --disable-renderer-backgrounding Prevents Chromium from lowering the priority of invisible pages' renderer processes. This flag is global to all renderer processes, if you only want to disable throttling in one window, you can take the hack of [playing silent audio][play-silent-audio]. ### --disk-cache-size=`size` Forces the maximum disk space to be used by the disk cache, in bytes. ### --enable-logging\[=file] Prints Chromium's logging to stderr (or a log file). The `ELECTRON_ENABLE_LOGGING` environment variable has the same effect as passing `--enable-logging`. Passing `--enable-logging` will result in logs being printed on stderr. Passing `--enable-logging=file` will result in logs being saved to the file specified by `--log-file=...`, or to `electron_debug.log` in the user-data directory if `--log-file` is not specified. > **Note:** On Windows, logs from child processes cannot be sent to stderr. > Logging to a file is the most reliable way to collect logs on Windows. See also `--log-file`, `--log-level`, `--v`, and `--vmodule`. ### --force-fieldtrials=`trials` Field trials to be forcefully enabled or disabled. For example: `WebRTC-Audio-Red-For-Opus/Enabled/` ### --host-rules=`rules` A comma-separated list of `rules` that control how hostnames are mapped. For example: * `MAP * 127.0.0.1` Forces all hostnames to be mapped to 127.0.0.1 * `MAP *.google.com proxy` Forces all google.com subdomains to be resolved to "proxy". * `MAP test.com [::1]:77` Forces "test.com" to resolve to IPv6 loopback. Will also force the port of the resulting socket address to be 77. * `MAP * baz, EXCLUDE www.google.com` Remaps everything to "baz", except for "www.google.com". These mappings apply to the endpoint host in a net request (the TCP connect and host resolver in a direct connection, and the `CONNECT` in an HTTP proxy connection, and the endpoint host in a `SOCKS` proxy connection). ### --host-resolver-rules=`rules` Like `--host-rules` but these `rules` only apply to the host resolver. ### --ignore-certificate-errors Ignores certificate related errors. ### --ignore-connections-limit=`domains` Ignore the connections limit for `domains` list separated by `,`. ### --js-flags=`flags` Specifies the flags passed to the Node.js engine. It has to be passed when starting Electron if you want to enable the `flags` in the main process. ```sh $ electron --js-flags="--harmony_proxies --harmony_collections" your-app ``` See the [Node.js documentation][node-cli] or run `node --help` in your terminal for a list of available flags. Additionally, run `node --v8-options` to see a list of flags that specifically refer to Node.js's V8 JavaScript engine. ### --lang Set a custom locale. ### --log-file=`path` If `--enable-logging` is specified, logs will be written to the given path. The parent directory must exist. Setting the `ELECTRON_LOG_FILE` environment variable is equivalent to passing this flag. If both are present, the command-line switch takes precedence. ### --log-net-log=`path` Enables net log events to be saved and writes them to `path`. ### --log-level=`N` Sets the verbosity of logging when used together with `--enable-logging`. `N` should be one of [Chrome's LogSeverities][severities]. Note that two complimentary logging mechanisms in Chromium -- `LOG()` and `VLOG()` -- are controlled by different switches. `--log-level` controls `LOG()` messages, while `--v` and `--vmodule` control `VLOG()` messages. So you may want to use a combination of these three switches depending on the granularity you want and what logging calls are made by the code you're trying to watch. See [Chromium Logging source][logging] for more information on how `LOG()` and `VLOG()` interact. Loosely speaking, `VLOG()` can be thought of as sub-levels / per-module levels inside `LOG(INFO)` to control the firehose of `LOG(INFO)` data. See also `--enable-logging`, `--log-level`, `--v`, and `--vmodule`. ### --no-proxy-server Don't use a proxy server and always make direct connections. Overrides any other proxy server flags that are passed. ### --no-sandbox Disables the Chromium [sandbox](https://www.chromium.org/developers/design-documents/sandbox). Forces renderer process and Chromium helper processes to run un-sandboxed. Should only be used for testing. ### --proxy-bypass-list=`hosts` Instructs Electron to bypass the proxy server for the given semi-colon-separated list of hosts. This flag has an effect only if used in tandem with `--proxy-server`. For example: ```javascript const { app } = require('electron') app.commandLine.appendSwitch('proxy-bypass-list', '<local>;*.google.com;*foo.com;1.2.3.4:5678') ``` Will use the proxy server for all hosts except for local addresses (`localhost`, `127.0.0.1` etc.), `google.com` subdomains, hosts that contain the suffix `foo.com` and anything at `1.2.3.4:5678`. ### --proxy-pac-url=`url` Uses the PAC script at the specified `url`. ### --proxy-server=`address:port` Use a specified proxy server, which overrides the system setting. This switch only affects requests with HTTP protocol, including HTTPS and WebSocket requests. It is also noteworthy that not all proxy servers support HTTPS and WebSocket requests. The proxy URL does not support username and password authentication [per Chromium issue](https://bugs.chromium.org/p/chromium/issues/detail?id=615947). ### --remote-debugging-port=`port` Enables remote debugging over HTTP on the specified `port`. ### --v=`log_level` Gives the default maximal active V-logging level; 0 is the default. Normally positive values are used for V-logging levels. This switch only works when `--enable-logging` is also passed. See also `--enable-logging`, `--log-level`, and `--vmodule`. ### --vmodule=`pattern` Gives the per-module maximal V-logging levels to override the value given by `--v`. E.g. `my_module=2,foo*=3` would change the logging level for all code in source files `my_module.*` and `foo*.*`. Any pattern containing a forward or backward slash will be tested against the whole pathname and not only the module. E.g. `*/foo/bar/*=2` would change the logging level for all code in the source files under a `foo/bar` directory. This switch only works when `--enable-logging` is also passed. See also `--enable-logging`, `--log-level`, and `--v`. ### --force_high_performance_gpu Force using discrete GPU when there are multiple GPUs available. ### --force_low_power_gpu Force using integrated GPU when there are multiple GPUs available. ## Node.js Flags Electron supports some of the [CLI flags][node-cli] supported by Node.js. **Note:** Passing unsupported command line switches to Electron when it is not running in `ELECTRON_RUN_AS_NODE` will have no effect. ### --inspect-brk\[=\[host:]port] Activate inspector on host:port and break at start of user script. Default host:port is 127.0.0.1:9229. Aliased to `--debug-brk=[host:]port`. ### --inspect-port=\[host:]port Set the `host:port` to be used when the inspector is activated. Useful when activating the inspector by sending the SIGUSR1 signal. Default host is `127.0.0.1`. Aliased to `--debug-port=[host:]port`. ### --inspect\[=\[host:]port] Activate inspector on `host:port`. Default is `127.0.0.1:9229`. V8 inspector integration allows tools such as Chrome DevTools and IDEs to debug and profile Electron instances. The tools attach to Electron instances via a TCP port and communicate using the [Chrome DevTools Protocol](https://chromedevtools.github.io/devtools-protocol/). See the [Debugging the Main Process][debugging-main-process] guide for more details. Aliased to `--debug[=[host:]port`. ### --inspect-publish-uid=stderr,http Specify ways of the inspector web socket url exposure. By default inspector websocket url is available in stderr and under /json/list endpoint on http://host:port/json/list. [app]: app.md [append-switch]: command-line.md#commandlineappendswitchswitch-value [debugging-main-process]: ../tutorial/debugging-main-process.md [logging]: https://source.chromium.org/chromium/chromium/src/+/main:base/logging.h [node-cli]: https://nodejs.org/api/cli.html [play-silent-audio]: https://github.com/atom/atom/pull/9485/files [ready]: app.md#event-ready [severities]: https://source.chromium.org/chromium/chromium/src/+/main:base/logging.h?q=logging::LogSeverity&ss=chromium
closed
electron/electron
https://github.com/electron/electron
39,322
[Bug]: --trace-warnings option not doing anything
### 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 25.3.2 ### What operating system are you using? Other (specify below) ### Operating System Version any OS ### What arch are you using? Other (specify below) ### Last Known Working Electron version _No response_ ### Expected Behavior I expect to get some more information about warning when using `--trace-warnings` ### Actual Behavior Same behavior as without `--trace-warnings` ` "start": "electron --trace-warnings ."` ``` electron-quick-start git:(main) npm start > [email protected] start > electron . --trace-warnings (node:22471) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 window-all-closed listeners added to [App]. Use emitter.setMaxListeners() to increase limit (Use `electron --trace-warnings ...` to show where the warning was created) ``` ` "start": "electron ."` ``` electron-quick-start git:(main) ✗ npm start > [email protected] start > electron . (node:22616) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 window-all-closed listeners added to [App]. Use emitter.setMaxListeners() to increase limit (Use `electron --trace-warnings ...` to show where the warning was created) ``` ### Testcase Gist URL https://github.com/hovancik/electron-trace-warnings-isssue ### Additional Information _No response_
https://github.com/electron/electron/issues/39322
https://github.com/electron/electron/pull/39344
c5b9f766f373f4d403a8af2f75e28ca2d901cc32
2e0517c0addc05678e59906d91d72cc8f4860547
2023-08-01T15:47:31Z
c++
2023-08-04T10:59:40Z
shell/common/node_bindings.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/common/node_bindings.h" #include <algorithm> #include <string> #include <utility> #include <vector> #include "base/base_paths.h" #include "base/command_line.h" #include "base/containers/fixed_flat_set.h" #include "base/environment.h" #include "base/path_service.h" #include "base/run_loop.h" #include "base/strings/string_split.h" #include "base/strings/utf_string_conversions.h" #include "base/task/single_thread_task_runner.h" #include "base/trace_event/trace_event.h" #include "content/public/browser/browser_thread.h" #include "content/public/common/content_paths.h" #include "electron/buildflags/buildflags.h" #include "electron/fuses.h" #include "shell/browser/api/electron_api_app.h" #include "shell/common/api/electron_bindings.h" #include "shell/common/electron_command_line.h" #include "shell/common/gin_converters/file_path_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/gin_helper/event.h" #include "shell/common/gin_helper/event_emitter_caller.h" #include "shell/common/gin_helper/locker.h" #include "shell/common/gin_helper/microtasks_scope.h" #include "shell/common/mac/main_application_bundle.h" #include "third_party/blink/renderer/bindings/core/v8/v8_initializer.h" // nogncheck #include "third_party/electron_node/src/debug_utils.h" #if !IS_MAS_BUILD() #include "shell/common/crash_keys.h" #endif #define ELECTRON_BROWSER_BINDINGS(V) \ V(electron_browser_app) \ V(electron_browser_auto_updater) \ V(electron_browser_browser_view) \ V(electron_browser_content_tracing) \ V(electron_browser_crash_reporter) \ V(electron_browser_desktop_capturer) \ V(electron_browser_dialog) \ V(electron_browser_event_emitter) \ V(electron_browser_global_shortcut) \ V(electron_browser_in_app_purchase) \ V(electron_browser_menu) \ V(electron_browser_message_port) \ V(electron_browser_native_theme) \ V(electron_browser_net) \ V(electron_browser_notification) \ V(electron_browser_power_monitor) \ V(electron_browser_power_save_blocker) \ V(electron_browser_protocol) \ V(electron_browser_printing) \ V(electron_browser_push_notifications) \ V(electron_browser_safe_storage) \ V(electron_browser_session) \ V(electron_browser_screen) \ V(electron_browser_system_preferences) \ V(electron_browser_base_window) \ V(electron_browser_tray) \ V(electron_browser_utility_process) \ V(electron_browser_view) \ V(electron_browser_web_contents) \ V(electron_browser_web_contents_view) \ V(electron_browser_web_frame_main) \ V(electron_browser_web_view_manager) \ V(electron_browser_window) #define ELECTRON_COMMON_BINDINGS(V) \ V(electron_common_asar) \ V(electron_common_clipboard) \ V(electron_common_command_line) \ V(electron_common_crashpad_support) \ V(electron_common_environment) \ V(electron_common_features) \ V(electron_common_native_image) \ V(electron_common_shell) \ V(electron_common_v8_util) #define ELECTRON_RENDERER_BINDINGS(V) \ V(electron_renderer_context_bridge) \ V(electron_renderer_crash_reporter) \ V(electron_renderer_ipc) \ V(electron_renderer_web_frame) #define ELECTRON_UTILITY_BINDINGS(V) V(electron_utility_parent_port) #define ELECTRON_VIEWS_BINDINGS(V) V(electron_browser_image_view) #define ELECTRON_TESTING_BINDINGS(V) V(electron_common_testing) // This is used to load built-in bindings. Instead of using // __attribute__((constructor)), we call the _register_<modname> // function for each built-in bindings explicitly. This is only // forward declaration. The definitions are in each binding's // implementation when calling the NODE_LINKED_BINDING_CONTEXT_AWARE. #define V(modname) void _register_##modname(); ELECTRON_BROWSER_BINDINGS(V) ELECTRON_COMMON_BINDINGS(V) ELECTRON_RENDERER_BINDINGS(V) ELECTRON_UTILITY_BINDINGS(V) #if BUILDFLAG(ENABLE_VIEWS_API) ELECTRON_VIEWS_BINDINGS(V) #endif #if DCHECK_IS_ON() ELECTRON_TESTING_BINDINGS(V) #endif #undef V namespace { void stop_and_close_uv_loop(uv_loop_t* loop) { uv_stop(loop); auto const ensure_closing = [](uv_handle_t* handle, void*) { // We should be using the UvHandle wrapper everywhere, in which case // all handles should already be in a closing state... DCHECK(uv_is_closing(handle)); // ...but if a raw handle got through, through, do the right thing anyway if (!uv_is_closing(handle)) { uv_close(handle, nullptr); } }; uv_walk(loop, ensure_closing, nullptr); // All remaining handles are in a closing state now. // Pump the event loop so that they can finish closing. for (;;) if (uv_run(loop, UV_RUN_DEFAULT) == 0) break; DCHECK_EQ(0, uv_loop_alive(loop)); node::CheckedUvLoopClose(loop); } bool g_is_initialized = false; void V8FatalErrorCallback(const char* location, const char* message) { LOG(ERROR) << "Fatal error in V8: " << location << " " << message; #if !IS_MAS_BUILD() electron::crash_keys::SetCrashKey("electron.v8-fatal.message", message); electron::crash_keys::SetCrashKey("electron.v8-fatal.location", location); #endif volatile int* zero = nullptr; *zero = 0; } bool AllowWasmCodeGenerationCallback(v8::Local<v8::Context> context, v8::Local<v8::String> source) { // If we're running with contextIsolation enabled in the renderer process, // fall back to Blink's logic. if (node::Environment::GetCurrent(context) == nullptr) { if (!electron::IsRendererProcess()) return false; return blink::V8Initializer::WasmCodeGenerationCheckCallbackInMainThread( context, source); } return node::AllowWasmCodeGenerationCallback(context, source); } v8::ModifyCodeGenerationFromStringsResult ModifyCodeGenerationFromStrings( v8::Local<v8::Context> context, v8::Local<v8::Value> source, bool is_code_like) { if (node::Environment::GetCurrent(context) == nullptr) { // No node environment means we're in the renderer process, either in a // sandboxed renderer or in an unsandboxed renderer with context isolation // enabled. if (!electron::IsRendererProcess()) { NOTREACHED(); return {false, {}}; } return blink::V8Initializer::CodeGenerationCheckCallbackInMainThread( context, source, is_code_like); } // If we get here then we have a node environment, so either a) we're in the // non-rendrer process, or b) we're in the renderer process in a context that // has both node and blink, i.e. contextIsolation disabled. // If we're in the renderer with contextIsolation disabled, ask blink first // (for CSP), and iff that allows codegen, delegate to node. if (electron::IsRendererProcess()) { v8::ModifyCodeGenerationFromStringsResult result = blink::V8Initializer::CodeGenerationCheckCallbackInMainThread( context, source, is_code_like); if (!result.codegen_allowed) return result; } // If we're in the main process or utility process, delegate to node. return node::ModifyCodeGenerationFromStrings(context, source, is_code_like); } void ErrorMessageListener(v8::Local<v8::Message> message, v8::Local<v8::Value> data) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); node::Environment* env = node::Environment::GetCurrent(isolate); if (env) { gin_helper::MicrotasksScope microtasks_scope( isolate, env->context()->GetMicrotaskQueue(), v8::MicrotasksScope::kDoNotRunMicrotasks); // Emit the after() hooks now that the exception has been handled. // Analogous to node/lib/internal/process/execution.js#L176-L180 if (env->async_hooks()->fields()[node::AsyncHooks::kAfter]) { while (env->async_hooks()->fields()[node::AsyncHooks::kStackLength]) { node::AsyncWrap::EmitAfter(env, env->execution_async_id()); env->async_hooks()->pop_async_context(env->execution_async_id()); } } // Ensure that the async id stack is properly cleared so the async // hook stack does not become corrupted. env->async_hooks()->clear_async_id_stack(); } } // Only allow DebugOptions in non-ELECTRON_RUN_AS_NODE mode. // If node CLI inspect support is disabled, allow no debug options. bool IsAllowedDebugOption(base::StringPiece option) { static constexpr auto options = base::MakeFixedFlatSet<base::StringPiece>({ "--debug", "--debug-brk", "--debug-port", "--inspect", "--inspect-brk", "--inspect-brk-node", "--inspect-port", "--inspect-publish-uid", }); return electron::fuses::IsNodeCliInspectEnabled() && options.contains(option); } // Initialize NODE_OPTIONS to pass to Node.js // See https://nodejs.org/api/cli.html#cli_node_options_options void SetNodeOptions(base::Environment* env) { // Options that are unilaterally disallowed static constexpr auto disallowed = base::MakeFixedFlatSet<base::StringPiece>({ "--enable-fips", "--force-fips", "--openssl-config", "--use-bundled-ca", "--use-openssl-ca", }); static constexpr auto pkg_opts = base::MakeFixedFlatSet<base::StringPiece>({ "--http-parser", "--max-http-header-size", }); if (env->HasVar("NODE_OPTIONS")) { if (electron::fuses::IsNodeOptionsEnabled()) { std::string options; env->GetVar("NODE_OPTIONS", &options); std::vector<std::string> parts = base::SplitString( options, " ", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY); bool is_packaged_app = electron::api::App::IsPackaged(); for (const auto& part : parts) { // Strip off values passed to individual NODE_OPTIONs std::string option = part.substr(0, part.find('=')); if (is_packaged_app && !pkg_opts.contains(option)) { // Explicitly disallow majority of NODE_OPTIONS in packaged apps LOG(ERROR) << "Most NODE_OPTIONs are not supported in packaged apps." << " See documentation for more details."; options.erase(options.find(option), part.length()); } else if (disallowed.contains(option)) { // Remove NODE_OPTIONS specifically disallowed for use in Node.js // through Electron owing to constraints like BoringSSL. LOG(ERROR) << "The NODE_OPTION " << option << " is not supported in Electron"; options.erase(options.find(option), part.length()); } } // overwrite new NODE_OPTIONS without unsupported variables env->SetVar("NODE_OPTIONS", options); } else { LOG(ERROR) << "NODE_OPTIONS have been disabled in this app"; env->SetVar("NODE_OPTIONS", ""); } } } } // namespace namespace electron { namespace { base::FilePath GetResourcesPath() { #if BUILDFLAG(IS_MAC) return MainApplicationBundlePath().Append("Contents").Append("Resources"); #else auto* command_line = base::CommandLine::ForCurrentProcess(); base::FilePath exec_path(command_line->GetProgram()); base::PathService::Get(base::FILE_EXE, &exec_path); return exec_path.DirName().Append(FILE_PATH_LITERAL("resources")); #endif } } // namespace NodeBindings::NodeBindings(BrowserEnvironment browser_env) : browser_env_(browser_env) { if (browser_env == BrowserEnvironment::kWorker) { uv_loop_init(&worker_loop_); uv_loop_ = &worker_loop_; } else { uv_loop_ = uv_default_loop(); } // Interrupt embed polling when a handle is started. uv_loop_configure(uv_loop_, UV_LOOP_INTERRUPT_ON_IO_CHANGE); } NodeBindings::~NodeBindings() { // Quit the embed thread. embed_closed_ = true; uv_sem_post(&embed_sem_); WakeupEmbedThread(); // Wait for everything to be done. uv_thread_join(&embed_thread_); // Clear uv. uv_sem_destroy(&embed_sem_); dummy_uv_handle_.reset(); // Clean up worker loop if (in_worker_loop()) stop_and_close_uv_loop(uv_loop_); } void NodeBindings::RegisterBuiltinBindings() { #define V(modname) _register_##modname(); if (IsBrowserProcess()) { ELECTRON_BROWSER_BINDINGS(V) #if BUILDFLAG(ENABLE_VIEWS_API) ELECTRON_VIEWS_BINDINGS(V) #endif } ELECTRON_COMMON_BINDINGS(V) if (IsRendererProcess()) { ELECTRON_RENDERER_BINDINGS(V) } if (IsUtilityProcess()) { ELECTRON_UTILITY_BINDINGS(V) } #if DCHECK_IS_ON() ELECTRON_TESTING_BINDINGS(V) #endif #undef V } bool NodeBindings::IsInitialized() { return g_is_initialized; } // Initialize Node.js cli options to pass to Node.js // See https://nodejs.org/api/cli.html#cli_options void NodeBindings::SetNodeCliFlags() { const auto argv = base::CommandLine::ForCurrentProcess()->argv(); std::vector<std::string> args; // TODO(codebytere): We need to set the first entry in args to the // process name owing to src/node_options-inl.h#L286-L290 but this is // redundant and so should be refactored upstream. args.reserve(argv.size() + 1); args.emplace_back("electron"); for (const auto& arg : argv) { #if BUILDFLAG(IS_WIN) const auto& option = base::WideToUTF8(arg); #else const auto& option = arg; #endif const auto stripped = base::StringPiece(option).substr(0, option.find('=')); // Only allow in no-op (--) option or DebugOptions if (IsAllowedDebugOption(stripped) || stripped == "--") args.push_back(option); } // We need to disable Node.js' fetch implementation to prevent // conflict with Blink's in renderer and worker processes. if (browser_env_ == BrowserEnvironment::kRenderer || browser_env_ == BrowserEnvironment::kWorker) { args.push_back("--no-experimental-fetch"); } std::vector<std::string> errors; const int exit_code = ProcessGlobalArgs(&args, nullptr, &errors, node::kDisallowedInEnvironment); const std::string err_str = "Error parsing Node.js cli flags "; if (exit_code != 0) { LOG(ERROR) << err_str; } else if (!errors.empty()) { LOG(ERROR) << err_str << base::JoinString(errors, " "); } } void NodeBindings::Initialize(v8::Local<v8::Context> context) { TRACE_EVENT0("electron", "NodeBindings::Initialize"); // Open node's error reporting system for browser process. #if BUILDFLAG(IS_LINUX) // Get real command line in renderer process forked by zygote. if (browser_env_ != BrowserEnvironment::kBrowser) ElectronCommandLine::InitializeFromCommandLine(); #endif // Explicitly register electron's builtin bindings. RegisterBuiltinBindings(); // Parse and set Node.js cli flags. SetNodeCliFlags(); auto env = base::Environment::Create(); SetNodeOptions(env.get()); std::vector<std::string> argv = {"electron"}; std::vector<std::string> exec_argv; std::vector<std::string> errors; uint64_t process_flags = node::ProcessFlags::kNoFlags; // We do not want the child processes spawned from the utility process // to inherit the custom stdio handles created for the parent. if (browser_env_ != BrowserEnvironment::kUtility) process_flags |= node::ProcessFlags::kEnableStdioInheritance; if (!fuses::IsNodeOptionsEnabled()) process_flags |= node::ProcessFlags::kDisableNodeOptionsEnv; int exit_code = node::InitializeNodeWithArgs( &argv, &exec_argv, &errors, static_cast<node::ProcessFlags::Flags>(process_flags)); for (const std::string& error : errors) fprintf(stderr, "%s: %s\n", argv[0].c_str(), error.c_str()); if (exit_code != 0) exit(exit_code); #if BUILDFLAG(IS_WIN) // uv_init overrides error mode to suppress the default crash dialog, bring // it back if user wants to show it. if (browser_env_ == BrowserEnvironment::kBrowser || env->HasVar("ELECTRON_DEFAULT_ERROR_MODE")) SetErrorMode(GetErrorMode() & ~SEM_NOGPFAULTERRORBOX); #endif gin_helper::internal::Event::GetConstructor(context); g_is_initialized = true; } node::Environment* NodeBindings::CreateEnvironment( v8::Handle<v8::Context> context, node::MultiIsolatePlatform* platform, std::vector<std::string> args, std::vector<std::string> exec_args) { // Feed node the path to initialization script. std::string process_type; switch (browser_env_) { case BrowserEnvironment::kBrowser: process_type = "browser"; break; case BrowserEnvironment::kRenderer: process_type = "renderer"; break; case BrowserEnvironment::kWorker: process_type = "worker"; break; case BrowserEnvironment::kUtility: process_type = "utility"; break; } v8::Isolate* isolate = context->GetIsolate(); gin_helper::Dictionary global(isolate, context->Global()); if (browser_env_ == BrowserEnvironment::kBrowser) { const std::vector<std::string> search_paths = {"app.asar", "app", "default_app.asar"}; const std::vector<std::string> app_asar_search_paths = {"app.asar"}; context->Global()->SetPrivate( context, v8::Private::ForApi( isolate, gin::ConvertToV8(isolate, "appSearchPaths").As<v8::String>()), gin::ConvertToV8(isolate, electron::fuses::IsOnlyLoadAppFromAsarEnabled() ? app_asar_search_paths : search_paths)); } base::FilePath resources_path = GetResourcesPath(); std::string init_script = "electron/js2c/" + process_type + "_init"; args.insert(args.begin() + 1, init_script); auto* isolate_data = node::CreateIsolateData(isolate, uv_loop_, platform); context->SetAlignedPointerInEmbedderData(kElectronContextEmbedderDataIndex, static_cast<void*>(isolate_data)); node::Environment* env; uint64_t flags = node::EnvironmentFlags::kDefaultFlags | node::EnvironmentFlags::kHideConsoleWindows | node::EnvironmentFlags::kNoGlobalSearchPaths; if (browser_env_ == BrowserEnvironment::kRenderer || browser_env_ == BrowserEnvironment::kWorker) { // Only one ESM loader can be registered per isolate - // in renderer processes this should be blink. We need to tell Node.js // not to register its handler (overriding blinks) in non-browser processes. // We also avoid overriding globals like setImmediate, clearImmediate // queueMicrotask etc during the bootstrap phase of Node.js // for processes that already have these defined by DOM. // Check //third_party/electron_node/lib/internal/bootstrap/node.js // for the list of overrides on globalThis. flags |= node::EnvironmentFlags::kNoRegisterESMLoader | node::EnvironmentFlags::kNoBrowserGlobals | node::EnvironmentFlags::kNoCreateInspector; } if (!electron::fuses::IsNodeCliInspectEnabled()) { // If --inspect and friends are disabled we also shouldn't listen for // SIGUSR1 flags |= node::EnvironmentFlags::kNoStartDebugSignalHandler; } { v8::TryCatch try_catch(isolate); env = node::CreateEnvironment( static_cast<node::IsolateData*>(isolate_data), context, args, exec_args, static_cast<node::EnvironmentFlags::Flags>(flags)); if (try_catch.HasCaught()) { std::string err_msg = "Failed to initialize node environment in process: " + process_type; v8::Local<v8::Message> message = try_catch.Message(); std::string msg; if (!message.IsEmpty() && gin::ConvertFromV8(isolate, message->Get(), &msg)) err_msg += " , with error: " + msg; LOG(ERROR) << err_msg; } } DCHECK(env); node::IsolateSettings is; // Use a custom fatal error callback to allow us to add // crash message and location to CrashReports. is.fatal_error_callback = V8FatalErrorCallback; // We don't want to abort either in the renderer or browser processes. // We already listen for uncaught exceptions and handle them there. // For utility process we expect the process to behave as standard // Node.js runtime and abort the process with appropriate exit // code depending on a handler being set for `uncaughtException` event. if (browser_env_ != BrowserEnvironment::kUtility) { is.should_abort_on_uncaught_exception_callback = [](v8::Isolate*) { return false; }; } // Use a custom callback here to allow us to leverage Blink's logic in the // renderer process. is.allow_wasm_code_generation_callback = AllowWasmCodeGenerationCallback; is.flags |= node::IsolateSettingsFlags:: ALLOW_MODIFY_CODE_GENERATION_FROM_STRINGS_CALLBACK; is.modify_code_generation_from_strings_callback = ModifyCodeGenerationFromStrings; if (browser_env_ == BrowserEnvironment::kBrowser || browser_env_ == BrowserEnvironment::kUtility) { // Node.js requires that microtask checkpoints be explicitly invoked. is.policy = v8::MicrotasksPolicy::kExplicit; } else { // Blink expects the microtasks policy to be kScoped, but Node.js expects it // to be kExplicit. In the renderer, there can be many contexts within the // same isolate, so we don't want to change the existing policy here, which // could be either kExplicit or kScoped depending on whether we're executing // from within a Node.js or a Blink entrypoint. Instead, the policy is // toggled to kExplicit when entering Node.js through UvRunOnce. is.policy = context->GetIsolate()->GetMicrotasksPolicy(); // We do not want to use Node.js' message listener as it interferes with // Blink's. is.flags &= ~node::IsolateSettingsFlags::MESSAGE_LISTENER_WITH_ERROR_LEVEL; // Isolate message listeners are additive (you can add multiple), so instead // we add an extra one here to ensure that the async hook stack is properly // cleared when errors are thrown. context->GetIsolate()->AddMessageListenerWithErrorLevel( ErrorMessageListener, v8::Isolate::kMessageError); // We do not want to use the promise rejection callback that Node.js uses, // because it does not send PromiseRejectionEvents to the global script // context. We need to use the one Blink already provides. is.flags |= node::IsolateSettingsFlags::SHOULD_NOT_SET_PROMISE_REJECTION_CALLBACK; // We do not want to use the stack trace callback that Node.js uses, // because it relies on Node.js being aware of the current Context and // that's not always the case. We need to use the one Blink already // provides. is.flags |= node::IsolateSettingsFlags::SHOULD_NOT_SET_PREPARE_STACK_TRACE_CALLBACK; } node::SetIsolateUpForNode(context->GetIsolate(), is); gin_helper::Dictionary process(context->GetIsolate(), env->process_object()); process.SetReadOnly("type", process_type); process.Set("resourcesPath", resources_path); // The path to helper app. base::FilePath helper_exec_path; base::PathService::Get(content::CHILD_PROCESS_EXE, &helper_exec_path); process.Set("helperExecPath", helper_exec_path); return env; } node::Environment* NodeBindings::CreateEnvironment( v8::Handle<v8::Context> context, node::MultiIsolatePlatform* platform) { #if BUILDFLAG(IS_WIN) auto& electron_args = ElectronCommandLine::argv(); std::vector<std::string> args(electron_args.size()); std::transform(electron_args.cbegin(), electron_args.cend(), args.begin(), [](auto& a) { return base::WideToUTF8(a); }); #else auto args = ElectronCommandLine::argv(); #endif return CreateEnvironment(context, platform, args, {}); } void NodeBindings::LoadEnvironment(node::Environment* env) { node::LoadEnvironment(env, node::StartExecutionCallback{}); gin_helper::EmitEvent(env->isolate(), env->process_object(), "loaded"); } void NodeBindings::PrepareEmbedThread() { // IOCP does not change for the process until the loop is recreated, // we ensure that there is only a single polling thread satisfying // the concurrency limit set from CreateIoCompletionPort call by // uv_loop_init for the lifetime of this process. // More background can be found at: // https://github.com/microsoft/vscode/issues/142786#issuecomment-1061673400 if (initialized_) return; // Add dummy handle for libuv, otherwise libuv would quit when there is // nothing to do. uv_async_init(uv_loop_, dummy_uv_handle_.get(), nullptr); // Start worker that will interrupt main loop when having uv events. uv_sem_init(&embed_sem_, 0); uv_thread_create(&embed_thread_, EmbedThreadRunner, this); } void NodeBindings::StartPolling() { // Avoid calling UvRunOnce if the loop is already active, // otherwise it can lead to situations were the number of active // threads processing on IOCP is greater than the concurrency limit. if (initialized_) return; initialized_ = true; // The MessageLoop should have been created, remember the one in main thread. task_runner_ = base::SingleThreadTaskRunner::GetCurrentDefault(); // Run uv loop for once to give the uv__io_poll a chance to add all events. UvRunOnce(); } void NodeBindings::UvRunOnce() { node::Environment* env = uv_env(); // When doing navigation without restarting renderer process, it may happen // that the node environment is destroyed but the message loop is still there. // In this case we should not run uv loop. if (!env) return; v8::HandleScope handle_scope(env->isolate()); // Enter node context while dealing with uv events. v8::Context::Scope context_scope(env->context()); // Node.js expects `kExplicit` microtasks policy and will run microtasks // checkpoints after every call into JavaScript. Since we use a different // policy in the renderer - switch to `kExplicit` and then drop back to the // previous policy value. v8::MicrotaskQueue* microtask_queue = env->context()->GetMicrotaskQueue(); auto old_policy = microtask_queue->microtasks_policy(); DCHECK_EQ(microtask_queue->GetMicrotasksScopeDepth(), 0); microtask_queue->set_microtasks_policy(v8::MicrotasksPolicy::kExplicit); if (browser_env_ != BrowserEnvironment::kBrowser) TRACE_EVENT_BEGIN0("devtools.timeline", "FunctionCall"); // Deal with uv events. int r = uv_run(uv_loop_, UV_RUN_NOWAIT); if (browser_env_ != BrowserEnvironment::kBrowser) TRACE_EVENT_END0("devtools.timeline", "FunctionCall"); microtask_queue->set_microtasks_policy(old_policy); if (r == 0) base::RunLoop().QuitWhenIdle(); // Quit from uv. // Tell the worker thread to continue polling. uv_sem_post(&embed_sem_); } void NodeBindings::WakeupMainThread() { DCHECK(task_runner_); task_runner_->PostTask(FROM_HERE, base::BindOnce(&NodeBindings::UvRunOnce, weak_factory_.GetWeakPtr())); } void NodeBindings::WakeupEmbedThread() { uv_async_send(dummy_uv_handle_.get()); } // static void NodeBindings::EmbedThreadRunner(void* arg) { auto* self = static_cast<NodeBindings*>(arg); while (true) { // Wait for the main loop to deal with events. uv_sem_wait(&self->embed_sem_); if (self->embed_closed_) break; // Wait for something to happen in uv loop. // Note that the PollEvents() is implemented by derived classes, so when // this class is being destructed the PollEvents() would not be available // anymore. Because of it we must make sure we only invoke PollEvents() // when this class is alive. self->PollEvents(); if (self->embed_closed_) break; // Deal with event in main thread. self->WakeupMainThread(); } } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
21,062
Unable to click tray icon with VoiceOver
<!-- As an open source project with a dedicated but small maintainer team, it can sometimes take a long time for issues to be addressed so please be patient and we will get back to you as soon as we can. --> ### Preflight Checklist <!-- Please ensure you've completed the following steps by replacing [ ] with [x]--> * [ 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 an issue that matches the one I want to file, without success. ### Issue Details * **Electron Version:** * 7.1.1 * **Operating System:** * Mac OS 10.15.1 * **Last Known Working Electron version:** * N/A ### Expected Behavior When clicking tray icons using the VoiceOver screen reader, the tray click event should fire. ### Actual Behavior Clicking the tray icon does nothing, unless a context menu is set using `tray.setContextMenu`, in which case the menu opens. ### To Reproduce Basic demo of the issue (can be reproduced in Electron Fiddle): https://gist.github.com/oysteinmoseng/bec736b1c2ceec3fa6e5a77d46d3ac08 To reproduce with VoiceOver, start VoiceOver (cmd+F5), navigate to the tray (VO + M M), and attempt to click the icon (VO + spacebar). VoiceOver will announce that the icon was pressed, but no click event will be fired.
https://github.com/electron/electron/issues/21062
https://github.com/electron/electron/pull/39352
1eb6e45a365fd7b73b23302662f29e465a698719
dc707ee93835b279ff67dbd5f80ce28a4b9df3e1
2019-11-09T16:46:07Z
c++
2023-08-07T07:52:18Z
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/memory/raw_ptr.h" #include "base/message_loop/message_pump_mac.h" #include "base/strings/sys_string_conversions.h" #include "base/task/current_thread.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 { raw_ptr<electron::TrayIconCocoa> trayIcon_; // weak ElectronMenuController* menuController_; // weak BOOL ignoreDoubleClickEvents_; NSStatusItem* __strong statusItem_; NSTrackingArea* __strong trackingArea_; } @end // @interface StatusItemView @implementation StatusItemView - (void)dealloc { trayIcon_ = nil; menuController_ = nil; } - (id)initWithIcon:(electron::TrayIconCocoa*)icon { trayIcon_ = icon; menuController_ = nil; ignoreDoubleClickEvents_ = NO; if ((self = [super initWithFrame:CGRectZero])) { [self registerForDraggedTypes:@[ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" NSFilenamesPboardType, #pragma clang diagnostic pop NSPasteboardTypeString, ]]; // Create the status item. NSStatusItem* item = [[NSStatusBar systemStatusBar] statusItemWithLength:NSVariableStatusItemLength]; statusItem_ = item; [[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_ = [[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_ = nil; } // Ensure any open menu is closed. if ([statusItem_ menu]) [[statusItem_ menu] cancelTracking]; [[NSStatusBar systemStatusBar] removeStatusItem:statusItem_]; [self removeFromSuperview]; statusItem_ = nil; } - (void)setImage:(NSImage*)image { [[statusItem_ button] setImage:image]; [self updateDimensions]; } - (void)setAlternateImage:(NSImage*)image { [[statusItem_ button] setAlternateImage:image]; // We need to change the button type here because the default button type for // NSStatusItem, NSStatusBarButton, does not display alternate content when // clicked. NSButtonTypeMomentaryChange displays its alternate content when // clicked and returns to its normal content when the user releases it, which // is the behavior users would expect when clicking a button with an alternate // image set. [[statusItem_ button] setButtonType:NSButtonTypeMomentaryChange]; [self updateDimensions]; } - (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"]) { 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 if one exists and has a non-zero // number of items. Custom mouseUp handler won't be invoked in this case. if (menuController_ && [[menuController_ menu] numberOfItems] > 0) { [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::ScopedAllowApplicationTasksInNativeNestedLoop allow; // Show a custom menu. if (menu_model) { ElectronMenuController* menuController = [[ElectronMenuController alloc] initWithModel:menu_model useDefaultAccelerator:NO]; // Hacky way to mimic design of ordinary tray menu. [statusItem_ setMenu:[menuController menu]]; [[statusItem_ button] performClick:self]; [statusItem_ setMenu:[menuController_ menu]]; 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]; // TODO(codebytere): update to currently supported NSPasteboardTypeFileURL or // kUTTypeFileURL. #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" 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:NSPasteboardTypeString]) { NSString* dropText = [pboard stringForType:NSPasteboardTypeString]; trayIcon_->NotifyDropText(base::SysNSStringToUTF8(dropText)); return YES; } #pragma clang diagnostic pop 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_ = [[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(base::WeakPtr<ElectronMenuModel> menu_model) { [status_item_view_ popUpContextMenu:menu_model.get()]; } void TrayIconCocoa::PopUpContextMenu( const gfx::Point& pos, base::WeakPtr<ElectronMenuModel> menu_model) { content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&TrayIconCocoa::PopUpOnUI, weak_factory_.GetWeakPtr(), menu_model)); } void TrayIconCocoa::CloseContextMenu() { [status_item_view_ closeContextMenu]; } void TrayIconCocoa::SetContextMenu(raw_ptr<ElectronMenuModel> menu_model) { if (menu_model) { // Create native menu. menu_ = [[ElectronMenuController alloc] initWithModel:menu_model useDefaultAccelerator:NO]; } else { menu_ = nil; } [status_item_view_ setMenuController:menu_]; } 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
21,062
Unable to click tray icon with VoiceOver
<!-- As an open source project with a dedicated but small maintainer team, it can sometimes take a long time for issues to be addressed so please be patient and we will get back to you as soon as we can. --> ### Preflight Checklist <!-- Please ensure you've completed the following steps by replacing [ ] with [x]--> * [ 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 an issue that matches the one I want to file, without success. ### Issue Details * **Electron Version:** * 7.1.1 * **Operating System:** * Mac OS 10.15.1 * **Last Known Working Electron version:** * N/A ### Expected Behavior When clicking tray icons using the VoiceOver screen reader, the tray click event should fire. ### Actual Behavior Clicking the tray icon does nothing, unless a context menu is set using `tray.setContextMenu`, in which case the menu opens. ### To Reproduce Basic demo of the issue (can be reproduced in Electron Fiddle): https://gist.github.com/oysteinmoseng/bec736b1c2ceec3fa6e5a77d46d3ac08 To reproduce with VoiceOver, start VoiceOver (cmd+F5), navigate to the tray (VO + M M), and attempt to click the icon (VO + spacebar). VoiceOver will announce that the icon was pressed, but no click event will be fired.
https://github.com/electron/electron/issues/21062
https://github.com/electron/electron/pull/39352
1eb6e45a365fd7b73b23302662f29e465a698719
dc707ee93835b279ff67dbd5f80ce28a4b9df3e1
2019-11-09T16:46:07Z
c++
2023-08-07T07:52:18Z
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/memory/raw_ptr.h" #include "base/message_loop/message_pump_mac.h" #include "base/strings/sys_string_conversions.h" #include "base/task/current_thread.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 { raw_ptr<electron::TrayIconCocoa> trayIcon_; // weak ElectronMenuController* menuController_; // weak BOOL ignoreDoubleClickEvents_; NSStatusItem* __strong statusItem_; NSTrackingArea* __strong trackingArea_; } @end // @interface StatusItemView @implementation StatusItemView - (void)dealloc { trayIcon_ = nil; menuController_ = nil; } - (id)initWithIcon:(electron::TrayIconCocoa*)icon { trayIcon_ = icon; menuController_ = nil; ignoreDoubleClickEvents_ = NO; if ((self = [super initWithFrame:CGRectZero])) { [self registerForDraggedTypes:@[ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" NSFilenamesPboardType, #pragma clang diagnostic pop NSPasteboardTypeString, ]]; // Create the status item. NSStatusItem* item = [[NSStatusBar systemStatusBar] statusItemWithLength:NSVariableStatusItemLength]; statusItem_ = item; [[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_ = [[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_ = nil; } // Ensure any open menu is closed. if ([statusItem_ menu]) [[statusItem_ menu] cancelTracking]; [[NSStatusBar systemStatusBar] removeStatusItem:statusItem_]; [self removeFromSuperview]; statusItem_ = nil; } - (void)setImage:(NSImage*)image { [[statusItem_ button] setImage:image]; [self updateDimensions]; } - (void)setAlternateImage:(NSImage*)image { [[statusItem_ button] setAlternateImage:image]; // We need to change the button type here because the default button type for // NSStatusItem, NSStatusBarButton, does not display alternate content when // clicked. NSButtonTypeMomentaryChange displays its alternate content when // clicked and returns to its normal content when the user releases it, which // is the behavior users would expect when clicking a button with an alternate // image set. [[statusItem_ button] setButtonType:NSButtonTypeMomentaryChange]; [self updateDimensions]; } - (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"]) { 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 if one exists and has a non-zero // number of items. Custom mouseUp handler won't be invoked in this case. if (menuController_ && [[menuController_ menu] numberOfItems] > 0) { [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::ScopedAllowApplicationTasksInNativeNestedLoop allow; // Show a custom menu. if (menu_model) { ElectronMenuController* menuController = [[ElectronMenuController alloc] initWithModel:menu_model useDefaultAccelerator:NO]; // Hacky way to mimic design of ordinary tray menu. [statusItem_ setMenu:[menuController menu]]; [[statusItem_ button] performClick:self]; [statusItem_ setMenu:[menuController_ menu]]; 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]; // TODO(codebytere): update to currently supported NSPasteboardTypeFileURL or // kUTTypeFileURL. #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" 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:NSPasteboardTypeString]) { NSString* dropText = [pboard stringForType:NSPasteboardTypeString]; trayIcon_->NotifyDropText(base::SysNSStringToUTF8(dropText)); return YES; } #pragma clang diagnostic pop 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_ = [[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(base::WeakPtr<ElectronMenuModel> menu_model) { [status_item_view_ popUpContextMenu:menu_model.get()]; } void TrayIconCocoa::PopUpContextMenu( const gfx::Point& pos, base::WeakPtr<ElectronMenuModel> menu_model) { content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&TrayIconCocoa::PopUpOnUI, weak_factory_.GetWeakPtr(), menu_model)); } void TrayIconCocoa::CloseContextMenu() { [status_item_view_ closeContextMenu]; } void TrayIconCocoa::SetContextMenu(raw_ptr<ElectronMenuModel> menu_model) { if (menu_model) { // Create native menu. menu_ = [[ElectronMenuController alloc] initWithModel:menu_model useDefaultAccelerator:NO]; } else { menu_ = nil; } [status_item_view_ setMenuController:menu_]; } 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
39,377
[Bug]: removeBrowserView() crashes if view.webContents.close() is called beforehand.
### 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 25.3.0 ### What operating system are you using? macOS ### Operating System Version macOs Ventura 13.4.1 (c) ### What arch are you using? x64 ### Last Known Working Electron version 25.2.0 ### Expected Behavior We are using `browserViews` in a `browserWindow`, when closing our view, we need the `window.close` event to be sent, so I'm using the `view.webContents.close()` to close the window (it's hosting a citrix receiver html5 page) before I call `mainWindow.removeBrowserView()`. Expected behavior is the `browserView` closes, and the `getBrowserViews` list is updated by `removeBrowserView()` call. ### Actual Behavior The `removeBrowserView` call crashes the electron app. In the fiddle it crashes with `Electron exited with signal SIGSEGV.` ### Testcase Gist URL https://gist.github.com/Bill77/1db0aefcd338b612f66e09a9f7372d82 ### Additional Information Attached is a Electron Fiddle with the **add** and **close** buttons. To reproduce, add the view and then close it, which works in `25.2.0` but does not in `25.3.0+`. Looking at the change log, it seem it's related to [this PR](https://github.com/electron/electron/pull/38996). I did try to just use the `webContents.close()` and skip calling `removeBrowserView()` but the view list does not get updated, and we get a list of views that have null `webContents`. Which I suspect is causing the issue in `removeBrowerView()` to crash. We either need a solution where within `removeBrowserView` it calls the `webContents.close` or the logic in `removeBrowserView` needs null checks on the `webContent` references. Sorry, that's my guess based on not looking at the Electron code directly! 🤷‍♂️
https://github.com/electron/electron/issues/39377
https://github.com/electron/electron/pull/39387
1548a2f9fb6d9bf9e0c4f6ace595189cf84b38e9
8f4f82618c51029f91cfb6516bc9c75164bfee9a
2023-08-04T23:22:40Z
c++
2023-08-08T08:23:14Z
shell/browser/api/electron_api_base_window.cc
// Copyright (c) 2018 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_base_window.h" #include <algorithm> #include <string> #include <utility> #include <vector> #include "base/containers/contains.h" #include "base/task/single_thread_task_runner.h" #include "electron/buildflags/buildflags.h" #include "gin/dictionary.h" #include "shell/browser/api/electron_api_browser_view.h" #include "shell/browser/api/electron_api_menu.h" #include "shell/browser/api/electron_api_view.h" #include "shell/browser/api/electron_api_web_contents.h" #include "shell/browser/javascript_environment.h" #include "shell/common/color_util.h" #include "shell/common/gin_converters/callback_converter.h" #include "shell/common/gin_converters/file_path_converter.h" #include "shell/common/gin_converters/gfx_converter.h" #include "shell/common/gin_converters/image_converter.h" #include "shell/common/gin_converters/native_window_converter.h" #include "shell/common/gin_converters/optional_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/gin_helper/persistent_dictionary.h" #include "shell/common/node_includes.h" #include "shell/common/options_switches.h" #if defined(TOOLKIT_VIEWS) #include "shell/browser/native_window_views.h" #endif #if BUILDFLAG(IS_WIN) #include "shell/browser/ui/win/taskbar_host.h" #include "ui/base/win/shell.h" #endif #if BUILDFLAG(IS_WIN) namespace gin { template <> struct Converter<electron::TaskbarHost::ThumbarButton> { static bool FromV8(v8::Isolate* isolate, v8::Handle<v8::Value> val, electron::TaskbarHost::ThumbarButton* out) { gin::Dictionary dict(isolate); if (!gin::ConvertFromV8(isolate, val, &dict)) return false; dict.Get("click", &(out->clicked_callback)); dict.Get("tooltip", &(out->tooltip)); dict.Get("flags", &out->flags); return dict.Get("icon", &(out->icon)); } }; } // namespace gin #endif namespace electron::api { namespace { // Converts binary data to Buffer. v8::Local<v8::Value> ToBuffer(v8::Isolate* isolate, void* val, int size) { auto buffer = node::Buffer::Copy(isolate, static_cast<char*>(val), size); if (buffer.IsEmpty()) return v8::Null(isolate); else return buffer.ToLocalChecked(); } } // namespace BaseWindow::BaseWindow(v8::Isolate* isolate, const gin_helper::Dictionary& options) { // The parent window. gin::Handle<BaseWindow> parent; if (options.Get("parent", &parent) && !parent.IsEmpty()) parent_window_.Reset(isolate, parent.ToV8()); // Offscreen windows are always created frameless. gin_helper::Dictionary web_preferences; bool offscreen; if (options.Get(options::kWebPreferences, &web_preferences) && web_preferences.Get(options::kOffscreen, &offscreen) && offscreen) { const_cast<gin_helper::Dictionary&>(options).Set(options::kFrame, false); } // Creates NativeWindow. window_.reset(NativeWindow::Create( options, parent.IsEmpty() ? nullptr : parent->window_.get())); window_->AddObserver(this); #if defined(TOOLKIT_VIEWS) v8::Local<v8::Value> icon; if (options.Get(options::kIcon, &icon)) { SetIconImpl(isolate, icon, NativeImage::OnConvertError::kWarn); } #endif } BaseWindow::BaseWindow(gin_helper::Arguments* args, const gin_helper::Dictionary& options) : BaseWindow(args->isolate(), options) { InitWithArgs(args); // Init window after everything has been setup. window()->InitFromOptions(options); } BaseWindow::~BaseWindow() { CloseImmediately(); // Destroy the native window in next tick because the native code might be // iterating all windows. base::SingleThreadTaskRunner::GetCurrentDefault()->DeleteSoon( FROM_HERE, window_.release()); // Remove global reference so the JS object can be garbage collected. self_ref_.Reset(); } void BaseWindow::InitWith(v8::Isolate* isolate, v8::Local<v8::Object> wrapper) { AttachAsUserData(window_.get()); gin_helper::TrackableObject<BaseWindow>::InitWith(isolate, wrapper); // We can only append this window to parent window's child windows after this // window's JS wrapper gets initialized. if (!parent_window_.IsEmpty()) { gin::Handle<BaseWindow> parent; gin::ConvertFromV8(isolate, GetParentWindow(), &parent); DCHECK(!parent.IsEmpty()); parent->child_windows_.Set(isolate, weak_map_id(), wrapper); } // Reference this object in case it got garbage collected. self_ref_.Reset(isolate, wrapper); } void BaseWindow::WillCloseWindow(bool* prevent_default) { if (Emit("close")) { *prevent_default = true; } } void BaseWindow::OnWindowClosed() { // Invalidate weak ptrs before the Javascript object is destroyed, // there might be some delayed emit events which shouldn't be // triggered after this. weak_factory_.InvalidateWeakPtrs(); RemoveFromWeakMap(); window_->RemoveObserver(this); // We can not call Destroy here because we need to call Emit first, but we // also do not want any method to be used, so just mark as destroyed here. MarkDestroyed(); Emit("closed"); RemoveFromParentChildWindows(); BaseWindow::ResetBrowserViews(); // Destroy the native class when window is closed. base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask( FROM_HERE, GetDestroyClosure()); } void BaseWindow::OnWindowEndSession() { Emit("session-end"); } void BaseWindow::OnWindowBlur() { EmitEventSoon("blur"); } void BaseWindow::OnWindowFocus() { EmitEventSoon("focus"); } void BaseWindow::OnWindowShow() { Emit("show"); } void BaseWindow::OnWindowHide() { Emit("hide"); } void BaseWindow::OnWindowMaximize() { Emit("maximize"); } void BaseWindow::OnWindowUnmaximize() { Emit("unmaximize"); } void BaseWindow::OnWindowMinimize() { Emit("minimize"); } void BaseWindow::OnWindowRestore() { Emit("restore"); } void BaseWindow::OnWindowWillResize(const gfx::Rect& new_bounds, const gfx::ResizeEdge& edge, bool* prevent_default) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); gin_helper::Dictionary info = gin::Dictionary::CreateEmpty(isolate); info.Set("edge", edge); if (Emit("will-resize", new_bounds, info)) { *prevent_default = true; } } void BaseWindow::OnWindowResize() { Emit("resize"); } void BaseWindow::OnWindowResized() { Emit("resized"); } void BaseWindow::OnWindowWillMove(const gfx::Rect& new_bounds, bool* prevent_default) { if (Emit("will-move", new_bounds)) { *prevent_default = true; } } void BaseWindow::OnWindowMove() { Emit("move"); } void BaseWindow::OnWindowMoved() { Emit("moved"); } void BaseWindow::OnWindowEnterFullScreen() { Emit("enter-full-screen"); } void BaseWindow::OnWindowLeaveFullScreen() { Emit("leave-full-screen"); } void BaseWindow::OnWindowSwipe(const std::string& direction) { Emit("swipe", direction); } void BaseWindow::OnWindowRotateGesture(float rotation) { Emit("rotate-gesture", rotation); } void BaseWindow::OnWindowSheetBegin() { Emit("sheet-begin"); } void BaseWindow::OnWindowSheetEnd() { Emit("sheet-end"); } void BaseWindow::OnWindowEnterHtmlFullScreen() { Emit("enter-html-full-screen"); } void BaseWindow::OnWindowLeaveHtmlFullScreen() { Emit("leave-html-full-screen"); } void BaseWindow::OnWindowAlwaysOnTopChanged() { Emit("always-on-top-changed", IsAlwaysOnTop()); } void BaseWindow::OnExecuteAppCommand(const std::string& command_name) { Emit("app-command", command_name); } void BaseWindow::OnTouchBarItemResult(const std::string& item_id, const base::Value::Dict& details) { Emit("-touch-bar-interaction", item_id, details); } void BaseWindow::OnNewWindowForTab() { Emit("new-window-for-tab"); } void BaseWindow::OnSystemContextMenu(int x, int y, bool* prevent_default) { if (Emit("system-context-menu", gfx::Point(x, y))) { *prevent_default = true; } } #if BUILDFLAG(IS_WIN) void BaseWindow::OnWindowMessage(UINT message, WPARAM w_param, LPARAM l_param) { if (IsWindowMessageHooked(message)) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); messages_callback_map_[message].Run( ToBuffer(isolate, static_cast<void*>(&w_param), sizeof(WPARAM)), ToBuffer(isolate, static_cast<void*>(&l_param), sizeof(LPARAM))); } } #endif void BaseWindow::SetContentView(gin::Handle<View> view) { ResetBrowserViews(); content_view_.Reset(isolate(), view.ToV8()); window_->SetContentView(view->view()); } void BaseWindow::CloseImmediately() { if (!window_->IsClosed()) window_->CloseImmediately(); } void BaseWindow::Close() { window_->Close(); } void BaseWindow::Focus() { window_->Focus(true); } void BaseWindow::Blur() { window_->Focus(false); } bool BaseWindow::IsFocused() { return window_->IsFocused(); } void BaseWindow::Show() { window_->Show(); } void BaseWindow::ShowInactive() { // This method doesn't make sense for modal window. if (IsModal()) return; window_->ShowInactive(); } void BaseWindow::Hide() { window_->Hide(); } bool BaseWindow::IsVisible() { return window_->IsVisible(); } bool BaseWindow::IsEnabled() { return window_->IsEnabled(); } void BaseWindow::SetEnabled(bool enable) { window_->SetEnabled(enable); } void BaseWindow::Maximize() { window_->Maximize(); } void BaseWindow::Unmaximize() { window_->Unmaximize(); } bool BaseWindow::IsMaximized() { return window_->IsMaximized(); } void BaseWindow::Minimize() { window_->Minimize(); } void BaseWindow::Restore() { window_->Restore(); } bool BaseWindow::IsMinimized() { return window_->IsMinimized(); } void BaseWindow::SetFullScreen(bool fullscreen) { window_->SetFullScreen(fullscreen); } bool BaseWindow::IsFullscreen() { return window_->IsFullscreen(); } void BaseWindow::SetBounds(const gfx::Rect& bounds, gin_helper::Arguments* args) { bool animate = false; args->GetNext(&animate); window_->SetBounds(bounds, animate); } gfx::Rect BaseWindow::GetBounds() { return window_->GetBounds(); } bool BaseWindow::IsNormal() { return window_->IsNormal(); } gfx::Rect BaseWindow::GetNormalBounds() { return window_->GetNormalBounds(); } void BaseWindow::SetContentBounds(const gfx::Rect& bounds, gin_helper::Arguments* args) { bool animate = false; args->GetNext(&animate); window_->SetContentBounds(bounds, animate); } gfx::Rect BaseWindow::GetContentBounds() { return window_->GetContentBounds(); } void BaseWindow::SetSize(int width, int height, gin_helper::Arguments* args) { bool animate = false; gfx::Size size = window_->GetMinimumSize(); size.SetToMax(gfx::Size(width, height)); args->GetNext(&animate); window_->SetSize(size, animate); } std::vector<int> BaseWindow::GetSize() { std::vector<int> result(2); gfx::Size size = window_->GetSize(); result[0] = size.width(); result[1] = size.height(); return result; } void BaseWindow::SetContentSize(int width, int height, gin_helper::Arguments* args) { bool animate = false; args->GetNext(&animate); window_->SetContentSize(gfx::Size(width, height), animate); } std::vector<int> BaseWindow::GetContentSize() { std::vector<int> result(2); gfx::Size size = window_->GetContentSize(); result[0] = size.width(); result[1] = size.height(); return result; } void BaseWindow::SetMinimumSize(int width, int height) { window_->SetMinimumSize(gfx::Size(width, height)); } std::vector<int> BaseWindow::GetMinimumSize() { std::vector<int> result(2); gfx::Size size = window_->GetMinimumSize(); result[0] = size.width(); result[1] = size.height(); return result; } void BaseWindow::SetMaximumSize(int width, int height) { window_->SetMaximumSize(gfx::Size(width, height)); } std::vector<int> BaseWindow::GetMaximumSize() { std::vector<int> result(2); gfx::Size size = window_->GetMaximumSize(); result[0] = size.width(); result[1] = size.height(); return result; } void BaseWindow::SetSheetOffset(double offsetY, gin_helper::Arguments* args) { double offsetX = 0.0; args->GetNext(&offsetX); window_->SetSheetOffset(offsetX, offsetY); } void BaseWindow::SetResizable(bool resizable) { window_->SetResizable(resizable); } bool BaseWindow::IsResizable() { return window_->IsResizable(); } void BaseWindow::SetMovable(bool movable) { window_->SetMovable(movable); } bool BaseWindow::IsMovable() { return window_->IsMovable(); } void BaseWindow::SetMinimizable(bool minimizable) { window_->SetMinimizable(minimizable); } bool BaseWindow::IsMinimizable() { return window_->IsMinimizable(); } void BaseWindow::SetMaximizable(bool maximizable) { window_->SetMaximizable(maximizable); } bool BaseWindow::IsMaximizable() { return window_->IsMaximizable(); } void BaseWindow::SetFullScreenable(bool fullscreenable) { window_->SetFullScreenable(fullscreenable); } bool BaseWindow::IsFullScreenable() { return window_->IsFullScreenable(); } void BaseWindow::SetClosable(bool closable) { window_->SetClosable(closable); } bool BaseWindow::IsClosable() { return window_->IsClosable(); } void BaseWindow::SetAlwaysOnTop(bool top, gin_helper::Arguments* args) { std::string level = "floating"; int relative_level = 0; args->GetNext(&level); args->GetNext(&relative_level); ui::ZOrderLevel z_order = top ? ui::ZOrderLevel::kFloatingWindow : ui::ZOrderLevel::kNormal; window_->SetAlwaysOnTop(z_order, level, relative_level); } bool BaseWindow::IsAlwaysOnTop() { return window_->GetZOrderLevel() != ui::ZOrderLevel::kNormal; } void BaseWindow::Center() { window_->Center(); } void BaseWindow::SetPosition(int x, int y, gin_helper::Arguments* args) { bool animate = false; args->GetNext(&animate); window_->SetPosition(gfx::Point(x, y), animate); } std::vector<int> BaseWindow::GetPosition() { std::vector<int> result(2); gfx::Point pos = window_->GetPosition(); result[0] = pos.x(); result[1] = pos.y(); return result; } void BaseWindow::MoveAbove(const std::string& sourceId, gin_helper::Arguments* args) { if (!window_->MoveAbove(sourceId)) args->ThrowError("Invalid media source id"); } void BaseWindow::MoveTop() { window_->MoveTop(); } void BaseWindow::SetTitle(const std::string& title) { window_->SetTitle(title); } std::string BaseWindow::GetTitle() { return window_->GetTitle(); } void BaseWindow::SetAccessibleTitle(const std::string& title) { window_->SetAccessibleTitle(title); } std::string BaseWindow::GetAccessibleTitle() { return window_->GetAccessibleTitle(); } void BaseWindow::FlashFrame(bool flash) { window_->FlashFrame(flash); } void BaseWindow::SetSkipTaskbar(bool skip) { window_->SetSkipTaskbar(skip); } void BaseWindow::SetExcludedFromShownWindowsMenu(bool excluded) { window_->SetExcludedFromShownWindowsMenu(excluded); } bool BaseWindow::IsExcludedFromShownWindowsMenu() { return window_->IsExcludedFromShownWindowsMenu(); } void BaseWindow::SetSimpleFullScreen(bool simple_fullscreen) { window_->SetSimpleFullScreen(simple_fullscreen); } bool BaseWindow::IsSimpleFullScreen() { return window_->IsSimpleFullScreen(); } void BaseWindow::SetKiosk(bool kiosk) { window_->SetKiosk(kiosk); } bool BaseWindow::IsKiosk() { return window_->IsKiosk(); } bool BaseWindow::IsTabletMode() const { return window_->IsTabletMode(); } void BaseWindow::SetBackgroundColor(const std::string& color_name) { SkColor color = ParseCSSColor(color_name); window_->SetBackgroundColor(color); } std::string BaseWindow::GetBackgroundColor(gin_helper::Arguments* args) { return ToRGBHex(window_->GetBackgroundColor()); } void BaseWindow::InvalidateShadow() { window_->InvalidateShadow(); } void BaseWindow::SetHasShadow(bool has_shadow) { window_->SetHasShadow(has_shadow); } bool BaseWindow::HasShadow() { return window_->HasShadow(); } void BaseWindow::SetOpacity(const double opacity) { window_->SetOpacity(opacity); } double BaseWindow::GetOpacity() { return window_->GetOpacity(); } void BaseWindow::SetShape(const std::vector<gfx::Rect>& rects) { window_->widget()->SetShape(std::make_unique<std::vector<gfx::Rect>>(rects)); } void BaseWindow::SetRepresentedFilename(const std::string& filename) { window_->SetRepresentedFilename(filename); } std::string BaseWindow::GetRepresentedFilename() { return window_->GetRepresentedFilename(); } void BaseWindow::SetDocumentEdited(bool edited) { window_->SetDocumentEdited(edited); } bool BaseWindow::IsDocumentEdited() { return window_->IsDocumentEdited(); } void BaseWindow::SetIgnoreMouseEvents(bool ignore, gin_helper::Arguments* args) { gin_helper::Dictionary options; bool forward = false; args->GetNext(&options) && options.Get("forward", &forward); return window_->SetIgnoreMouseEvents(ignore, forward); } void BaseWindow::SetContentProtection(bool enable) { return window_->SetContentProtection(enable); } void BaseWindow::SetFocusable(bool focusable) { return window_->SetFocusable(focusable); } bool BaseWindow::IsFocusable() { return window_->IsFocusable(); } void BaseWindow::SetMenu(v8::Isolate* isolate, v8::Local<v8::Value> value) { auto context = isolate->GetCurrentContext(); gin::Handle<Menu> menu; v8::Local<v8::Object> object; if (value->IsObject() && value->ToObject(context).ToLocal(&object) && gin::ConvertFromV8(isolate, value, &menu) && !menu.IsEmpty()) { // We only want to update the menu if the menu has a non-zero item count, // or we risk crashes. if (menu->model()->GetItemCount() == 0) { RemoveMenu(); } else { window_->SetMenu(menu->model()); } menu_.Reset(isolate, menu.ToV8()); } else if (value->IsNull()) { RemoveMenu(); } else { isolate->ThrowException( v8::Exception::TypeError(gin::StringToV8(isolate, "Invalid Menu"))); } } void BaseWindow::RemoveMenu() { menu_.Reset(); window_->SetMenu(nullptr); } void BaseWindow::SetParentWindow(v8::Local<v8::Value> value, gin_helper::Arguments* args) { if (IsModal()) { args->ThrowError("Can not be called for modal window"); return; } gin::Handle<BaseWindow> parent; if (value->IsNull() || value->IsUndefined()) { RemoveFromParentChildWindows(); parent_window_.Reset(); window_->SetParentWindow(nullptr); } else if (gin::ConvertFromV8(isolate(), value, &parent)) { RemoveFromParentChildWindows(); parent_window_.Reset(isolate(), value); window_->SetParentWindow(parent->window_.get()); parent->child_windows_.Set(isolate(), weak_map_id(), GetWrapper()); } else { args->ThrowError("Must pass BaseWindow instance or null"); } } void BaseWindow::SetBrowserView( absl::optional<gin::Handle<BrowserView>> browser_view) { ResetBrowserViews(); if (browser_view) AddBrowserView(*browser_view); } void BaseWindow::AddBrowserView(gin::Handle<BrowserView> browser_view) { if (!base::Contains(browser_views_, browser_view.ToV8())) { // If we're reparenting a BrowserView, ensure that it's detached from // its previous owner window. BaseWindow* owner_window = browser_view->owner_window(); if (owner_window) { // iter == browser_views_.end() should imply owner_window != this. DCHECK_NE(owner_window, this); owner_window->RemoveBrowserView(browser_view); browser_view->SetOwnerWindow(nullptr); } window_->AddBrowserView(browser_view->view()); window_->AddDraggableRegionProvider(browser_view.get()); browser_view->SetOwnerWindow(this); browser_views_.emplace_back().Reset(isolate(), browser_view.ToV8()); } } void BaseWindow::RemoveBrowserView(gin::Handle<BrowserView> browser_view) { auto iter = std::find(browser_views_.begin(), browser_views_.end(), browser_view.ToV8()); if (iter != browser_views_.end()) { window_->RemoveBrowserView(browser_view->view()); window_->RemoveDraggableRegionProvider(browser_view.get()); browser_view->SetOwnerWindow(nullptr); iter->Reset(); browser_views_.erase(iter); } } void BaseWindow::SetTopBrowserView(gin::Handle<BrowserView> browser_view, gin_helper::Arguments* args) { BaseWindow* owner_window = browser_view->owner_window(); auto iter = std::find(browser_views_.begin(), browser_views_.end(), browser_view.ToV8()); if (iter == browser_views_.end() || (owner_window && owner_window != this)) { args->ThrowError("Given BrowserView is not attached to the window"); return; } browser_views_.erase(iter); browser_views_.emplace_back().Reset(isolate(), browser_view.ToV8()); window_->SetTopBrowserView(browser_view->view()); } std::string BaseWindow::GetMediaSourceId() const { return window_->GetDesktopMediaID().ToString(); } v8::Local<v8::Value> BaseWindow::GetNativeWindowHandle() { // TODO(MarshallOfSound): Replace once // https://chromium-review.googlesource.com/c/chromium/src/+/1253094/ has // landed NativeWindowHandle handle = window_->GetNativeWindowHandle(); return ToBuffer(isolate(), &handle, sizeof(handle)); } void BaseWindow::SetProgressBar(double progress, gin_helper::Arguments* args) { gin_helper::Dictionary options; std::string mode; args->GetNext(&options) && options.Get("mode", &mode); NativeWindow::ProgressState state = NativeWindow::ProgressState::kNormal; if (mode == "error") state = NativeWindow::ProgressState::kError; else if (mode == "paused") state = NativeWindow::ProgressState::kPaused; else if (mode == "indeterminate") state = NativeWindow::ProgressState::kIndeterminate; else if (mode == "none") state = NativeWindow::ProgressState::kNone; window_->SetProgressBar(progress, state); } void BaseWindow::SetOverlayIcon(const gfx::Image& overlay, const std::string& description) { window_->SetOverlayIcon(overlay, description); } void BaseWindow::SetVisibleOnAllWorkspaces(bool visible, gin_helper::Arguments* args) { gin_helper::Dictionary options; bool visibleOnFullScreen = false; bool skipTransformProcessType = false; if (args->GetNext(&options)) { options.Get("visibleOnFullScreen", &visibleOnFullScreen); options.Get("skipTransformProcessType", &skipTransformProcessType); } return window_->SetVisibleOnAllWorkspaces(visible, visibleOnFullScreen, skipTransformProcessType); } bool BaseWindow::IsVisibleOnAllWorkspaces() { return window_->IsVisibleOnAllWorkspaces(); } void BaseWindow::SetAutoHideCursor(bool auto_hide) { window_->SetAutoHideCursor(auto_hide); } void BaseWindow::SetVibrancy(v8::Isolate* isolate, v8::Local<v8::Value> value) { std::string type = gin::V8ToString(isolate, value); window_->SetVibrancy(type); } void BaseWindow::SetBackgroundMaterial(const std::string& material_type) { window_->SetBackgroundMaterial(material_type); } #if BUILDFLAG(IS_MAC) std::string BaseWindow::GetAlwaysOnTopLevel() { return window_->GetAlwaysOnTopLevel(); } void BaseWindow::SetWindowButtonVisibility(bool visible) { window_->SetWindowButtonVisibility(visible); } bool BaseWindow::GetWindowButtonVisibility() const { return window_->GetWindowButtonVisibility(); } void BaseWindow::SetWindowButtonPosition(absl::optional<gfx::Point> position) { window_->SetWindowButtonPosition(std::move(position)); } absl::optional<gfx::Point> BaseWindow::GetWindowButtonPosition() const { return window_->GetWindowButtonPosition(); } #endif #if BUILDFLAG(IS_MAC) bool BaseWindow::IsHiddenInMissionControl() { return window_->IsHiddenInMissionControl(); } void BaseWindow::SetHiddenInMissionControl(bool hidden) { window_->SetHiddenInMissionControl(hidden); } #endif void BaseWindow::SetTouchBar( std::vector<gin_helper::PersistentDictionary> items) { window_->SetTouchBar(std::move(items)); } void BaseWindow::RefreshTouchBarItem(const std::string& item_id) { window_->RefreshTouchBarItem(item_id); } void BaseWindow::SetEscapeTouchBarItem(gin_helper::PersistentDictionary item) { window_->SetEscapeTouchBarItem(std::move(item)); } void BaseWindow::SelectPreviousTab() { window_->SelectPreviousTab(); } void BaseWindow::SelectNextTab() { window_->SelectNextTab(); } void BaseWindow::ShowAllTabs() { window_->ShowAllTabs(); } void BaseWindow::MergeAllWindows() { window_->MergeAllWindows(); } void BaseWindow::MoveTabToNewWindow() { window_->MoveTabToNewWindow(); } void BaseWindow::ToggleTabBar() { window_->ToggleTabBar(); } void BaseWindow::AddTabbedWindow(NativeWindow* window, gin_helper::Arguments* args) { if (!window_->AddTabbedWindow(window)) args->ThrowError("AddTabbedWindow cannot be called by a window on itself."); } void BaseWindow::SetAutoHideMenuBar(bool auto_hide) { window_->SetAutoHideMenuBar(auto_hide); } bool BaseWindow::IsMenuBarAutoHide() { return window_->IsMenuBarAutoHide(); } void BaseWindow::SetMenuBarVisibility(bool visible) { window_->SetMenuBarVisibility(visible); } bool BaseWindow::IsMenuBarVisible() { return window_->IsMenuBarVisible(); } void BaseWindow::SetAspectRatio(double aspect_ratio, gin_helper::Arguments* args) { gfx::Size extra_size; args->GetNext(&extra_size); window_->SetAspectRatio(aspect_ratio, extra_size); } void BaseWindow::PreviewFile(const std::string& path, gin_helper::Arguments* args) { std::string display_name; if (!args->GetNext(&display_name)) display_name = path; window_->PreviewFile(path, display_name); } void BaseWindow::CloseFilePreview() { window_->CloseFilePreview(); } void BaseWindow::SetGTKDarkThemeEnabled(bool use_dark_theme) { window_->SetGTKDarkThemeEnabled(use_dark_theme); } v8::Local<v8::Value> BaseWindow::GetContentView() const { if (content_view_.IsEmpty()) return v8::Null(isolate()); else return v8::Local<v8::Value>::New(isolate(), content_view_); } v8::Local<v8::Value> BaseWindow::GetParentWindow() const { if (parent_window_.IsEmpty()) return v8::Null(isolate()); else return v8::Local<v8::Value>::New(isolate(), parent_window_); } std::vector<v8::Local<v8::Object>> BaseWindow::GetChildWindows() const { return child_windows_.Values(isolate()); } v8::Local<v8::Value> BaseWindow::GetBrowserView( gin_helper::Arguments* args) const { if (browser_views_.empty()) { return v8::Null(isolate()); } else if (browser_views_.size() == 1) { auto first_view = browser_views_.begin(); return v8::Local<v8::Value>::New(isolate(), *first_view); } else { args->ThrowError( "BrowserWindow have multiple BrowserViews, " "Use getBrowserViews() instead"); return v8::Null(isolate()); } } std::vector<v8::Local<v8::Value>> BaseWindow::GetBrowserViews() const { std::vector<v8::Local<v8::Value>> ret; for (auto const& browser_view : browser_views_) { ret.push_back(v8::Local<v8::Value>::New(isolate(), browser_view)); } return ret; } bool BaseWindow::IsModal() const { return window_->is_modal(); } bool BaseWindow::SetThumbarButtons(gin_helper::Arguments* args) { #if BUILDFLAG(IS_WIN) std::vector<TaskbarHost::ThumbarButton> buttons; if (!args->GetNext(&buttons)) { args->ThrowError(); return false; } auto* window = static_cast<NativeWindowViews*>(window_.get()); return window->taskbar_host().SetThumbarButtons( window_->GetAcceleratedWidget(), buttons); #else return false; #endif } #if defined(TOOLKIT_VIEWS) void BaseWindow::SetIcon(v8::Isolate* isolate, v8::Local<v8::Value> icon) { SetIconImpl(isolate, icon, NativeImage::OnConvertError::kThrow); } void BaseWindow::SetIconImpl(v8::Isolate* isolate, v8::Local<v8::Value> icon, NativeImage::OnConvertError on_error) { NativeImage* native_image = nullptr; if (!NativeImage::TryConvertNativeImage(isolate, icon, &native_image, on_error)) return; #if BUILDFLAG(IS_WIN) static_cast<NativeWindowViews*>(window_.get()) ->SetIcon(native_image->GetHICON(GetSystemMetrics(SM_CXSMICON)), native_image->GetHICON(GetSystemMetrics(SM_CXICON))); #elif BUILDFLAG(IS_LINUX) static_cast<NativeWindowViews*>(window_.get()) ->SetIcon(native_image->image().AsImageSkia()); #endif } #endif #if BUILDFLAG(IS_WIN) bool BaseWindow::HookWindowMessage(UINT message, const MessageCallback& callback) { messages_callback_map_[message] = callback; return true; } void BaseWindow::UnhookWindowMessage(UINT message) { messages_callback_map_.erase(message); } bool BaseWindow::IsWindowMessageHooked(UINT message) { return base::Contains(messages_callback_map_, message); } void BaseWindow::UnhookAllWindowMessages() { messages_callback_map_.clear(); } bool BaseWindow::SetThumbnailClip(const gfx::Rect& region) { auto* window = static_cast<NativeWindowViews*>(window_.get()); return window->taskbar_host().SetThumbnailClip( window_->GetAcceleratedWidget(), region); } bool BaseWindow::SetThumbnailToolTip(const std::string& tooltip) { auto* window = static_cast<NativeWindowViews*>(window_.get()); return window->taskbar_host().SetThumbnailToolTip( window_->GetAcceleratedWidget(), tooltip); } void BaseWindow::SetAppDetails(const gin_helper::Dictionary& options) { std::wstring app_id; base::FilePath app_icon_path; int app_icon_index = 0; std::wstring relaunch_command; std::wstring relaunch_display_name; options.Get("appId", &app_id); options.Get("appIconPath", &app_icon_path); options.Get("appIconIndex", &app_icon_index); options.Get("relaunchCommand", &relaunch_command); options.Get("relaunchDisplayName", &relaunch_display_name); ui::win::SetAppDetailsForWindow(app_id, app_icon_path, app_icon_index, relaunch_command, relaunch_display_name, window_->GetAcceleratedWidget()); } #endif int32_t BaseWindow::GetID() const { return weak_map_id(); } void BaseWindow::ResetBrowserViews() { v8::HandleScope scope(isolate()); for (auto& item : browser_views_) { gin::Handle<BrowserView> browser_view; if (gin::ConvertFromV8(isolate(), v8::Local<v8::Value>::New(isolate(), item), &browser_view) && !browser_view.IsEmpty()) { // There's a chance that the BrowserView may have been reparented - only // reset if the owner window is *this* window. BaseWindow* owner_window = browser_view->owner_window(); DCHECK_EQ(owner_window, this); browser_view->SetOwnerWindow(nullptr); window_->RemoveBrowserView(browser_view->view()); window_->RemoveDraggableRegionProvider(browser_view.get()); browser_view->SetOwnerWindow(nullptr); } item.Reset(); } browser_views_.clear(); } void BaseWindow::RemoveFromParentChildWindows() { if (parent_window_.IsEmpty()) return; gin::Handle<BaseWindow> parent; if (!gin::ConvertFromV8(isolate(), GetParentWindow(), &parent) || parent.IsEmpty()) { return; } parent->child_windows_.Remove(weak_map_id()); } // static gin_helper::WrappableBase* BaseWindow::New(gin_helper::Arguments* args) { gin_helper::Dictionary options = gin::Dictionary::CreateEmpty(args->isolate()); args->GetNext(&options); return new BaseWindow(args, options); } // static void BaseWindow::BuildPrototype(v8::Isolate* isolate, v8::Local<v8::FunctionTemplate> prototype) { prototype->SetClassName(gin::StringToV8(isolate, "BaseWindow")); gin_helper::Destroyable::MakeDestroyable(isolate, prototype); gin_helper::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate()) .SetMethod("setContentView", &BaseWindow::SetContentView) .SetMethod("close", &BaseWindow::Close) .SetMethod("focus", &BaseWindow::Focus) .SetMethod("blur", &BaseWindow::Blur) .SetMethod("isFocused", &BaseWindow::IsFocused) .SetMethod("show", &BaseWindow::Show) .SetMethod("showInactive", &BaseWindow::ShowInactive) .SetMethod("hide", &BaseWindow::Hide) .SetMethod("isVisible", &BaseWindow::IsVisible) .SetMethod("isEnabled", &BaseWindow::IsEnabled) .SetMethod("setEnabled", &BaseWindow::SetEnabled) .SetMethod("maximize", &BaseWindow::Maximize) .SetMethod("unmaximize", &BaseWindow::Unmaximize) .SetMethod("isMaximized", &BaseWindow::IsMaximized) .SetMethod("minimize", &BaseWindow::Minimize) .SetMethod("restore", &BaseWindow::Restore) .SetMethod("isMinimized", &BaseWindow::IsMinimized) .SetMethod("setFullScreen", &BaseWindow::SetFullScreen) .SetMethod("isFullScreen", &BaseWindow::IsFullscreen) .SetMethod("setBounds", &BaseWindow::SetBounds) .SetMethod("getBounds", &BaseWindow::GetBounds) .SetMethod("isNormal", &BaseWindow::IsNormal) .SetMethod("getNormalBounds", &BaseWindow::GetNormalBounds) .SetMethod("setSize", &BaseWindow::SetSize) .SetMethod("getSize", &BaseWindow::GetSize) .SetMethod("setContentBounds", &BaseWindow::SetContentBounds) .SetMethod("getContentBounds", &BaseWindow::GetContentBounds) .SetMethod("setContentSize", &BaseWindow::SetContentSize) .SetMethod("getContentSize", &BaseWindow::GetContentSize) .SetMethod("setMinimumSize", &BaseWindow::SetMinimumSize) .SetMethod("getMinimumSize", &BaseWindow::GetMinimumSize) .SetMethod("setMaximumSize", &BaseWindow::SetMaximumSize) .SetMethod("getMaximumSize", &BaseWindow::GetMaximumSize) .SetMethod("setSheetOffset", &BaseWindow::SetSheetOffset) .SetMethod("moveAbove", &BaseWindow::MoveAbove) .SetMethod("moveTop", &BaseWindow::MoveTop) .SetMethod("setResizable", &BaseWindow::SetResizable) .SetMethod("isResizable", &BaseWindow::IsResizable) .SetMethod("setMovable", &BaseWindow::SetMovable) .SetMethod("isMovable", &BaseWindow::IsMovable) .SetMethod("setMinimizable", &BaseWindow::SetMinimizable) .SetMethod("isMinimizable", &BaseWindow::IsMinimizable) .SetMethod("setMaximizable", &BaseWindow::SetMaximizable) .SetMethod("isMaximizable", &BaseWindow::IsMaximizable) .SetMethod("setFullScreenable", &BaseWindow::SetFullScreenable) .SetMethod("isFullScreenable", &BaseWindow::IsFullScreenable) .SetMethod("setClosable", &BaseWindow::SetClosable) .SetMethod("isClosable", &BaseWindow::IsClosable) .SetMethod("setAlwaysOnTop", &BaseWindow::SetAlwaysOnTop) .SetMethod("isAlwaysOnTop", &BaseWindow::IsAlwaysOnTop) .SetMethod("center", &BaseWindow::Center) .SetMethod("setPosition", &BaseWindow::SetPosition) .SetMethod("getPosition", &BaseWindow::GetPosition) .SetMethod("setTitle", &BaseWindow::SetTitle) .SetMethod("getTitle", &BaseWindow::GetTitle) .SetProperty("accessibleTitle", &BaseWindow::GetAccessibleTitle, &BaseWindow::SetAccessibleTitle) .SetMethod("flashFrame", &BaseWindow::FlashFrame) .SetMethod("setSkipTaskbar", &BaseWindow::SetSkipTaskbar) .SetMethod("setSimpleFullScreen", &BaseWindow::SetSimpleFullScreen) .SetMethod("isSimpleFullScreen", &BaseWindow::IsSimpleFullScreen) .SetMethod("setKiosk", &BaseWindow::SetKiosk) .SetMethod("isKiosk", &BaseWindow::IsKiosk) .SetMethod("isTabletMode", &BaseWindow::IsTabletMode) .SetMethod("setBackgroundColor", &BaseWindow::SetBackgroundColor) .SetMethod("getBackgroundColor", &BaseWindow::GetBackgroundColor) .SetMethod("setHasShadow", &BaseWindow::SetHasShadow) .SetMethod("hasShadow", &BaseWindow::HasShadow) .SetMethod("setOpacity", &BaseWindow::SetOpacity) .SetMethod("getOpacity", &BaseWindow::GetOpacity) .SetMethod("setShape", &BaseWindow::SetShape) .SetMethod("setRepresentedFilename", &BaseWindow::SetRepresentedFilename) .SetMethod("getRepresentedFilename", &BaseWindow::GetRepresentedFilename) .SetMethod("setDocumentEdited", &BaseWindow::SetDocumentEdited) .SetMethod("isDocumentEdited", &BaseWindow::IsDocumentEdited) .SetMethod("setIgnoreMouseEvents", &BaseWindow::SetIgnoreMouseEvents) .SetMethod("setContentProtection", &BaseWindow::SetContentProtection) .SetMethod("setFocusable", &BaseWindow::SetFocusable) .SetMethod("isFocusable", &BaseWindow::IsFocusable) .SetMethod("setMenu", &BaseWindow::SetMenu) .SetMethod("removeMenu", &BaseWindow::RemoveMenu) .SetMethod("setParentWindow", &BaseWindow::SetParentWindow) .SetMethod("setBrowserView", &BaseWindow::SetBrowserView) .SetMethod("addBrowserView", &BaseWindow::AddBrowserView) .SetMethod("removeBrowserView", &BaseWindow::RemoveBrowserView) .SetMethod("setTopBrowserView", &BaseWindow::SetTopBrowserView) .SetMethod("getMediaSourceId", &BaseWindow::GetMediaSourceId) .SetMethod("getNativeWindowHandle", &BaseWindow::GetNativeWindowHandle) .SetMethod("setProgressBar", &BaseWindow::SetProgressBar) .SetMethod("setOverlayIcon", &BaseWindow::SetOverlayIcon) .SetMethod("setVisibleOnAllWorkspaces", &BaseWindow::SetVisibleOnAllWorkspaces) .SetMethod("isVisibleOnAllWorkspaces", &BaseWindow::IsVisibleOnAllWorkspaces) #if BUILDFLAG(IS_MAC) .SetMethod("invalidateShadow", &BaseWindow::InvalidateShadow) .SetMethod("_getAlwaysOnTopLevel", &BaseWindow::GetAlwaysOnTopLevel) .SetMethod("setAutoHideCursor", &BaseWindow::SetAutoHideCursor) #endif .SetMethod("setVibrancy", &BaseWindow::SetVibrancy) .SetMethod("setBackgroundMaterial", &BaseWindow::SetBackgroundMaterial) #if BUILDFLAG(IS_MAC) .SetMethod("isHiddenInMissionControl", &BaseWindow::IsHiddenInMissionControl) .SetMethod("setHiddenInMissionControl", &BaseWindow::SetHiddenInMissionControl) #endif .SetMethod("_setTouchBarItems", &BaseWindow::SetTouchBar) .SetMethod("_refreshTouchBarItem", &BaseWindow::RefreshTouchBarItem) .SetMethod("_setEscapeTouchBarItem", &BaseWindow::SetEscapeTouchBarItem) #if BUILDFLAG(IS_MAC) .SetMethod("selectPreviousTab", &BaseWindow::SelectPreviousTab) .SetMethod("selectNextTab", &BaseWindow::SelectNextTab) .SetMethod("showAllTabs", &BaseWindow::ShowAllTabs) .SetMethod("mergeAllWindows", &BaseWindow::MergeAllWindows) .SetMethod("moveTabToNewWindow", &BaseWindow::MoveTabToNewWindow) .SetMethod("toggleTabBar", &BaseWindow::ToggleTabBar) .SetMethod("addTabbedWindow", &BaseWindow::AddTabbedWindow) .SetMethod("setWindowButtonVisibility", &BaseWindow::SetWindowButtonVisibility) .SetMethod("_getWindowButtonVisibility", &BaseWindow::GetWindowButtonVisibility) .SetMethod("setWindowButtonPosition", &BaseWindow::SetWindowButtonPosition) .SetMethod("getWindowButtonPosition", &BaseWindow::GetWindowButtonPosition) .SetProperty("excludedFromShownWindowsMenu", &BaseWindow::IsExcludedFromShownWindowsMenu, &BaseWindow::SetExcludedFromShownWindowsMenu) #endif .SetMethod("setAutoHideMenuBar", &BaseWindow::SetAutoHideMenuBar) .SetMethod("isMenuBarAutoHide", &BaseWindow::IsMenuBarAutoHide) .SetMethod("setMenuBarVisibility", &BaseWindow::SetMenuBarVisibility) .SetMethod("isMenuBarVisible", &BaseWindow::IsMenuBarVisible) .SetMethod("setAspectRatio", &BaseWindow::SetAspectRatio) .SetMethod("previewFile", &BaseWindow::PreviewFile) .SetMethod("closeFilePreview", &BaseWindow::CloseFilePreview) .SetMethod("getContentView", &BaseWindow::GetContentView) .SetMethod("getParentWindow", &BaseWindow::GetParentWindow) .SetMethod("getChildWindows", &BaseWindow::GetChildWindows) .SetMethod("getBrowserView", &BaseWindow::GetBrowserView) .SetMethod("getBrowserViews", &BaseWindow::GetBrowserViews) .SetMethod("isModal", &BaseWindow::IsModal) .SetMethod("setThumbarButtons", &BaseWindow::SetThumbarButtons) #if defined(TOOLKIT_VIEWS) .SetMethod("setIcon", &BaseWindow::SetIcon) #endif #if BUILDFLAG(IS_WIN) .SetMethod("hookWindowMessage", &BaseWindow::HookWindowMessage) .SetMethod("isWindowMessageHooked", &BaseWindow::IsWindowMessageHooked) .SetMethod("unhookWindowMessage", &BaseWindow::UnhookWindowMessage) .SetMethod("unhookAllWindowMessages", &BaseWindow::UnhookAllWindowMessages) .SetMethod("setThumbnailClip", &BaseWindow::SetThumbnailClip) .SetMethod("setThumbnailToolTip", &BaseWindow::SetThumbnailToolTip) .SetMethod("setAppDetails", &BaseWindow::SetAppDetails) #endif .SetProperty("id", &BaseWindow::GetID); } } // namespace electron::api namespace { using electron::api::BaseWindow; void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused, v8::Local<v8::Context> context, void* priv) { v8::Isolate* isolate = context->GetIsolate(); BaseWindow::SetConstructor(isolate, base::BindRepeating(&BaseWindow::New)); gin_helper::Dictionary constructor(isolate, BaseWindow::GetConstructor(isolate) ->GetFunction(context) .ToLocalChecked()); constructor.SetMethod("fromId", &BaseWindow::FromWeakMapID); constructor.SetMethod("getAllWindows", &BaseWindow::GetAll); gin_helper::Dictionary dict(isolate, exports); dict.Set("BaseWindow", constructor); } } // namespace NODE_LINKED_BINDING_CONTEXT_AWARE(electron_browser_base_window, Initialize)
closed
electron/electron
https://github.com/electron/electron
39,377
[Bug]: removeBrowserView() crashes if view.webContents.close() is called beforehand.
### 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 25.3.0 ### What operating system are you using? macOS ### Operating System Version macOs Ventura 13.4.1 (c) ### What arch are you using? x64 ### Last Known Working Electron version 25.2.0 ### Expected Behavior We are using `browserViews` in a `browserWindow`, when closing our view, we need the `window.close` event to be sent, so I'm using the `view.webContents.close()` to close the window (it's hosting a citrix receiver html5 page) before I call `mainWindow.removeBrowserView()`. Expected behavior is the `browserView` closes, and the `getBrowserViews` list is updated by `removeBrowserView()` call. ### Actual Behavior The `removeBrowserView` call crashes the electron app. In the fiddle it crashes with `Electron exited with signal SIGSEGV.` ### Testcase Gist URL https://gist.github.com/Bill77/1db0aefcd338b612f66e09a9f7372d82 ### Additional Information Attached is a Electron Fiddle with the **add** and **close** buttons. To reproduce, add the view and then close it, which works in `25.2.0` but does not in `25.3.0+`. Looking at the change log, it seem it's related to [this PR](https://github.com/electron/electron/pull/38996). I did try to just use the `webContents.close()` and skip calling `removeBrowserView()` but the view list does not get updated, and we get a list of views that have null `webContents`. Which I suspect is causing the issue in `removeBrowerView()` to crash. We either need a solution where within `removeBrowserView` it calls the `webContents.close` or the logic in `removeBrowserView` needs null checks on the `webContent` references. Sorry, that's my guess based on not looking at the Electron code directly! 🤷‍♂️
https://github.com/electron/electron/issues/39377
https://github.com/electron/electron/pull/39387
1548a2f9fb6d9bf9e0c4f6ace595189cf84b38e9
8f4f82618c51029f91cfb6516bc9c75164bfee9a
2023-08-04T23:22:40Z
c++
2023-08-08T08:23:14Z
shell/browser/api/electron_api_base_window.cc
// Copyright (c) 2018 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_base_window.h" #include <algorithm> #include <string> #include <utility> #include <vector> #include "base/containers/contains.h" #include "base/task/single_thread_task_runner.h" #include "electron/buildflags/buildflags.h" #include "gin/dictionary.h" #include "shell/browser/api/electron_api_browser_view.h" #include "shell/browser/api/electron_api_menu.h" #include "shell/browser/api/electron_api_view.h" #include "shell/browser/api/electron_api_web_contents.h" #include "shell/browser/javascript_environment.h" #include "shell/common/color_util.h" #include "shell/common/gin_converters/callback_converter.h" #include "shell/common/gin_converters/file_path_converter.h" #include "shell/common/gin_converters/gfx_converter.h" #include "shell/common/gin_converters/image_converter.h" #include "shell/common/gin_converters/native_window_converter.h" #include "shell/common/gin_converters/optional_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/gin_helper/persistent_dictionary.h" #include "shell/common/node_includes.h" #include "shell/common/options_switches.h" #if defined(TOOLKIT_VIEWS) #include "shell/browser/native_window_views.h" #endif #if BUILDFLAG(IS_WIN) #include "shell/browser/ui/win/taskbar_host.h" #include "ui/base/win/shell.h" #endif #if BUILDFLAG(IS_WIN) namespace gin { template <> struct Converter<electron::TaskbarHost::ThumbarButton> { static bool FromV8(v8::Isolate* isolate, v8::Handle<v8::Value> val, electron::TaskbarHost::ThumbarButton* out) { gin::Dictionary dict(isolate); if (!gin::ConvertFromV8(isolate, val, &dict)) return false; dict.Get("click", &(out->clicked_callback)); dict.Get("tooltip", &(out->tooltip)); dict.Get("flags", &out->flags); return dict.Get("icon", &(out->icon)); } }; } // namespace gin #endif namespace electron::api { namespace { // Converts binary data to Buffer. v8::Local<v8::Value> ToBuffer(v8::Isolate* isolate, void* val, int size) { auto buffer = node::Buffer::Copy(isolate, static_cast<char*>(val), size); if (buffer.IsEmpty()) return v8::Null(isolate); else return buffer.ToLocalChecked(); } } // namespace BaseWindow::BaseWindow(v8::Isolate* isolate, const gin_helper::Dictionary& options) { // The parent window. gin::Handle<BaseWindow> parent; if (options.Get("parent", &parent) && !parent.IsEmpty()) parent_window_.Reset(isolate, parent.ToV8()); // Offscreen windows are always created frameless. gin_helper::Dictionary web_preferences; bool offscreen; if (options.Get(options::kWebPreferences, &web_preferences) && web_preferences.Get(options::kOffscreen, &offscreen) && offscreen) { const_cast<gin_helper::Dictionary&>(options).Set(options::kFrame, false); } // Creates NativeWindow. window_.reset(NativeWindow::Create( options, parent.IsEmpty() ? nullptr : parent->window_.get())); window_->AddObserver(this); #if defined(TOOLKIT_VIEWS) v8::Local<v8::Value> icon; if (options.Get(options::kIcon, &icon)) { SetIconImpl(isolate, icon, NativeImage::OnConvertError::kWarn); } #endif } BaseWindow::BaseWindow(gin_helper::Arguments* args, const gin_helper::Dictionary& options) : BaseWindow(args->isolate(), options) { InitWithArgs(args); // Init window after everything has been setup. window()->InitFromOptions(options); } BaseWindow::~BaseWindow() { CloseImmediately(); // Destroy the native window in next tick because the native code might be // iterating all windows. base::SingleThreadTaskRunner::GetCurrentDefault()->DeleteSoon( FROM_HERE, window_.release()); // Remove global reference so the JS object can be garbage collected. self_ref_.Reset(); } void BaseWindow::InitWith(v8::Isolate* isolate, v8::Local<v8::Object> wrapper) { AttachAsUserData(window_.get()); gin_helper::TrackableObject<BaseWindow>::InitWith(isolate, wrapper); // We can only append this window to parent window's child windows after this // window's JS wrapper gets initialized. if (!parent_window_.IsEmpty()) { gin::Handle<BaseWindow> parent; gin::ConvertFromV8(isolate, GetParentWindow(), &parent); DCHECK(!parent.IsEmpty()); parent->child_windows_.Set(isolate, weak_map_id(), wrapper); } // Reference this object in case it got garbage collected. self_ref_.Reset(isolate, wrapper); } void BaseWindow::WillCloseWindow(bool* prevent_default) { if (Emit("close")) { *prevent_default = true; } } void BaseWindow::OnWindowClosed() { // Invalidate weak ptrs before the Javascript object is destroyed, // there might be some delayed emit events which shouldn't be // triggered after this. weak_factory_.InvalidateWeakPtrs(); RemoveFromWeakMap(); window_->RemoveObserver(this); // We can not call Destroy here because we need to call Emit first, but we // also do not want any method to be used, so just mark as destroyed here. MarkDestroyed(); Emit("closed"); RemoveFromParentChildWindows(); BaseWindow::ResetBrowserViews(); // Destroy the native class when window is closed. base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask( FROM_HERE, GetDestroyClosure()); } void BaseWindow::OnWindowEndSession() { Emit("session-end"); } void BaseWindow::OnWindowBlur() { EmitEventSoon("blur"); } void BaseWindow::OnWindowFocus() { EmitEventSoon("focus"); } void BaseWindow::OnWindowShow() { Emit("show"); } void BaseWindow::OnWindowHide() { Emit("hide"); } void BaseWindow::OnWindowMaximize() { Emit("maximize"); } void BaseWindow::OnWindowUnmaximize() { Emit("unmaximize"); } void BaseWindow::OnWindowMinimize() { Emit("minimize"); } void BaseWindow::OnWindowRestore() { Emit("restore"); } void BaseWindow::OnWindowWillResize(const gfx::Rect& new_bounds, const gfx::ResizeEdge& edge, bool* prevent_default) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); gin_helper::Dictionary info = gin::Dictionary::CreateEmpty(isolate); info.Set("edge", edge); if (Emit("will-resize", new_bounds, info)) { *prevent_default = true; } } void BaseWindow::OnWindowResize() { Emit("resize"); } void BaseWindow::OnWindowResized() { Emit("resized"); } void BaseWindow::OnWindowWillMove(const gfx::Rect& new_bounds, bool* prevent_default) { if (Emit("will-move", new_bounds)) { *prevent_default = true; } } void BaseWindow::OnWindowMove() { Emit("move"); } void BaseWindow::OnWindowMoved() { Emit("moved"); } void BaseWindow::OnWindowEnterFullScreen() { Emit("enter-full-screen"); } void BaseWindow::OnWindowLeaveFullScreen() { Emit("leave-full-screen"); } void BaseWindow::OnWindowSwipe(const std::string& direction) { Emit("swipe", direction); } void BaseWindow::OnWindowRotateGesture(float rotation) { Emit("rotate-gesture", rotation); } void BaseWindow::OnWindowSheetBegin() { Emit("sheet-begin"); } void BaseWindow::OnWindowSheetEnd() { Emit("sheet-end"); } void BaseWindow::OnWindowEnterHtmlFullScreen() { Emit("enter-html-full-screen"); } void BaseWindow::OnWindowLeaveHtmlFullScreen() { Emit("leave-html-full-screen"); } void BaseWindow::OnWindowAlwaysOnTopChanged() { Emit("always-on-top-changed", IsAlwaysOnTop()); } void BaseWindow::OnExecuteAppCommand(const std::string& command_name) { Emit("app-command", command_name); } void BaseWindow::OnTouchBarItemResult(const std::string& item_id, const base::Value::Dict& details) { Emit("-touch-bar-interaction", item_id, details); } void BaseWindow::OnNewWindowForTab() { Emit("new-window-for-tab"); } void BaseWindow::OnSystemContextMenu(int x, int y, bool* prevent_default) { if (Emit("system-context-menu", gfx::Point(x, y))) { *prevent_default = true; } } #if BUILDFLAG(IS_WIN) void BaseWindow::OnWindowMessage(UINT message, WPARAM w_param, LPARAM l_param) { if (IsWindowMessageHooked(message)) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); messages_callback_map_[message].Run( ToBuffer(isolate, static_cast<void*>(&w_param), sizeof(WPARAM)), ToBuffer(isolate, static_cast<void*>(&l_param), sizeof(LPARAM))); } } #endif void BaseWindow::SetContentView(gin::Handle<View> view) { ResetBrowserViews(); content_view_.Reset(isolate(), view.ToV8()); window_->SetContentView(view->view()); } void BaseWindow::CloseImmediately() { if (!window_->IsClosed()) window_->CloseImmediately(); } void BaseWindow::Close() { window_->Close(); } void BaseWindow::Focus() { window_->Focus(true); } void BaseWindow::Blur() { window_->Focus(false); } bool BaseWindow::IsFocused() { return window_->IsFocused(); } void BaseWindow::Show() { window_->Show(); } void BaseWindow::ShowInactive() { // This method doesn't make sense for modal window. if (IsModal()) return; window_->ShowInactive(); } void BaseWindow::Hide() { window_->Hide(); } bool BaseWindow::IsVisible() { return window_->IsVisible(); } bool BaseWindow::IsEnabled() { return window_->IsEnabled(); } void BaseWindow::SetEnabled(bool enable) { window_->SetEnabled(enable); } void BaseWindow::Maximize() { window_->Maximize(); } void BaseWindow::Unmaximize() { window_->Unmaximize(); } bool BaseWindow::IsMaximized() { return window_->IsMaximized(); } void BaseWindow::Minimize() { window_->Minimize(); } void BaseWindow::Restore() { window_->Restore(); } bool BaseWindow::IsMinimized() { return window_->IsMinimized(); } void BaseWindow::SetFullScreen(bool fullscreen) { window_->SetFullScreen(fullscreen); } bool BaseWindow::IsFullscreen() { return window_->IsFullscreen(); } void BaseWindow::SetBounds(const gfx::Rect& bounds, gin_helper::Arguments* args) { bool animate = false; args->GetNext(&animate); window_->SetBounds(bounds, animate); } gfx::Rect BaseWindow::GetBounds() { return window_->GetBounds(); } bool BaseWindow::IsNormal() { return window_->IsNormal(); } gfx::Rect BaseWindow::GetNormalBounds() { return window_->GetNormalBounds(); } void BaseWindow::SetContentBounds(const gfx::Rect& bounds, gin_helper::Arguments* args) { bool animate = false; args->GetNext(&animate); window_->SetContentBounds(bounds, animate); } gfx::Rect BaseWindow::GetContentBounds() { return window_->GetContentBounds(); } void BaseWindow::SetSize(int width, int height, gin_helper::Arguments* args) { bool animate = false; gfx::Size size = window_->GetMinimumSize(); size.SetToMax(gfx::Size(width, height)); args->GetNext(&animate); window_->SetSize(size, animate); } std::vector<int> BaseWindow::GetSize() { std::vector<int> result(2); gfx::Size size = window_->GetSize(); result[0] = size.width(); result[1] = size.height(); return result; } void BaseWindow::SetContentSize(int width, int height, gin_helper::Arguments* args) { bool animate = false; args->GetNext(&animate); window_->SetContentSize(gfx::Size(width, height), animate); } std::vector<int> BaseWindow::GetContentSize() { std::vector<int> result(2); gfx::Size size = window_->GetContentSize(); result[0] = size.width(); result[1] = size.height(); return result; } void BaseWindow::SetMinimumSize(int width, int height) { window_->SetMinimumSize(gfx::Size(width, height)); } std::vector<int> BaseWindow::GetMinimumSize() { std::vector<int> result(2); gfx::Size size = window_->GetMinimumSize(); result[0] = size.width(); result[1] = size.height(); return result; } void BaseWindow::SetMaximumSize(int width, int height) { window_->SetMaximumSize(gfx::Size(width, height)); } std::vector<int> BaseWindow::GetMaximumSize() { std::vector<int> result(2); gfx::Size size = window_->GetMaximumSize(); result[0] = size.width(); result[1] = size.height(); return result; } void BaseWindow::SetSheetOffset(double offsetY, gin_helper::Arguments* args) { double offsetX = 0.0; args->GetNext(&offsetX); window_->SetSheetOffset(offsetX, offsetY); } void BaseWindow::SetResizable(bool resizable) { window_->SetResizable(resizable); } bool BaseWindow::IsResizable() { return window_->IsResizable(); } void BaseWindow::SetMovable(bool movable) { window_->SetMovable(movable); } bool BaseWindow::IsMovable() { return window_->IsMovable(); } void BaseWindow::SetMinimizable(bool minimizable) { window_->SetMinimizable(minimizable); } bool BaseWindow::IsMinimizable() { return window_->IsMinimizable(); } void BaseWindow::SetMaximizable(bool maximizable) { window_->SetMaximizable(maximizable); } bool BaseWindow::IsMaximizable() { return window_->IsMaximizable(); } void BaseWindow::SetFullScreenable(bool fullscreenable) { window_->SetFullScreenable(fullscreenable); } bool BaseWindow::IsFullScreenable() { return window_->IsFullScreenable(); } void BaseWindow::SetClosable(bool closable) { window_->SetClosable(closable); } bool BaseWindow::IsClosable() { return window_->IsClosable(); } void BaseWindow::SetAlwaysOnTop(bool top, gin_helper::Arguments* args) { std::string level = "floating"; int relative_level = 0; args->GetNext(&level); args->GetNext(&relative_level); ui::ZOrderLevel z_order = top ? ui::ZOrderLevel::kFloatingWindow : ui::ZOrderLevel::kNormal; window_->SetAlwaysOnTop(z_order, level, relative_level); } bool BaseWindow::IsAlwaysOnTop() { return window_->GetZOrderLevel() != ui::ZOrderLevel::kNormal; } void BaseWindow::Center() { window_->Center(); } void BaseWindow::SetPosition(int x, int y, gin_helper::Arguments* args) { bool animate = false; args->GetNext(&animate); window_->SetPosition(gfx::Point(x, y), animate); } std::vector<int> BaseWindow::GetPosition() { std::vector<int> result(2); gfx::Point pos = window_->GetPosition(); result[0] = pos.x(); result[1] = pos.y(); return result; } void BaseWindow::MoveAbove(const std::string& sourceId, gin_helper::Arguments* args) { if (!window_->MoveAbove(sourceId)) args->ThrowError("Invalid media source id"); } void BaseWindow::MoveTop() { window_->MoveTop(); } void BaseWindow::SetTitle(const std::string& title) { window_->SetTitle(title); } std::string BaseWindow::GetTitle() { return window_->GetTitle(); } void BaseWindow::SetAccessibleTitle(const std::string& title) { window_->SetAccessibleTitle(title); } std::string BaseWindow::GetAccessibleTitle() { return window_->GetAccessibleTitle(); } void BaseWindow::FlashFrame(bool flash) { window_->FlashFrame(flash); } void BaseWindow::SetSkipTaskbar(bool skip) { window_->SetSkipTaskbar(skip); } void BaseWindow::SetExcludedFromShownWindowsMenu(bool excluded) { window_->SetExcludedFromShownWindowsMenu(excluded); } bool BaseWindow::IsExcludedFromShownWindowsMenu() { return window_->IsExcludedFromShownWindowsMenu(); } void BaseWindow::SetSimpleFullScreen(bool simple_fullscreen) { window_->SetSimpleFullScreen(simple_fullscreen); } bool BaseWindow::IsSimpleFullScreen() { return window_->IsSimpleFullScreen(); } void BaseWindow::SetKiosk(bool kiosk) { window_->SetKiosk(kiosk); } bool BaseWindow::IsKiosk() { return window_->IsKiosk(); } bool BaseWindow::IsTabletMode() const { return window_->IsTabletMode(); } void BaseWindow::SetBackgroundColor(const std::string& color_name) { SkColor color = ParseCSSColor(color_name); window_->SetBackgroundColor(color); } std::string BaseWindow::GetBackgroundColor(gin_helper::Arguments* args) { return ToRGBHex(window_->GetBackgroundColor()); } void BaseWindow::InvalidateShadow() { window_->InvalidateShadow(); } void BaseWindow::SetHasShadow(bool has_shadow) { window_->SetHasShadow(has_shadow); } bool BaseWindow::HasShadow() { return window_->HasShadow(); } void BaseWindow::SetOpacity(const double opacity) { window_->SetOpacity(opacity); } double BaseWindow::GetOpacity() { return window_->GetOpacity(); } void BaseWindow::SetShape(const std::vector<gfx::Rect>& rects) { window_->widget()->SetShape(std::make_unique<std::vector<gfx::Rect>>(rects)); } void BaseWindow::SetRepresentedFilename(const std::string& filename) { window_->SetRepresentedFilename(filename); } std::string BaseWindow::GetRepresentedFilename() { return window_->GetRepresentedFilename(); } void BaseWindow::SetDocumentEdited(bool edited) { window_->SetDocumentEdited(edited); } bool BaseWindow::IsDocumentEdited() { return window_->IsDocumentEdited(); } void BaseWindow::SetIgnoreMouseEvents(bool ignore, gin_helper::Arguments* args) { gin_helper::Dictionary options; bool forward = false; args->GetNext(&options) && options.Get("forward", &forward); return window_->SetIgnoreMouseEvents(ignore, forward); } void BaseWindow::SetContentProtection(bool enable) { return window_->SetContentProtection(enable); } void BaseWindow::SetFocusable(bool focusable) { return window_->SetFocusable(focusable); } bool BaseWindow::IsFocusable() { return window_->IsFocusable(); } void BaseWindow::SetMenu(v8::Isolate* isolate, v8::Local<v8::Value> value) { auto context = isolate->GetCurrentContext(); gin::Handle<Menu> menu; v8::Local<v8::Object> object; if (value->IsObject() && value->ToObject(context).ToLocal(&object) && gin::ConvertFromV8(isolate, value, &menu) && !menu.IsEmpty()) { // We only want to update the menu if the menu has a non-zero item count, // or we risk crashes. if (menu->model()->GetItemCount() == 0) { RemoveMenu(); } else { window_->SetMenu(menu->model()); } menu_.Reset(isolate, menu.ToV8()); } else if (value->IsNull()) { RemoveMenu(); } else { isolate->ThrowException( v8::Exception::TypeError(gin::StringToV8(isolate, "Invalid Menu"))); } } void BaseWindow::RemoveMenu() { menu_.Reset(); window_->SetMenu(nullptr); } void BaseWindow::SetParentWindow(v8::Local<v8::Value> value, gin_helper::Arguments* args) { if (IsModal()) { args->ThrowError("Can not be called for modal window"); return; } gin::Handle<BaseWindow> parent; if (value->IsNull() || value->IsUndefined()) { RemoveFromParentChildWindows(); parent_window_.Reset(); window_->SetParentWindow(nullptr); } else if (gin::ConvertFromV8(isolate(), value, &parent)) { RemoveFromParentChildWindows(); parent_window_.Reset(isolate(), value); window_->SetParentWindow(parent->window_.get()); parent->child_windows_.Set(isolate(), weak_map_id(), GetWrapper()); } else { args->ThrowError("Must pass BaseWindow instance or null"); } } void BaseWindow::SetBrowserView( absl::optional<gin::Handle<BrowserView>> browser_view) { ResetBrowserViews(); if (browser_view) AddBrowserView(*browser_view); } void BaseWindow::AddBrowserView(gin::Handle<BrowserView> browser_view) { if (!base::Contains(browser_views_, browser_view.ToV8())) { // If we're reparenting a BrowserView, ensure that it's detached from // its previous owner window. BaseWindow* owner_window = browser_view->owner_window(); if (owner_window) { // iter == browser_views_.end() should imply owner_window != this. DCHECK_NE(owner_window, this); owner_window->RemoveBrowserView(browser_view); browser_view->SetOwnerWindow(nullptr); } window_->AddBrowserView(browser_view->view()); window_->AddDraggableRegionProvider(browser_view.get()); browser_view->SetOwnerWindow(this); browser_views_.emplace_back().Reset(isolate(), browser_view.ToV8()); } } void BaseWindow::RemoveBrowserView(gin::Handle<BrowserView> browser_view) { auto iter = std::find(browser_views_.begin(), browser_views_.end(), browser_view.ToV8()); if (iter != browser_views_.end()) { window_->RemoveBrowserView(browser_view->view()); window_->RemoveDraggableRegionProvider(browser_view.get()); browser_view->SetOwnerWindow(nullptr); iter->Reset(); browser_views_.erase(iter); } } void BaseWindow::SetTopBrowserView(gin::Handle<BrowserView> browser_view, gin_helper::Arguments* args) { BaseWindow* owner_window = browser_view->owner_window(); auto iter = std::find(browser_views_.begin(), browser_views_.end(), browser_view.ToV8()); if (iter == browser_views_.end() || (owner_window && owner_window != this)) { args->ThrowError("Given BrowserView is not attached to the window"); return; } browser_views_.erase(iter); browser_views_.emplace_back().Reset(isolate(), browser_view.ToV8()); window_->SetTopBrowserView(browser_view->view()); } std::string BaseWindow::GetMediaSourceId() const { return window_->GetDesktopMediaID().ToString(); } v8::Local<v8::Value> BaseWindow::GetNativeWindowHandle() { // TODO(MarshallOfSound): Replace once // https://chromium-review.googlesource.com/c/chromium/src/+/1253094/ has // landed NativeWindowHandle handle = window_->GetNativeWindowHandle(); return ToBuffer(isolate(), &handle, sizeof(handle)); } void BaseWindow::SetProgressBar(double progress, gin_helper::Arguments* args) { gin_helper::Dictionary options; std::string mode; args->GetNext(&options) && options.Get("mode", &mode); NativeWindow::ProgressState state = NativeWindow::ProgressState::kNormal; if (mode == "error") state = NativeWindow::ProgressState::kError; else if (mode == "paused") state = NativeWindow::ProgressState::kPaused; else if (mode == "indeterminate") state = NativeWindow::ProgressState::kIndeterminate; else if (mode == "none") state = NativeWindow::ProgressState::kNone; window_->SetProgressBar(progress, state); } void BaseWindow::SetOverlayIcon(const gfx::Image& overlay, const std::string& description) { window_->SetOverlayIcon(overlay, description); } void BaseWindow::SetVisibleOnAllWorkspaces(bool visible, gin_helper::Arguments* args) { gin_helper::Dictionary options; bool visibleOnFullScreen = false; bool skipTransformProcessType = false; if (args->GetNext(&options)) { options.Get("visibleOnFullScreen", &visibleOnFullScreen); options.Get("skipTransformProcessType", &skipTransformProcessType); } return window_->SetVisibleOnAllWorkspaces(visible, visibleOnFullScreen, skipTransformProcessType); } bool BaseWindow::IsVisibleOnAllWorkspaces() { return window_->IsVisibleOnAllWorkspaces(); } void BaseWindow::SetAutoHideCursor(bool auto_hide) { window_->SetAutoHideCursor(auto_hide); } void BaseWindow::SetVibrancy(v8::Isolate* isolate, v8::Local<v8::Value> value) { std::string type = gin::V8ToString(isolate, value); window_->SetVibrancy(type); } void BaseWindow::SetBackgroundMaterial(const std::string& material_type) { window_->SetBackgroundMaterial(material_type); } #if BUILDFLAG(IS_MAC) std::string BaseWindow::GetAlwaysOnTopLevel() { return window_->GetAlwaysOnTopLevel(); } void BaseWindow::SetWindowButtonVisibility(bool visible) { window_->SetWindowButtonVisibility(visible); } bool BaseWindow::GetWindowButtonVisibility() const { return window_->GetWindowButtonVisibility(); } void BaseWindow::SetWindowButtonPosition(absl::optional<gfx::Point> position) { window_->SetWindowButtonPosition(std::move(position)); } absl::optional<gfx::Point> BaseWindow::GetWindowButtonPosition() const { return window_->GetWindowButtonPosition(); } #endif #if BUILDFLAG(IS_MAC) bool BaseWindow::IsHiddenInMissionControl() { return window_->IsHiddenInMissionControl(); } void BaseWindow::SetHiddenInMissionControl(bool hidden) { window_->SetHiddenInMissionControl(hidden); } #endif void BaseWindow::SetTouchBar( std::vector<gin_helper::PersistentDictionary> items) { window_->SetTouchBar(std::move(items)); } void BaseWindow::RefreshTouchBarItem(const std::string& item_id) { window_->RefreshTouchBarItem(item_id); } void BaseWindow::SetEscapeTouchBarItem(gin_helper::PersistentDictionary item) { window_->SetEscapeTouchBarItem(std::move(item)); } void BaseWindow::SelectPreviousTab() { window_->SelectPreviousTab(); } void BaseWindow::SelectNextTab() { window_->SelectNextTab(); } void BaseWindow::ShowAllTabs() { window_->ShowAllTabs(); } void BaseWindow::MergeAllWindows() { window_->MergeAllWindows(); } void BaseWindow::MoveTabToNewWindow() { window_->MoveTabToNewWindow(); } void BaseWindow::ToggleTabBar() { window_->ToggleTabBar(); } void BaseWindow::AddTabbedWindow(NativeWindow* window, gin_helper::Arguments* args) { if (!window_->AddTabbedWindow(window)) args->ThrowError("AddTabbedWindow cannot be called by a window on itself."); } void BaseWindow::SetAutoHideMenuBar(bool auto_hide) { window_->SetAutoHideMenuBar(auto_hide); } bool BaseWindow::IsMenuBarAutoHide() { return window_->IsMenuBarAutoHide(); } void BaseWindow::SetMenuBarVisibility(bool visible) { window_->SetMenuBarVisibility(visible); } bool BaseWindow::IsMenuBarVisible() { return window_->IsMenuBarVisible(); } void BaseWindow::SetAspectRatio(double aspect_ratio, gin_helper::Arguments* args) { gfx::Size extra_size; args->GetNext(&extra_size); window_->SetAspectRatio(aspect_ratio, extra_size); } void BaseWindow::PreviewFile(const std::string& path, gin_helper::Arguments* args) { std::string display_name; if (!args->GetNext(&display_name)) display_name = path; window_->PreviewFile(path, display_name); } void BaseWindow::CloseFilePreview() { window_->CloseFilePreview(); } void BaseWindow::SetGTKDarkThemeEnabled(bool use_dark_theme) { window_->SetGTKDarkThemeEnabled(use_dark_theme); } v8::Local<v8::Value> BaseWindow::GetContentView() const { if (content_view_.IsEmpty()) return v8::Null(isolate()); else return v8::Local<v8::Value>::New(isolate(), content_view_); } v8::Local<v8::Value> BaseWindow::GetParentWindow() const { if (parent_window_.IsEmpty()) return v8::Null(isolate()); else return v8::Local<v8::Value>::New(isolate(), parent_window_); } std::vector<v8::Local<v8::Object>> BaseWindow::GetChildWindows() const { return child_windows_.Values(isolate()); } v8::Local<v8::Value> BaseWindow::GetBrowserView( gin_helper::Arguments* args) const { if (browser_views_.empty()) { return v8::Null(isolate()); } else if (browser_views_.size() == 1) { auto first_view = browser_views_.begin(); return v8::Local<v8::Value>::New(isolate(), *first_view); } else { args->ThrowError( "BrowserWindow have multiple BrowserViews, " "Use getBrowserViews() instead"); return v8::Null(isolate()); } } std::vector<v8::Local<v8::Value>> BaseWindow::GetBrowserViews() const { std::vector<v8::Local<v8::Value>> ret; for (auto const& browser_view : browser_views_) { ret.push_back(v8::Local<v8::Value>::New(isolate(), browser_view)); } return ret; } bool BaseWindow::IsModal() const { return window_->is_modal(); } bool BaseWindow::SetThumbarButtons(gin_helper::Arguments* args) { #if BUILDFLAG(IS_WIN) std::vector<TaskbarHost::ThumbarButton> buttons; if (!args->GetNext(&buttons)) { args->ThrowError(); return false; } auto* window = static_cast<NativeWindowViews*>(window_.get()); return window->taskbar_host().SetThumbarButtons( window_->GetAcceleratedWidget(), buttons); #else return false; #endif } #if defined(TOOLKIT_VIEWS) void BaseWindow::SetIcon(v8::Isolate* isolate, v8::Local<v8::Value> icon) { SetIconImpl(isolate, icon, NativeImage::OnConvertError::kThrow); } void BaseWindow::SetIconImpl(v8::Isolate* isolate, v8::Local<v8::Value> icon, NativeImage::OnConvertError on_error) { NativeImage* native_image = nullptr; if (!NativeImage::TryConvertNativeImage(isolate, icon, &native_image, on_error)) return; #if BUILDFLAG(IS_WIN) static_cast<NativeWindowViews*>(window_.get()) ->SetIcon(native_image->GetHICON(GetSystemMetrics(SM_CXSMICON)), native_image->GetHICON(GetSystemMetrics(SM_CXICON))); #elif BUILDFLAG(IS_LINUX) static_cast<NativeWindowViews*>(window_.get()) ->SetIcon(native_image->image().AsImageSkia()); #endif } #endif #if BUILDFLAG(IS_WIN) bool BaseWindow::HookWindowMessage(UINT message, const MessageCallback& callback) { messages_callback_map_[message] = callback; return true; } void BaseWindow::UnhookWindowMessage(UINT message) { messages_callback_map_.erase(message); } bool BaseWindow::IsWindowMessageHooked(UINT message) { return base::Contains(messages_callback_map_, message); } void BaseWindow::UnhookAllWindowMessages() { messages_callback_map_.clear(); } bool BaseWindow::SetThumbnailClip(const gfx::Rect& region) { auto* window = static_cast<NativeWindowViews*>(window_.get()); return window->taskbar_host().SetThumbnailClip( window_->GetAcceleratedWidget(), region); } bool BaseWindow::SetThumbnailToolTip(const std::string& tooltip) { auto* window = static_cast<NativeWindowViews*>(window_.get()); return window->taskbar_host().SetThumbnailToolTip( window_->GetAcceleratedWidget(), tooltip); } void BaseWindow::SetAppDetails(const gin_helper::Dictionary& options) { std::wstring app_id; base::FilePath app_icon_path; int app_icon_index = 0; std::wstring relaunch_command; std::wstring relaunch_display_name; options.Get("appId", &app_id); options.Get("appIconPath", &app_icon_path); options.Get("appIconIndex", &app_icon_index); options.Get("relaunchCommand", &relaunch_command); options.Get("relaunchDisplayName", &relaunch_display_name); ui::win::SetAppDetailsForWindow(app_id, app_icon_path, app_icon_index, relaunch_command, relaunch_display_name, window_->GetAcceleratedWidget()); } #endif int32_t BaseWindow::GetID() const { return weak_map_id(); } void BaseWindow::ResetBrowserViews() { v8::HandleScope scope(isolate()); for (auto& item : browser_views_) { gin::Handle<BrowserView> browser_view; if (gin::ConvertFromV8(isolate(), v8::Local<v8::Value>::New(isolate(), item), &browser_view) && !browser_view.IsEmpty()) { // There's a chance that the BrowserView may have been reparented - only // reset if the owner window is *this* window. BaseWindow* owner_window = browser_view->owner_window(); DCHECK_EQ(owner_window, this); browser_view->SetOwnerWindow(nullptr); window_->RemoveBrowserView(browser_view->view()); window_->RemoveDraggableRegionProvider(browser_view.get()); browser_view->SetOwnerWindow(nullptr); } item.Reset(); } browser_views_.clear(); } void BaseWindow::RemoveFromParentChildWindows() { if (parent_window_.IsEmpty()) return; gin::Handle<BaseWindow> parent; if (!gin::ConvertFromV8(isolate(), GetParentWindow(), &parent) || parent.IsEmpty()) { return; } parent->child_windows_.Remove(weak_map_id()); } // static gin_helper::WrappableBase* BaseWindow::New(gin_helper::Arguments* args) { gin_helper::Dictionary options = gin::Dictionary::CreateEmpty(args->isolate()); args->GetNext(&options); return new BaseWindow(args, options); } // static void BaseWindow::BuildPrototype(v8::Isolate* isolate, v8::Local<v8::FunctionTemplate> prototype) { prototype->SetClassName(gin::StringToV8(isolate, "BaseWindow")); gin_helper::Destroyable::MakeDestroyable(isolate, prototype); gin_helper::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate()) .SetMethod("setContentView", &BaseWindow::SetContentView) .SetMethod("close", &BaseWindow::Close) .SetMethod("focus", &BaseWindow::Focus) .SetMethod("blur", &BaseWindow::Blur) .SetMethod("isFocused", &BaseWindow::IsFocused) .SetMethod("show", &BaseWindow::Show) .SetMethod("showInactive", &BaseWindow::ShowInactive) .SetMethod("hide", &BaseWindow::Hide) .SetMethod("isVisible", &BaseWindow::IsVisible) .SetMethod("isEnabled", &BaseWindow::IsEnabled) .SetMethod("setEnabled", &BaseWindow::SetEnabled) .SetMethod("maximize", &BaseWindow::Maximize) .SetMethod("unmaximize", &BaseWindow::Unmaximize) .SetMethod("isMaximized", &BaseWindow::IsMaximized) .SetMethod("minimize", &BaseWindow::Minimize) .SetMethod("restore", &BaseWindow::Restore) .SetMethod("isMinimized", &BaseWindow::IsMinimized) .SetMethod("setFullScreen", &BaseWindow::SetFullScreen) .SetMethod("isFullScreen", &BaseWindow::IsFullscreen) .SetMethod("setBounds", &BaseWindow::SetBounds) .SetMethod("getBounds", &BaseWindow::GetBounds) .SetMethod("isNormal", &BaseWindow::IsNormal) .SetMethod("getNormalBounds", &BaseWindow::GetNormalBounds) .SetMethod("setSize", &BaseWindow::SetSize) .SetMethod("getSize", &BaseWindow::GetSize) .SetMethod("setContentBounds", &BaseWindow::SetContentBounds) .SetMethod("getContentBounds", &BaseWindow::GetContentBounds) .SetMethod("setContentSize", &BaseWindow::SetContentSize) .SetMethod("getContentSize", &BaseWindow::GetContentSize) .SetMethod("setMinimumSize", &BaseWindow::SetMinimumSize) .SetMethod("getMinimumSize", &BaseWindow::GetMinimumSize) .SetMethod("setMaximumSize", &BaseWindow::SetMaximumSize) .SetMethod("getMaximumSize", &BaseWindow::GetMaximumSize) .SetMethod("setSheetOffset", &BaseWindow::SetSheetOffset) .SetMethod("moveAbove", &BaseWindow::MoveAbove) .SetMethod("moveTop", &BaseWindow::MoveTop) .SetMethod("setResizable", &BaseWindow::SetResizable) .SetMethod("isResizable", &BaseWindow::IsResizable) .SetMethod("setMovable", &BaseWindow::SetMovable) .SetMethod("isMovable", &BaseWindow::IsMovable) .SetMethod("setMinimizable", &BaseWindow::SetMinimizable) .SetMethod("isMinimizable", &BaseWindow::IsMinimizable) .SetMethod("setMaximizable", &BaseWindow::SetMaximizable) .SetMethod("isMaximizable", &BaseWindow::IsMaximizable) .SetMethod("setFullScreenable", &BaseWindow::SetFullScreenable) .SetMethod("isFullScreenable", &BaseWindow::IsFullScreenable) .SetMethod("setClosable", &BaseWindow::SetClosable) .SetMethod("isClosable", &BaseWindow::IsClosable) .SetMethod("setAlwaysOnTop", &BaseWindow::SetAlwaysOnTop) .SetMethod("isAlwaysOnTop", &BaseWindow::IsAlwaysOnTop) .SetMethod("center", &BaseWindow::Center) .SetMethod("setPosition", &BaseWindow::SetPosition) .SetMethod("getPosition", &BaseWindow::GetPosition) .SetMethod("setTitle", &BaseWindow::SetTitle) .SetMethod("getTitle", &BaseWindow::GetTitle) .SetProperty("accessibleTitle", &BaseWindow::GetAccessibleTitle, &BaseWindow::SetAccessibleTitle) .SetMethod("flashFrame", &BaseWindow::FlashFrame) .SetMethod("setSkipTaskbar", &BaseWindow::SetSkipTaskbar) .SetMethod("setSimpleFullScreen", &BaseWindow::SetSimpleFullScreen) .SetMethod("isSimpleFullScreen", &BaseWindow::IsSimpleFullScreen) .SetMethod("setKiosk", &BaseWindow::SetKiosk) .SetMethod("isKiosk", &BaseWindow::IsKiosk) .SetMethod("isTabletMode", &BaseWindow::IsTabletMode) .SetMethod("setBackgroundColor", &BaseWindow::SetBackgroundColor) .SetMethod("getBackgroundColor", &BaseWindow::GetBackgroundColor) .SetMethod("setHasShadow", &BaseWindow::SetHasShadow) .SetMethod("hasShadow", &BaseWindow::HasShadow) .SetMethod("setOpacity", &BaseWindow::SetOpacity) .SetMethod("getOpacity", &BaseWindow::GetOpacity) .SetMethod("setShape", &BaseWindow::SetShape) .SetMethod("setRepresentedFilename", &BaseWindow::SetRepresentedFilename) .SetMethod("getRepresentedFilename", &BaseWindow::GetRepresentedFilename) .SetMethod("setDocumentEdited", &BaseWindow::SetDocumentEdited) .SetMethod("isDocumentEdited", &BaseWindow::IsDocumentEdited) .SetMethod("setIgnoreMouseEvents", &BaseWindow::SetIgnoreMouseEvents) .SetMethod("setContentProtection", &BaseWindow::SetContentProtection) .SetMethod("setFocusable", &BaseWindow::SetFocusable) .SetMethod("isFocusable", &BaseWindow::IsFocusable) .SetMethod("setMenu", &BaseWindow::SetMenu) .SetMethod("removeMenu", &BaseWindow::RemoveMenu) .SetMethod("setParentWindow", &BaseWindow::SetParentWindow) .SetMethod("setBrowserView", &BaseWindow::SetBrowserView) .SetMethod("addBrowserView", &BaseWindow::AddBrowserView) .SetMethod("removeBrowserView", &BaseWindow::RemoveBrowserView) .SetMethod("setTopBrowserView", &BaseWindow::SetTopBrowserView) .SetMethod("getMediaSourceId", &BaseWindow::GetMediaSourceId) .SetMethod("getNativeWindowHandle", &BaseWindow::GetNativeWindowHandle) .SetMethod("setProgressBar", &BaseWindow::SetProgressBar) .SetMethod("setOverlayIcon", &BaseWindow::SetOverlayIcon) .SetMethod("setVisibleOnAllWorkspaces", &BaseWindow::SetVisibleOnAllWorkspaces) .SetMethod("isVisibleOnAllWorkspaces", &BaseWindow::IsVisibleOnAllWorkspaces) #if BUILDFLAG(IS_MAC) .SetMethod("invalidateShadow", &BaseWindow::InvalidateShadow) .SetMethod("_getAlwaysOnTopLevel", &BaseWindow::GetAlwaysOnTopLevel) .SetMethod("setAutoHideCursor", &BaseWindow::SetAutoHideCursor) #endif .SetMethod("setVibrancy", &BaseWindow::SetVibrancy) .SetMethod("setBackgroundMaterial", &BaseWindow::SetBackgroundMaterial) #if BUILDFLAG(IS_MAC) .SetMethod("isHiddenInMissionControl", &BaseWindow::IsHiddenInMissionControl) .SetMethod("setHiddenInMissionControl", &BaseWindow::SetHiddenInMissionControl) #endif .SetMethod("_setTouchBarItems", &BaseWindow::SetTouchBar) .SetMethod("_refreshTouchBarItem", &BaseWindow::RefreshTouchBarItem) .SetMethod("_setEscapeTouchBarItem", &BaseWindow::SetEscapeTouchBarItem) #if BUILDFLAG(IS_MAC) .SetMethod("selectPreviousTab", &BaseWindow::SelectPreviousTab) .SetMethod("selectNextTab", &BaseWindow::SelectNextTab) .SetMethod("showAllTabs", &BaseWindow::ShowAllTabs) .SetMethod("mergeAllWindows", &BaseWindow::MergeAllWindows) .SetMethod("moveTabToNewWindow", &BaseWindow::MoveTabToNewWindow) .SetMethod("toggleTabBar", &BaseWindow::ToggleTabBar) .SetMethod("addTabbedWindow", &BaseWindow::AddTabbedWindow) .SetMethod("setWindowButtonVisibility", &BaseWindow::SetWindowButtonVisibility) .SetMethod("_getWindowButtonVisibility", &BaseWindow::GetWindowButtonVisibility) .SetMethod("setWindowButtonPosition", &BaseWindow::SetWindowButtonPosition) .SetMethod("getWindowButtonPosition", &BaseWindow::GetWindowButtonPosition) .SetProperty("excludedFromShownWindowsMenu", &BaseWindow::IsExcludedFromShownWindowsMenu, &BaseWindow::SetExcludedFromShownWindowsMenu) #endif .SetMethod("setAutoHideMenuBar", &BaseWindow::SetAutoHideMenuBar) .SetMethod("isMenuBarAutoHide", &BaseWindow::IsMenuBarAutoHide) .SetMethod("setMenuBarVisibility", &BaseWindow::SetMenuBarVisibility) .SetMethod("isMenuBarVisible", &BaseWindow::IsMenuBarVisible) .SetMethod("setAspectRatio", &BaseWindow::SetAspectRatio) .SetMethod("previewFile", &BaseWindow::PreviewFile) .SetMethod("closeFilePreview", &BaseWindow::CloseFilePreview) .SetMethod("getContentView", &BaseWindow::GetContentView) .SetMethod("getParentWindow", &BaseWindow::GetParentWindow) .SetMethod("getChildWindows", &BaseWindow::GetChildWindows) .SetMethod("getBrowserView", &BaseWindow::GetBrowserView) .SetMethod("getBrowserViews", &BaseWindow::GetBrowserViews) .SetMethod("isModal", &BaseWindow::IsModal) .SetMethod("setThumbarButtons", &BaseWindow::SetThumbarButtons) #if defined(TOOLKIT_VIEWS) .SetMethod("setIcon", &BaseWindow::SetIcon) #endif #if BUILDFLAG(IS_WIN) .SetMethod("hookWindowMessage", &BaseWindow::HookWindowMessage) .SetMethod("isWindowMessageHooked", &BaseWindow::IsWindowMessageHooked) .SetMethod("unhookWindowMessage", &BaseWindow::UnhookWindowMessage) .SetMethod("unhookAllWindowMessages", &BaseWindow::UnhookAllWindowMessages) .SetMethod("setThumbnailClip", &BaseWindow::SetThumbnailClip) .SetMethod("setThumbnailToolTip", &BaseWindow::SetThumbnailToolTip) .SetMethod("setAppDetails", &BaseWindow::SetAppDetails) #endif .SetProperty("id", &BaseWindow::GetID); } } // namespace electron::api namespace { using electron::api::BaseWindow; void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused, v8::Local<v8::Context> context, void* priv) { v8::Isolate* isolate = context->GetIsolate(); BaseWindow::SetConstructor(isolate, base::BindRepeating(&BaseWindow::New)); gin_helper::Dictionary constructor(isolate, BaseWindow::GetConstructor(isolate) ->GetFunction(context) .ToLocalChecked()); constructor.SetMethod("fromId", &BaseWindow::FromWeakMapID); constructor.SetMethod("getAllWindows", &BaseWindow::GetAll); gin_helper::Dictionary dict(isolate, exports); dict.Set("BaseWindow", constructor); } } // namespace NODE_LINKED_BINDING_CONTEXT_AWARE(electron_browser_base_window, Initialize)
closed
electron/electron
https://github.com/electron/electron
39,288
[Bug]: js-flags 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 25.3.1 ### What operating system are you using? macOS ### Operating System Version 10.15.7 ### What arch are you using? x64 ### Last Known Working Electron version no test ### Expected Behavior `electron --js-flags="--enable-source-maps" .` makes node supports sourcemap ### Actual Behavior Error: unrecognized flag --enable-source-maps Try --help for options ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/39288
https://github.com/electron/electron/pull/39465
1d20ec5b990085fb38cc0494435cd6f57e0e8b3e
22429e21129bd22c06c23f7d714b96d31063d495
2023-07-30T11:40:10Z
c++
2023-08-15T18:49:21Z
docs/api/command-line-switches.md
# Supported Command Line Switches > Command line switches supported by Electron. You can use [app.commandLine.appendSwitch][append-switch] to append them in your app's main script before the [ready][ready] event of the [app][app] module is emitted: ```javascript const { app } = require('electron') app.commandLine.appendSwitch('remote-debugging-port', '8315') app.commandLine.appendSwitch('host-rules', 'MAP * 127.0.0.1') app.whenReady().then(() => { // Your code here }) ``` ## Electron CLI Flags ### --auth-server-whitelist=`url` A comma-separated list of servers for which integrated authentication is enabled. For example: ```sh --auth-server-whitelist='*example.com, *foobar.com, *baz' ``` then any `url` ending with `example.com`, `foobar.com`, `baz` will be considered for integrated authentication. Without `*` prefix the URL has to match exactly. ### --auth-negotiate-delegate-whitelist=`url` A comma-separated list of servers for which delegation of user credentials is required. Without `*` prefix the URL has to match exactly. ### --disable-ntlm-v2 Disables NTLM v2 for posix platforms, no effect elsewhere. ### --disable-http-cache Disables the disk cache for HTTP requests. ### --disable-http2 Disable HTTP/2 and SPDY/3.1 protocols. ### --disable-renderer-backgrounding Prevents Chromium from lowering the priority of invisible pages' renderer processes. This flag is global to all renderer processes, if you only want to disable throttling in one window, you can take the hack of [playing silent audio][play-silent-audio]. ### --disk-cache-size=`size` Forces the maximum disk space to be used by the disk cache, in bytes. ### --enable-logging\[=file] Prints Chromium's logging to stderr (or a log file). The `ELECTRON_ENABLE_LOGGING` environment variable has the same effect as passing `--enable-logging`. Passing `--enable-logging` will result in logs being printed on stderr. Passing `--enable-logging=file` will result in logs being saved to the file specified by `--log-file=...`, or to `electron_debug.log` in the user-data directory if `--log-file` is not specified. > **Note:** On Windows, logs from child processes cannot be sent to stderr. > Logging to a file is the most reliable way to collect logs on Windows. See also `--log-file`, `--log-level`, `--v`, and `--vmodule`. ### --force-fieldtrials=`trials` Field trials to be forcefully enabled or disabled. For example: `WebRTC-Audio-Red-For-Opus/Enabled/` ### --host-rules=`rules` A comma-separated list of `rules` that control how hostnames are mapped. For example: * `MAP * 127.0.0.1` Forces all hostnames to be mapped to 127.0.0.1 * `MAP *.google.com proxy` Forces all google.com subdomains to be resolved to "proxy". * `MAP test.com [::1]:77` Forces "test.com" to resolve to IPv6 loopback. Will also force the port of the resulting socket address to be 77. * `MAP * baz, EXCLUDE www.google.com` Remaps everything to "baz", except for "www.google.com". These mappings apply to the endpoint host in a net request (the TCP connect and host resolver in a direct connection, and the `CONNECT` in an HTTP proxy connection, and the endpoint host in a `SOCKS` proxy connection). ### --host-resolver-rules=`rules` Like `--host-rules` but these `rules` only apply to the host resolver. ### --ignore-certificate-errors Ignores certificate related errors. ### --ignore-connections-limit=`domains` Ignore the connections limit for `domains` list separated by `,`. ### --js-flags=`flags` Specifies the flags passed to the Node.js engine. It has to be passed when starting Electron if you want to enable the `flags` in the main process. ```sh $ electron --js-flags="--harmony_proxies --harmony_collections" your-app ``` See the [Node.js documentation][node-cli] or run `node --help` in your terminal for a list of available flags. Additionally, run `node --v8-options` to see a list of flags that specifically refer to Node.js's V8 JavaScript engine. ### --lang Set a custom locale. ### --log-file=`path` If `--enable-logging` is specified, logs will be written to the given path. The parent directory must exist. Setting the `ELECTRON_LOG_FILE` environment variable is equivalent to passing this flag. If both are present, the command-line switch takes precedence. ### --log-net-log=`path` Enables net log events to be saved and writes them to `path`. ### --log-level=`N` Sets the verbosity of logging when used together with `--enable-logging`. `N` should be one of [Chrome's LogSeverities][severities]. Note that two complimentary logging mechanisms in Chromium -- `LOG()` and `VLOG()` -- are controlled by different switches. `--log-level` controls `LOG()` messages, while `--v` and `--vmodule` control `VLOG()` messages. So you may want to use a combination of these three switches depending on the granularity you want and what logging calls are made by the code you're trying to watch. See [Chromium Logging source][logging] for more information on how `LOG()` and `VLOG()` interact. Loosely speaking, `VLOG()` can be thought of as sub-levels / per-module levels inside `LOG(INFO)` to control the firehose of `LOG(INFO)` data. See also `--enable-logging`, `--log-level`, `--v`, and `--vmodule`. ### --no-proxy-server Don't use a proxy server and always make direct connections. Overrides any other proxy server flags that are passed. ### --no-sandbox Disables the Chromium [sandbox](https://www.chromium.org/developers/design-documents/sandbox). Forces renderer process and Chromium helper processes to run un-sandboxed. Should only be used for testing. ### --proxy-bypass-list=`hosts` Instructs Electron to bypass the proxy server for the given semi-colon-separated list of hosts. This flag has an effect only if used in tandem with `--proxy-server`. For example: ```javascript const { app } = require('electron') app.commandLine.appendSwitch('proxy-bypass-list', '<local>;*.google.com;*foo.com;1.2.3.4:5678') ``` Will use the proxy server for all hosts except for local addresses (`localhost`, `127.0.0.1` etc.), `google.com` subdomains, hosts that contain the suffix `foo.com` and anything at `1.2.3.4:5678`. ### --proxy-pac-url=`url` Uses the PAC script at the specified `url`. ### --proxy-server=`address:port` Use a specified proxy server, which overrides the system setting. This switch only affects requests with HTTP protocol, including HTTPS and WebSocket requests. It is also noteworthy that not all proxy servers support HTTPS and WebSocket requests. The proxy URL does not support username and password authentication [per Chromium issue](https://bugs.chromium.org/p/chromium/issues/detail?id=615947). ### --remote-debugging-port=`port` Enables remote debugging over HTTP on the specified `port`. ### --v=`log_level` Gives the default maximal active V-logging level; 0 is the default. Normally positive values are used for V-logging levels. This switch only works when `--enable-logging` is also passed. See also `--enable-logging`, `--log-level`, and `--vmodule`. ### --vmodule=`pattern` Gives the per-module maximal V-logging levels to override the value given by `--v`. E.g. `my_module=2,foo*=3` would change the logging level for all code in source files `my_module.*` and `foo*.*`. Any pattern containing a forward or backward slash will be tested against the whole pathname and not only the module. E.g. `*/foo/bar/*=2` would change the logging level for all code in the source files under a `foo/bar` directory. This switch only works when `--enable-logging` is also passed. See also `--enable-logging`, `--log-level`, and `--v`. ### --force_high_performance_gpu Force using discrete GPU when there are multiple GPUs available. ### --force_low_power_gpu Force using integrated GPU when there are multiple GPUs available. ## Node.js Flags Electron supports some of the [CLI flags][node-cli] supported by Node.js. **Note:** Passing unsupported command line switches to Electron when it is not running in `ELECTRON_RUN_AS_NODE` will have no effect. ### `--inspect-brk\[=\[host:]port]` Activate inspector on host:port and break at start of user script. Default host:port is 127.0.0.1:9229. Aliased to `--debug-brk=[host:]port`. #### `--inspect-brk-node[=[host:]port]` Activate inspector on `host:port` and break at start of the first internal JavaScript script executed when the inspector is available. Default `host:port` is `127.0.0.1:9229`. ### `--inspect-port=\[host:]port` Set the `host:port` to be used when the inspector is activated. Useful when activating the inspector by sending the SIGUSR1 signal. Default host is `127.0.0.1`. Aliased to `--debug-port=[host:]port`. ### `--inspect\[=\[host:]port]` Activate inspector on `host:port`. Default is `127.0.0.1:9229`. V8 inspector integration allows tools such as Chrome DevTools and IDEs to debug and profile Electron instances. The tools attach to Electron instances via a TCP port and communicate using the [Chrome DevTools Protocol](https://chromedevtools.github.io/devtools-protocol/). See the [Debugging the Main Process][debugging-main-process] guide for more details. Aliased to `--debug[=[host:]port`. ### `--inspect-publish-uid=stderr,http` Specify ways of the inspector web socket url exposure. By default inspector websocket url is available in stderr and under /json/list endpoint on http://host:port/json/list. ### `--no-deprecation` Silence deprecation warnings. ### `--throw-deprecation` Throw errors for deprecations. ### `--trace-deprecation` Print stack traces for deprecations. ### `--trace-warnings` Print stack traces for process warnings (including deprecations). ### `--dns-result-order=order` Set the default value of the `verbatim` parameter in the Node.js [`dns.lookup()`](https://nodejs.org/api/dns.html#dnslookuphostname-options-callback) and [`dnsPromises.lookup()`](https://nodejs.org/api/dns.html#dnspromiseslookuphostname-options) functions. The value could be: * `ipv4first`: sets default `verbatim` `false`. * `verbatim`: sets default `verbatim` `true`. The default is `verbatim` and `dns.setDefaultResultOrder()` have higher priority than `--dns-result-order`. [app]: app.md [append-switch]: command-line.md#commandlineappendswitchswitch-value [debugging-main-process]: ../tutorial/debugging-main-process.md [logging]: https://source.chromium.org/chromium/chromium/src/+/main:base/logging.h [node-cli]: https://nodejs.org/api/cli.html [play-silent-audio]: https://github.com/atom/atom/pull/9485/files [ready]: app.md#event-ready [severities]: https://source.chromium.org/chromium/chromium/src/+/main:base/logging.h?q=logging::LogSeverity&ss=chromium
closed
electron/electron
https://github.com/electron/electron
39,288
[Bug]: js-flags 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 25.3.1 ### What operating system are you using? macOS ### Operating System Version 10.15.7 ### What arch are you using? x64 ### Last Known Working Electron version no test ### Expected Behavior `electron --js-flags="--enable-source-maps" .` makes node supports sourcemap ### Actual Behavior Error: unrecognized flag --enable-source-maps Try --help for options ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/39288
https://github.com/electron/electron/pull/39465
1d20ec5b990085fb38cc0494435cd6f57e0e8b3e
22429e21129bd22c06c23f7d714b96d31063d495
2023-07-30T11:40:10Z
c++
2023-08-15T18:49:21Z
shell/app/node_main.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/app/node_main.h" #include <map> #include <memory> #include <string> #include <utility> #include <vector> #include "base/base_switches.h" #include "base/command_line.h" #include "base/containers/fixed_flat_set.h" #include "base/feature_list.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "base/task/single_thread_task_runner.h" #include "base/task/thread_pool/thread_pool_instance.h" #include "content/public/common/content_switches.h" #include "electron/electron_version.h" #include "gin/array_buffer.h" #include "gin/public/isolate_holder.h" #include "gin/v8_initializer.h" #include "shell/app/uv_task_runner.h" #include "shell/browser/javascript_environment.h" #include "shell/common/api/electron_bindings.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/node_bindings.h" #include "shell/common/node_includes.h" #if BUILDFLAG(IS_WIN) #include "chrome/child/v8_crashpad_support_win.h" #endif #if BUILDFLAG(IS_LINUX) #include "base/environment.h" #include "base/posix/global_descriptors.h" #include "base/strings/string_number_conversions.h" #include "components/crash/core/app/crash_switches.h" // nogncheck #include "content/public/common/content_descriptors.h" #endif #if !IS_MAS_BUILD() #include "components/crash/core/app/crashpad.h" // nogncheck #include "shell/app/electron_crash_reporter_client.h" #include "shell/common/crash_keys.h" #endif namespace { // Initialize Node.js cli options to pass to Node.js // See https://nodejs.org/api/cli.html#cli_options int SetNodeCliFlags() { // Options that are unilaterally disallowed static constexpr auto disallowed = base::MakeFixedFlatSet<base::StringPiece>({ "--enable-fips", "--force-fips", "--openssl-config", "--use-bundled-ca", "--use-openssl-ca", }); const auto argv = base::CommandLine::ForCurrentProcess()->argv(); std::vector<std::string> args; // TODO(codebytere): We need to set the first entry in args to the // process name owing to src/node_options-inl.h#L286-L290 but this is // redundant and so should be refactored upstream. args.reserve(argv.size() + 1); args.emplace_back("electron"); for (const auto& arg : argv) { #if BUILDFLAG(IS_WIN) const auto& option = base::WideToUTF8(arg); #else const auto& option = arg; #endif const auto stripped = base::StringPiece(option).substr(0, option.find('=')); if (disallowed.contains(stripped)) { LOG(ERROR) << "The Node.js cli flag " << stripped << " is not supported in Electron"; // Node.js returns 9 from ProcessGlobalArgs for any errors encountered // when setting up cli flags and env vars. Since we're outlawing these // flags (making them errors) return 9 here for consistency. return 9; } else { args.push_back(option); } } std::vector<std::string> errors; // Node.js itself will output parsing errors to // console so we don't need to handle that ourselves return ProcessGlobalArgs(&args, nullptr, &errors, node::kDisallowedInEnvironment); } #if IS_MAS_BUILD() void SetCrashKeyStub(const std::string& key, const std::string& value) {} void ClearCrashKeyStub(const std::string& key) {} #endif } // namespace namespace electron { v8::Local<v8::Value> GetParameters(v8::Isolate* isolate) { std::map<std::string, std::string> keys; #if !IS_MAS_BUILD() electron::crash_keys::GetCrashKeys(&keys); #endif return gin::ConvertToV8(isolate, keys); } int NodeMain(int argc, char* argv[]) { base::CommandLine::Init(argc, argv); #if BUILDFLAG(IS_WIN) v8_crashpad_support::SetUp(); #endif #if BUILDFLAG(IS_LINUX) auto os_env = base::Environment::Create(); std::string fd_string, pid_string; if (os_env->GetVar("CRASHDUMP_SIGNAL_FD", &fd_string) && os_env->GetVar("CRASHPAD_HANDLER_PID", &pid_string)) { int fd = -1, pid = -1; DCHECK(base::StringToInt(fd_string, &fd)); DCHECK(base::StringToInt(pid_string, &pid)); base::GlobalDescriptors::GetInstance()->Set(kCrashDumpSignal, fd); // Following API is unsafe in multi-threaded scenario, but at this point // we are still single threaded. os_env->UnSetVar("CRASHDUMP_SIGNAL_FD"); os_env->UnSetVar("CRASHPAD_HANDLER_PID"); } #endif int exit_code = 1; { // Feed gin::PerIsolateData with a task runner. uv_loop_t* loop = uv_default_loop(); auto uv_task_runner = base::MakeRefCounted<UvTaskRunner>(loop); base::SingleThreadTaskRunner::CurrentDefaultHandle handle(uv_task_runner); // Initialize feature list. auto feature_list = std::make_unique<base::FeatureList>(); feature_list->InitializeFromCommandLine("", ""); base::FeatureList::SetInstance(std::move(feature_list)); // Explicitly register electron's builtin bindings. NodeBindings::RegisterBuiltinBindings(); // Parse and set Node.js cli flags. int flags_exit_code = SetNodeCliFlags(); if (flags_exit_code != 0) exit(flags_exit_code); // Hack around with the argv pointer. Used for process.title = "blah". argv = uv_setup_args(argc, argv); std::vector<std::string> args(argv, argv + argc); std::unique_ptr<node::InitializationResult> result = node::InitializeOncePerProcess( args, {node::ProcessInitializationFlags::kNoInitializeV8, node::ProcessInitializationFlags::kNoInitializeNodeV8Platform}); for (const std::string& error : result->errors()) fprintf(stderr, "%s: %s\n", args[0].c_str(), error.c_str()); if (result->early_return() != 0) { return result->exit_code(); } #if BUILDFLAG(IS_LINUX) // On Linux, initialize crashpad after Nodejs init phase so that // crash and termination signal handlers can be set by the crashpad client. if (!pid_string.empty()) { auto* command_line = base::CommandLine::ForCurrentProcess(); command_line->AppendSwitchASCII( crash_reporter::switches::kCrashpadHandlerPid, pid_string); ElectronCrashReporterClient::Create(); crash_reporter::InitializeCrashpad(false, "node"); crash_keys::SetCrashKeysFromCommandLine( *base::CommandLine::ForCurrentProcess()); crash_keys::SetPlatformCrashKey(); // Ensure the flags and env variable does not propagate to userland. command_line->RemoveSwitch(crash_reporter::switches::kCrashpadHandlerPid); } #elif BUILDFLAG(IS_WIN) || (BUILDFLAG(IS_MAC) && !IS_MAS_BUILD()) ElectronCrashReporterClient::Create(); crash_reporter::InitializeCrashpad(false, "node"); crash_keys::SetCrashKeysFromCommandLine( *base::CommandLine::ForCurrentProcess()); crash_keys::SetPlatformCrashKey(); #endif gin::V8Initializer::LoadV8Snapshot( gin::V8SnapshotFileType::kWithAdditionalContext); // V8 requires a task scheduler. base::ThreadPoolInstance::CreateAndStartWithDefaultParams("Electron"); // Allow Node.js to track the amount of time the event loop has spent // idle in the kernel’s event provider . uv_loop_configure(loop, UV_METRICS_IDLE_TIME); // Initialize gin::IsolateHolder. bool setup_wasm_streaming = node::per_process::cli_options->get_per_isolate_options() ->get_per_env_options() ->experimental_fetch; JavascriptEnvironment gin_env(loop, setup_wasm_streaming); v8::Isolate* isolate = gin_env.isolate(); v8::Isolate::Scope isolate_scope(isolate); v8::Locker locker(isolate); node::Environment* env = nullptr; node::IsolateData* isolate_data = nullptr; { v8::HandleScope scope(isolate); isolate_data = node::CreateIsolateData(isolate, loop, gin_env.platform()); CHECK_NE(nullptr, isolate_data); uint64_t env_flags = node::EnvironmentFlags::kDefaultFlags | node::EnvironmentFlags::kHideConsoleWindows; env = node::CreateEnvironment( isolate_data, isolate->GetCurrentContext(), result->args(), result->exec_args(), static_cast<node::EnvironmentFlags::Flags>(env_flags)); CHECK_NE(nullptr, env); node::SetIsolateUpForNode(isolate); gin_helper::Dictionary process(isolate, env->process_object()); process.SetMethod("crash", &ElectronBindings::Crash); // Setup process.crashReporter in child node processes gin_helper::Dictionary reporter = gin::Dictionary::CreateEmpty(isolate); reporter.SetMethod("getParameters", &GetParameters); #if IS_MAS_BUILD() reporter.SetMethod("addExtraParameter", &SetCrashKeyStub); reporter.SetMethod("removeExtraParameter", &ClearCrashKeyStub); #else reporter.SetMethod("addExtraParameter", &electron::crash_keys::SetCrashKey); reporter.SetMethod("removeExtraParameter", &electron::crash_keys::ClearCrashKey); #endif process.Set("crashReporter", reporter); gin_helper::Dictionary versions; if (process.Get("versions", &versions)) { versions.SetReadOnly(ELECTRON_PROJECT_NAME, ELECTRON_VERSION_STRING); } } v8::HandleScope scope(isolate); node::LoadEnvironment(env, node::StartExecutionCallback{}); // Potential reasons we get Nothing here may include: the env // is stopping, or the user hooks process.emit('exit'). exit_code = node::SpinEventLoop(env).FromMaybe(1); node::ResetStdio(); node::Stop(env, node::StopFlags::kDoNotTerminateIsolate); node::FreeEnvironment(env); node::FreeIsolateData(isolate_data); } // According to "src/gin/shell/gin_main.cc": // // gin::IsolateHolder waits for tasks running in ThreadPool in its // destructor and thus must be destroyed before ThreadPool starts skipping // CONTINUE_ON_SHUTDOWN tasks. base::ThreadPoolInstance::Get()->Shutdown(); v8::V8::Dispose(); return exit_code; } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
39,288
[Bug]: js-flags 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 25.3.1 ### What operating system are you using? macOS ### Operating System Version 10.15.7 ### What arch are you using? x64 ### Last Known Working Electron version no test ### Expected Behavior `electron --js-flags="--enable-source-maps" .` makes node supports sourcemap ### Actual Behavior Error: unrecognized flag --enable-source-maps Try --help for options ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/39288
https://github.com/electron/electron/pull/39465
1d20ec5b990085fb38cc0494435cd6f57e0e8b3e
22429e21129bd22c06c23f7d714b96d31063d495
2023-07-30T11:40:10Z
c++
2023-08-15T18:49:21Z
shell/common/node_bindings.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/common/node_bindings.h" #include <algorithm> #include <string> #include <utility> #include <vector> #include "base/base_paths.h" #include "base/command_line.h" #include "base/containers/fixed_flat_set.h" #include "base/environment.h" #include "base/path_service.h" #include "base/run_loop.h" #include "base/strings/string_split.h" #include "base/strings/utf_string_conversions.h" #include "base/task/single_thread_task_runner.h" #include "base/trace_event/trace_event.h" #include "content/public/browser/browser_thread.h" #include "content/public/common/content_paths.h" #include "electron/buildflags/buildflags.h" #include "electron/fuses.h" #include "shell/browser/api/electron_api_app.h" #include "shell/common/api/electron_bindings.h" #include "shell/common/electron_command_line.h" #include "shell/common/gin_converters/file_path_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/gin_helper/event.h" #include "shell/common/gin_helper/event_emitter_caller.h" #include "shell/common/gin_helper/locker.h" #include "shell/common/gin_helper/microtasks_scope.h" #include "shell/common/mac/main_application_bundle.h" #include "third_party/blink/renderer/bindings/core/v8/v8_initializer.h" // nogncheck #include "third_party/electron_node/src/debug_utils.h" #if !IS_MAS_BUILD() #include "shell/common/crash_keys.h" #endif #define ELECTRON_BROWSER_BINDINGS(V) \ V(electron_browser_app) \ V(electron_browser_auto_updater) \ V(electron_browser_browser_view) \ V(electron_browser_content_tracing) \ V(electron_browser_crash_reporter) \ V(electron_browser_desktop_capturer) \ V(electron_browser_dialog) \ V(electron_browser_event_emitter) \ V(electron_browser_global_shortcut) \ V(electron_browser_in_app_purchase) \ V(electron_browser_menu) \ V(electron_browser_message_port) \ V(electron_browser_native_theme) \ V(electron_browser_net) \ V(electron_browser_notification) \ V(electron_browser_power_monitor) \ V(electron_browser_power_save_blocker) \ V(electron_browser_protocol) \ V(electron_browser_printing) \ V(electron_browser_push_notifications) \ V(electron_browser_safe_storage) \ V(electron_browser_session) \ V(electron_browser_screen) \ V(electron_browser_system_preferences) \ V(electron_browser_base_window) \ V(electron_browser_tray) \ V(electron_browser_utility_process) \ V(electron_browser_view) \ V(electron_browser_web_contents) \ V(electron_browser_web_contents_view) \ V(electron_browser_web_frame_main) \ V(electron_browser_web_view_manager) \ V(electron_browser_window) #define ELECTRON_COMMON_BINDINGS(V) \ V(electron_common_asar) \ V(electron_common_clipboard) \ V(electron_common_command_line) \ V(electron_common_crashpad_support) \ V(electron_common_environment) \ V(electron_common_features) \ V(electron_common_native_image) \ V(electron_common_shell) \ V(electron_common_v8_util) #define ELECTRON_RENDERER_BINDINGS(V) \ V(electron_renderer_context_bridge) \ V(electron_renderer_crash_reporter) \ V(electron_renderer_ipc) \ V(electron_renderer_web_frame) #define ELECTRON_UTILITY_BINDINGS(V) V(electron_utility_parent_port) #define ELECTRON_VIEWS_BINDINGS(V) V(electron_browser_image_view) #define ELECTRON_TESTING_BINDINGS(V) V(electron_common_testing) // This is used to load built-in bindings. Instead of using // __attribute__((constructor)), we call the _register_<modname> // function for each built-in bindings explicitly. This is only // forward declaration. The definitions are in each binding's // implementation when calling the NODE_LINKED_BINDING_CONTEXT_AWARE. #define V(modname) void _register_##modname(); ELECTRON_BROWSER_BINDINGS(V) ELECTRON_COMMON_BINDINGS(V) ELECTRON_RENDERER_BINDINGS(V) ELECTRON_UTILITY_BINDINGS(V) #if BUILDFLAG(ENABLE_VIEWS_API) ELECTRON_VIEWS_BINDINGS(V) #endif #if DCHECK_IS_ON() ELECTRON_TESTING_BINDINGS(V) #endif #undef V namespace { void stop_and_close_uv_loop(uv_loop_t* loop) { uv_stop(loop); auto const ensure_closing = [](uv_handle_t* handle, void*) { // We should be using the UvHandle wrapper everywhere, in which case // all handles should already be in a closing state... DCHECK(uv_is_closing(handle)); // ...but if a raw handle got through, through, do the right thing anyway if (!uv_is_closing(handle)) { uv_close(handle, nullptr); } }; uv_walk(loop, ensure_closing, nullptr); // All remaining handles are in a closing state now. // Pump the event loop so that they can finish closing. for (;;) if (uv_run(loop, UV_RUN_DEFAULT) == 0) break; DCHECK_EQ(0, uv_loop_alive(loop)); node::CheckedUvLoopClose(loop); } bool g_is_initialized = false; void V8FatalErrorCallback(const char* location, const char* message) { LOG(ERROR) << "Fatal error in V8: " << location << " " << message; #if !IS_MAS_BUILD() electron::crash_keys::SetCrashKey("electron.v8-fatal.message", message); electron::crash_keys::SetCrashKey("electron.v8-fatal.location", location); #endif volatile int* zero = nullptr; *zero = 0; } bool AllowWasmCodeGenerationCallback(v8::Local<v8::Context> context, v8::Local<v8::String> source) { // If we're running with contextIsolation enabled in the renderer process, // fall back to Blink's logic. if (node::Environment::GetCurrent(context) == nullptr) { if (!electron::IsRendererProcess()) return false; return blink::V8Initializer::WasmCodeGenerationCheckCallbackInMainThread( context, source); } return node::AllowWasmCodeGenerationCallback(context, source); } v8::ModifyCodeGenerationFromStringsResult ModifyCodeGenerationFromStrings( v8::Local<v8::Context> context, v8::Local<v8::Value> source, bool is_code_like) { if (node::Environment::GetCurrent(context) == nullptr) { // No node environment means we're in the renderer process, either in a // sandboxed renderer or in an unsandboxed renderer with context isolation // enabled. if (!electron::IsRendererProcess()) { NOTREACHED(); return {false, {}}; } return blink::V8Initializer::CodeGenerationCheckCallbackInMainThread( context, source, is_code_like); } // If we get here then we have a node environment, so either a) we're in the // non-rendrer process, or b) we're in the renderer process in a context that // has both node and blink, i.e. contextIsolation disabled. // If we're in the renderer with contextIsolation disabled, ask blink first // (for CSP), and iff that allows codegen, delegate to node. if (electron::IsRendererProcess()) { v8::ModifyCodeGenerationFromStringsResult result = blink::V8Initializer::CodeGenerationCheckCallbackInMainThread( context, source, is_code_like); if (!result.codegen_allowed) return result; } // If we're in the main process or utility process, delegate to node. return node::ModifyCodeGenerationFromStrings(context, source, is_code_like); } void ErrorMessageListener(v8::Local<v8::Message> message, v8::Local<v8::Value> data) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); node::Environment* env = node::Environment::GetCurrent(isolate); if (env) { gin_helper::MicrotasksScope microtasks_scope( isolate, env->context()->GetMicrotaskQueue(), v8::MicrotasksScope::kDoNotRunMicrotasks); // Emit the after() hooks now that the exception has been handled. // Analogous to node/lib/internal/process/execution.js#L176-L180 if (env->async_hooks()->fields()[node::AsyncHooks::kAfter]) { while (env->async_hooks()->fields()[node::AsyncHooks::kStackLength]) { node::AsyncWrap::EmitAfter(env, env->execution_async_id()); env->async_hooks()->pop_async_context(env->execution_async_id()); } } // Ensure that the async id stack is properly cleared so the async // hook stack does not become corrupted. env->async_hooks()->clear_async_id_stack(); } } // Only allow a specific subset of options in non-ELECTRON_RUN_AS_NODE mode. // If node CLI inspect support is disabled, allow no debug options. bool IsAllowedOption(base::StringPiece option) { static constexpr auto debug_options = base::MakeFixedFlatSet<base::StringPiece>({ "--debug", "--debug-brk", "--debug-port", "--inspect", "--inspect-brk", "--inspect-brk-node", "--inspect-port", "--inspect-publish-uid", }); // This should be aligned with what's possible to set via the process object. static constexpr auto options = base::MakeFixedFlatSet<base::StringPiece>({ "--trace-warnings", "--trace-deprecation", "--throw-deprecation", "--no-deprecation", "--dns-result-order", }); if (debug_options.contains(option)) return electron::fuses::IsNodeCliInspectEnabled(); return options.contains(option); } // Initialize NODE_OPTIONS to pass to Node.js // See https://nodejs.org/api/cli.html#cli_node_options_options void SetNodeOptions(base::Environment* env) { // Options that are unilaterally disallowed static constexpr auto disallowed = base::MakeFixedFlatSet<base::StringPiece>( {"--enable-fips", "--force-fips", "--openssl-config", "--use-bundled-ca", "--use-openssl-ca", "--experimental-policy"}); static constexpr auto pkg_opts = base::MakeFixedFlatSet<base::StringPiece>({ "--http-parser", "--max-http-header-size", }); if (env->HasVar("NODE_OPTIONS")) { if (electron::fuses::IsNodeOptionsEnabled()) { std::string options; env->GetVar("NODE_OPTIONS", &options); std::vector<std::string> parts = base::SplitString( options, " ", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY); bool is_packaged_app = electron::api::App::IsPackaged(); for (const auto& part : parts) { // Strip off values passed to individual NODE_OPTIONs std::string option = part.substr(0, part.find('=')); if (is_packaged_app && !pkg_opts.contains(option)) { // Explicitly disallow majority of NODE_OPTIONS in packaged apps LOG(ERROR) << "Most NODE_OPTIONs are not supported in packaged apps." << " See documentation for more details."; options.erase(options.find(option), part.length()); } else if (disallowed.contains(option)) { // Remove NODE_OPTIONS specifically disallowed for use in Node.js // through Electron owing to constraints like BoringSSL. LOG(ERROR) << "The NODE_OPTION " << option << " is not supported in Electron"; options.erase(options.find(option), part.length()); } } // overwrite new NODE_OPTIONS without unsupported variables env->SetVar("NODE_OPTIONS", options); } else { LOG(ERROR) << "NODE_OPTIONS have been disabled in this app"; env->SetVar("NODE_OPTIONS", ""); } } } } // namespace namespace electron { namespace { base::FilePath GetResourcesPath() { #if BUILDFLAG(IS_MAC) return MainApplicationBundlePath().Append("Contents").Append("Resources"); #else auto* command_line = base::CommandLine::ForCurrentProcess(); base::FilePath exec_path(command_line->GetProgram()); base::PathService::Get(base::FILE_EXE, &exec_path); return exec_path.DirName().Append(FILE_PATH_LITERAL("resources")); #endif } } // namespace NodeBindings::NodeBindings(BrowserEnvironment browser_env) : browser_env_(browser_env) { if (browser_env == BrowserEnvironment::kWorker) { uv_loop_init(&worker_loop_); uv_loop_ = &worker_loop_; } else { uv_loop_ = uv_default_loop(); } // Interrupt embed polling when a handle is started. uv_loop_configure(uv_loop_, UV_LOOP_INTERRUPT_ON_IO_CHANGE); } NodeBindings::~NodeBindings() { // Quit the embed thread. embed_closed_ = true; uv_sem_post(&embed_sem_); WakeupEmbedThread(); // Wait for everything to be done. uv_thread_join(&embed_thread_); // Clear uv. uv_sem_destroy(&embed_sem_); dummy_uv_handle_.reset(); // Clean up worker loop if (in_worker_loop()) stop_and_close_uv_loop(uv_loop_); } void NodeBindings::RegisterBuiltinBindings() { #define V(modname) _register_##modname(); if (IsBrowserProcess()) { ELECTRON_BROWSER_BINDINGS(V) #if BUILDFLAG(ENABLE_VIEWS_API) ELECTRON_VIEWS_BINDINGS(V) #endif } ELECTRON_COMMON_BINDINGS(V) if (IsRendererProcess()) { ELECTRON_RENDERER_BINDINGS(V) } if (IsUtilityProcess()) { ELECTRON_UTILITY_BINDINGS(V) } #if DCHECK_IS_ON() ELECTRON_TESTING_BINDINGS(V) #endif #undef V } bool NodeBindings::IsInitialized() { return g_is_initialized; } // Initialize Node.js cli options to pass to Node.js // See https://nodejs.org/api/cli.html#cli_options void NodeBindings::SetNodeCliFlags() { const auto argv = base::CommandLine::ForCurrentProcess()->argv(); std::vector<std::string> args; // TODO(codebytere): We need to set the first entry in args to the // process name owing to src/node_options-inl.h#L286-L290 but this is // redundant and so should be refactored upstream. args.reserve(argv.size() + 1); args.emplace_back("electron"); for (const auto& arg : argv) { #if BUILDFLAG(IS_WIN) const auto& option = base::WideToUTF8(arg); #else const auto& option = arg; #endif const auto stripped = base::StringPiece(option).substr(0, option.find('=')); // Only allow in no-op (--) option or a small set of debug // and trace related options. if (IsAllowedOption(stripped) || stripped == "--") args.push_back(option); } // We need to disable Node.js' fetch implementation to prevent // conflict with Blink's in renderer and worker processes. if (browser_env_ == BrowserEnvironment::kRenderer || browser_env_ == BrowserEnvironment::kWorker) { args.push_back("--no-experimental-fetch"); } std::vector<std::string> errors; const int exit_code = ProcessGlobalArgs(&args, nullptr, &errors, node::kDisallowedInEnvironment); const std::string err_str = "Error parsing Node.js cli flags "; if (exit_code != 0) { LOG(ERROR) << err_str; } else if (!errors.empty()) { LOG(ERROR) << err_str << base::JoinString(errors, " "); } } void NodeBindings::Initialize(v8::Local<v8::Context> context) { TRACE_EVENT0("electron", "NodeBindings::Initialize"); // Open node's error reporting system for browser process. #if BUILDFLAG(IS_LINUX) // Get real command line in renderer process forked by zygote. if (browser_env_ != BrowserEnvironment::kBrowser) ElectronCommandLine::InitializeFromCommandLine(); #endif // Explicitly register electron's builtin bindings. RegisterBuiltinBindings(); // Parse and set Node.js cli flags. SetNodeCliFlags(); auto env = base::Environment::Create(); SetNodeOptions(env.get()); std::vector<std::string> argv = {"electron"}; std::vector<std::string> exec_argv; std::vector<std::string> errors; uint64_t process_flags = node::ProcessFlags::kNoFlags; // We do not want the child processes spawned from the utility process // to inherit the custom stdio handles created for the parent. if (browser_env_ != BrowserEnvironment::kUtility) process_flags |= node::ProcessFlags::kEnableStdioInheritance; if (!fuses::IsNodeOptionsEnabled()) process_flags |= node::ProcessFlags::kDisableNodeOptionsEnv; int exit_code = node::InitializeNodeWithArgs( &argv, &exec_argv, &errors, static_cast<node::ProcessFlags::Flags>(process_flags)); for (const std::string& error : errors) fprintf(stderr, "%s: %s\n", argv[0].c_str(), error.c_str()); if (exit_code != 0) exit(exit_code); #if BUILDFLAG(IS_WIN) // uv_init overrides error mode to suppress the default crash dialog, bring // it back if user wants to show it. if (browser_env_ == BrowserEnvironment::kBrowser || env->HasVar("ELECTRON_DEFAULT_ERROR_MODE")) SetErrorMode(GetErrorMode() & ~SEM_NOGPFAULTERRORBOX); #endif gin_helper::internal::Event::GetConstructor(context); g_is_initialized = true; } node::Environment* NodeBindings::CreateEnvironment( v8::Handle<v8::Context> context, node::MultiIsolatePlatform* platform, std::vector<std::string> args, std::vector<std::string> exec_args) { // Feed node the path to initialization script. std::string process_type; switch (browser_env_) { case BrowserEnvironment::kBrowser: process_type = "browser"; break; case BrowserEnvironment::kRenderer: process_type = "renderer"; break; case BrowserEnvironment::kWorker: process_type = "worker"; break; case BrowserEnvironment::kUtility: process_type = "utility"; break; } v8::Isolate* isolate = context->GetIsolate(); gin_helper::Dictionary global(isolate, context->Global()); if (browser_env_ == BrowserEnvironment::kBrowser) { const std::vector<std::string> search_paths = {"app.asar", "app", "default_app.asar"}; const std::vector<std::string> app_asar_search_paths = {"app.asar"}; context->Global()->SetPrivate( context, v8::Private::ForApi( isolate, gin::ConvertToV8(isolate, "appSearchPaths").As<v8::String>()), gin::ConvertToV8(isolate, electron::fuses::IsOnlyLoadAppFromAsarEnabled() ? app_asar_search_paths : search_paths)); } base::FilePath resources_path = GetResourcesPath(); std::string init_script = "electron/js2c/" + process_type + "_init"; args.insert(args.begin() + 1, init_script); auto* isolate_data = node::CreateIsolateData(isolate, uv_loop_, platform); context->SetAlignedPointerInEmbedderData(kElectronContextEmbedderDataIndex, static_cast<void*>(isolate_data)); node::Environment* env; uint64_t flags = node::EnvironmentFlags::kDefaultFlags | node::EnvironmentFlags::kHideConsoleWindows | node::EnvironmentFlags::kNoGlobalSearchPaths; if (browser_env_ == BrowserEnvironment::kRenderer || browser_env_ == BrowserEnvironment::kWorker) { // Only one ESM loader can be registered per isolate - // in renderer processes this should be blink. We need to tell Node.js // not to register its handler (overriding blinks) in non-browser processes. // We also avoid overriding globals like setImmediate, clearImmediate // queueMicrotask etc during the bootstrap phase of Node.js // for processes that already have these defined by DOM. // Check //third_party/electron_node/lib/internal/bootstrap/node.js // for the list of overrides on globalThis. flags |= node::EnvironmentFlags::kNoRegisterESMLoader | node::EnvironmentFlags::kNoBrowserGlobals | node::EnvironmentFlags::kNoCreateInspector; } if (!electron::fuses::IsNodeCliInspectEnabled()) { // If --inspect and friends are disabled we also shouldn't listen for // SIGUSR1 flags |= node::EnvironmentFlags::kNoStartDebugSignalHandler; } { v8::TryCatch try_catch(isolate); env = node::CreateEnvironment( static_cast<node::IsolateData*>(isolate_data), context, args, exec_args, static_cast<node::EnvironmentFlags::Flags>(flags)); if (try_catch.HasCaught()) { std::string err_msg = "Failed to initialize node environment in process: " + process_type; v8::Local<v8::Message> message = try_catch.Message(); std::string msg; if (!message.IsEmpty() && gin::ConvertFromV8(isolate, message->Get(), &msg)) err_msg += " , with error: " + msg; LOG(ERROR) << err_msg; } } DCHECK(env); node::IsolateSettings is; // Use a custom fatal error callback to allow us to add // crash message and location to CrashReports. is.fatal_error_callback = V8FatalErrorCallback; // We don't want to abort either in the renderer or browser processes. // We already listen for uncaught exceptions and handle them there. // For utility process we expect the process to behave as standard // Node.js runtime and abort the process with appropriate exit // code depending on a handler being set for `uncaughtException` event. if (browser_env_ != BrowserEnvironment::kUtility) { is.should_abort_on_uncaught_exception_callback = [](v8::Isolate*) { return false; }; } // Use a custom callback here to allow us to leverage Blink's logic in the // renderer process. is.allow_wasm_code_generation_callback = AllowWasmCodeGenerationCallback; is.flags |= node::IsolateSettingsFlags:: ALLOW_MODIFY_CODE_GENERATION_FROM_STRINGS_CALLBACK; is.modify_code_generation_from_strings_callback = ModifyCodeGenerationFromStrings; if (browser_env_ == BrowserEnvironment::kBrowser || browser_env_ == BrowserEnvironment::kUtility) { // Node.js requires that microtask checkpoints be explicitly invoked. is.policy = v8::MicrotasksPolicy::kExplicit; } else { // Blink expects the microtasks policy to be kScoped, but Node.js expects it // to be kExplicit. In the renderer, there can be many contexts within the // same isolate, so we don't want to change the existing policy here, which // could be either kExplicit or kScoped depending on whether we're executing // from within a Node.js or a Blink entrypoint. Instead, the policy is // toggled to kExplicit when entering Node.js through UvRunOnce. is.policy = context->GetIsolate()->GetMicrotasksPolicy(); // We do not want to use Node.js' message listener as it interferes with // Blink's. is.flags &= ~node::IsolateSettingsFlags::MESSAGE_LISTENER_WITH_ERROR_LEVEL; // Isolate message listeners are additive (you can add multiple), so instead // we add an extra one here to ensure that the async hook stack is properly // cleared when errors are thrown. context->GetIsolate()->AddMessageListenerWithErrorLevel( ErrorMessageListener, v8::Isolate::kMessageError); // We do not want to use the promise rejection callback that Node.js uses, // because it does not send PromiseRejectionEvents to the global script // context. We need to use the one Blink already provides. is.flags |= node::IsolateSettingsFlags::SHOULD_NOT_SET_PROMISE_REJECTION_CALLBACK; // We do not want to use the stack trace callback that Node.js uses, // because it relies on Node.js being aware of the current Context and // that's not always the case. We need to use the one Blink already // provides. is.flags |= node::IsolateSettingsFlags::SHOULD_NOT_SET_PREPARE_STACK_TRACE_CALLBACK; } node::SetIsolateUpForNode(context->GetIsolate(), is); gin_helper::Dictionary process(context->GetIsolate(), env->process_object()); process.SetReadOnly("type", process_type); process.Set("resourcesPath", resources_path); // The path to helper app. base::FilePath helper_exec_path; base::PathService::Get(content::CHILD_PROCESS_EXE, &helper_exec_path); process.Set("helperExecPath", helper_exec_path); return env; } node::Environment* NodeBindings::CreateEnvironment( v8::Handle<v8::Context> context, node::MultiIsolatePlatform* platform) { #if BUILDFLAG(IS_WIN) auto& electron_args = ElectronCommandLine::argv(); std::vector<std::string> args(electron_args.size()); std::transform(electron_args.cbegin(), electron_args.cend(), args.begin(), [](auto& a) { return base::WideToUTF8(a); }); #else auto args = ElectronCommandLine::argv(); #endif return CreateEnvironment(context, platform, args, {}); } void NodeBindings::LoadEnvironment(node::Environment* env) { node::LoadEnvironment(env, node::StartExecutionCallback{}); gin_helper::EmitEvent(env->isolate(), env->process_object(), "loaded"); } void NodeBindings::PrepareEmbedThread() { // IOCP does not change for the process until the loop is recreated, // we ensure that there is only a single polling thread satisfying // the concurrency limit set from CreateIoCompletionPort call by // uv_loop_init for the lifetime of this process. // More background can be found at: // https://github.com/microsoft/vscode/issues/142786#issuecomment-1061673400 if (initialized_) return; // Add dummy handle for libuv, otherwise libuv would quit when there is // nothing to do. uv_async_init(uv_loop_, dummy_uv_handle_.get(), nullptr); // Start worker that will interrupt main loop when having uv events. uv_sem_init(&embed_sem_, 0); uv_thread_create(&embed_thread_, EmbedThreadRunner, this); } void NodeBindings::StartPolling() { // Avoid calling UvRunOnce if the loop is already active, // otherwise it can lead to situations were the number of active // threads processing on IOCP is greater than the concurrency limit. if (initialized_) return; initialized_ = true; // The MessageLoop should have been created, remember the one in main thread. task_runner_ = base::SingleThreadTaskRunner::GetCurrentDefault(); // Run uv loop for once to give the uv__io_poll a chance to add all events. UvRunOnce(); } void NodeBindings::UvRunOnce() { node::Environment* env = uv_env(); // When doing navigation without restarting renderer process, it may happen // that the node environment is destroyed but the message loop is still there. // In this case we should not run uv loop. if (!env) return; v8::HandleScope handle_scope(env->isolate()); // Enter node context while dealing with uv events. v8::Context::Scope context_scope(env->context()); // Node.js expects `kExplicit` microtasks policy and will run microtasks // checkpoints after every call into JavaScript. Since we use a different // policy in the renderer - switch to `kExplicit` and then drop back to the // previous policy value. v8::MicrotaskQueue* microtask_queue = env->context()->GetMicrotaskQueue(); auto old_policy = microtask_queue->microtasks_policy(); DCHECK_EQ(microtask_queue->GetMicrotasksScopeDepth(), 0); microtask_queue->set_microtasks_policy(v8::MicrotasksPolicy::kExplicit); if (browser_env_ != BrowserEnvironment::kBrowser) TRACE_EVENT_BEGIN0("devtools.timeline", "FunctionCall"); // Deal with uv events. int r = uv_run(uv_loop_, UV_RUN_NOWAIT); if (browser_env_ != BrowserEnvironment::kBrowser) TRACE_EVENT_END0("devtools.timeline", "FunctionCall"); microtask_queue->set_microtasks_policy(old_policy); if (r == 0) base::RunLoop().QuitWhenIdle(); // Quit from uv. // Tell the worker thread to continue polling. uv_sem_post(&embed_sem_); } void NodeBindings::WakeupMainThread() { DCHECK(task_runner_); task_runner_->PostTask(FROM_HERE, base::BindOnce(&NodeBindings::UvRunOnce, weak_factory_.GetWeakPtr())); } void NodeBindings::WakeupEmbedThread() { uv_async_send(dummy_uv_handle_.get()); } // static void NodeBindings::EmbedThreadRunner(void* arg) { auto* self = static_cast<NodeBindings*>(arg); while (true) { // Wait for the main loop to deal with events. uv_sem_wait(&self->embed_sem_); if (self->embed_closed_) break; // Wait for something to happen in uv loop. // Note that the PollEvents() is implemented by derived classes, so when // this class is being destructed the PollEvents() would not be available // anymore. Because of it we must make sure we only invoke PollEvents() // when this class is alive. self->PollEvents(); if (self->embed_closed_) break; // Deal with event in main thread. self->WakeupMainThread(); } } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
39,288
[Bug]: js-flags 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 25.3.1 ### What operating system are you using? macOS ### Operating System Version 10.15.7 ### What arch are you using? x64 ### Last Known Working Electron version no test ### Expected Behavior `electron --js-flags="--enable-source-maps" .` makes node supports sourcemap ### Actual Behavior Error: unrecognized flag --enable-source-maps Try --help for options ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/39288
https://github.com/electron/electron/pull/39465
1d20ec5b990085fb38cc0494435cd6f57e0e8b3e
22429e21129bd22c06c23f7d714b96d31063d495
2023-07-30T11:40:10Z
c++
2023-08-15T18:49:21Z
shell/common/node_bindings.h
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #ifndef ELECTRON_SHELL_COMMON_NODE_BINDINGS_H_ #define ELECTRON_SHELL_COMMON_NODE_BINDINGS_H_ #include <string> #include <type_traits> #include <vector> #include "base/files/file_path.h" #include "base/memory/raw_ptr.h" #include "base/memory/raw_ptr_exclusion.h" #include "base/memory/weak_ptr.h" #include "gin/public/context_holder.h" #include "gin/public/gin_embedders.h" #include "shell/common/node_includes.h" #include "uv.h" // NOLINT(build/include_directory) #include "v8/include/v8.h" namespace base { class SingleThreadTaskRunner; } namespace electron { // Choose a reasonable unique index that's higher than any Blink uses // and thus unlikely to collide with an existing index. static constexpr int kElectronContextEmbedderDataIndex = static_cast<int>(gin::kPerContextDataStartIndex) + static_cast<int>(gin::kEmbedderElectron); // A helper class to manage uv_handle_t types, e.g. uv_async_t. // // As per the uv docs: "uv_close() MUST be called on each handle before // memory is released. Moreover, the memory can only be released in // close_cb or after it has returned." This class encapsulates the work // needed to follow those requirements. template <typename T, typename std::enable_if< // these are the C-style 'subclasses' of uv_handle_t std::is_same<T, uv_async_t>::value || std::is_same<T, uv_check_t>::value || std::is_same<T, uv_fs_event_t>::value || std::is_same<T, uv_fs_poll_t>::value || std::is_same<T, uv_idle_t>::value || std::is_same<T, uv_pipe_t>::value || std::is_same<T, uv_poll_t>::value || std::is_same<T, uv_prepare_t>::value || std::is_same<T, uv_process_t>::value || std::is_same<T, uv_signal_t>::value || std::is_same<T, uv_stream_t>::value || std::is_same<T, uv_tcp_t>::value || std::is_same<T, uv_timer_t>::value || std::is_same<T, uv_tty_t>::value || std::is_same<T, uv_udp_t>::value>::type* = nullptr> class UvHandle { public: UvHandle() : t_(new T) {} ~UvHandle() { reset(); } T* get() { return t_; } uv_handle_t* handle() { return reinterpret_cast<uv_handle_t*>(t_); } void reset() { auto* h = handle(); if (h != nullptr) { DCHECK_EQ(0, uv_is_closing(h)); uv_close(h, OnClosed); t_ = nullptr; } } private: static void OnClosed(uv_handle_t* handle) { delete reinterpret_cast<T*>(handle); } RAW_PTR_EXCLUSION T* t_ = {}; }; class NodeBindings { public: enum class BrowserEnvironment { kBrowser, kRenderer, kUtility, kWorker }; static NodeBindings* Create(BrowserEnvironment browser_env); static void RegisterBuiltinBindings(); static bool IsInitialized(); virtual ~NodeBindings(); // Setup V8, libuv. void Initialize(v8::Local<v8::Context> context); void SetNodeCliFlags(); // Create the environment and load node.js. node::Environment* CreateEnvironment(v8::Handle<v8::Context> context, node::MultiIsolatePlatform* platform, std::vector<std::string> args, std::vector<std::string> exec_args); node::Environment* CreateEnvironment(v8::Handle<v8::Context> context, node::MultiIsolatePlatform* platform); // Load node.js in the environment. void LoadEnvironment(node::Environment* env); // Prepare embed thread for message loop integration. void PrepareEmbedThread(); // Notify embed thread to start polling after environment is loaded. void StartPolling(); // Clears the PerIsolateData. void clear_isolate_data(v8::Local<v8::Context> context) { context->SetAlignedPointerInEmbedderData(kElectronContextEmbedderDataIndex, nullptr); } node::IsolateData* isolate_data(v8::Local<v8::Context> context) const { if (context->GetNumberOfEmbedderDataFields() <= kElectronContextEmbedderDataIndex) { return nullptr; } auto* isolate_data = static_cast<node::IsolateData*>( context->GetAlignedPointerFromEmbedderData( kElectronContextEmbedderDataIndex)); CHECK(isolate_data); CHECK(isolate_data->event_loop()); return isolate_data; } // Gets/sets the environment to wrap uv loop. void set_uv_env(node::Environment* env) { uv_env_ = env; } node::Environment* uv_env() const { return uv_env_; } uv_loop_t* uv_loop() const { return uv_loop_; } bool in_worker_loop() const { return uv_loop_ == &worker_loop_; } // disable copy NodeBindings(const NodeBindings&) = delete; NodeBindings& operator=(const NodeBindings&) = delete; protected: explicit NodeBindings(BrowserEnvironment browser_env); // Called to poll events in new thread. virtual void PollEvents() = 0; // Run the libuv loop for once. void UvRunOnce(); // Make the main thread run libuv loop. void WakeupMainThread(); // Interrupt the PollEvents. void WakeupEmbedThread(); // Which environment we are running. const BrowserEnvironment browser_env_; // Current thread's MessageLoop. scoped_refptr<base::SingleThreadTaskRunner> task_runner_; // Current thread's libuv loop. raw_ptr<uv_loop_t> uv_loop_; private: // Thread to poll uv events. static void EmbedThreadRunner(void* arg); // Indicates whether polling thread has been created. bool initialized_ = false; // Whether the libuv loop has ended. bool embed_closed_ = false; // Loop used when constructed in WORKER mode uv_loop_t worker_loop_; // Dummy handle to make uv's loop not quit. UvHandle<uv_async_t> dummy_uv_handle_; // Thread for polling events. uv_thread_t embed_thread_; // Semaphore to wait for main loop in the embed thread. uv_sem_t embed_sem_; // Environment that to wrap the uv loop. raw_ptr<node::Environment> uv_env_ = nullptr; // Isolate data used in creating the environment raw_ptr<node::IsolateData> isolate_data_ = nullptr; base::WeakPtrFactory<NodeBindings> weak_factory_{this}; }; } // namespace electron #endif // ELECTRON_SHELL_COMMON_NODE_BINDINGS_H_
closed
electron/electron
https://github.com/electron/electron
39,288
[Bug]: js-flags 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 25.3.1 ### What operating system are you using? macOS ### Operating System Version 10.15.7 ### What arch are you using? x64 ### Last Known Working Electron version no test ### Expected Behavior `electron --js-flags="--enable-source-maps" .` makes node supports sourcemap ### Actual Behavior Error: unrecognized flag --enable-source-maps Try --help for options ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/39288
https://github.com/electron/electron/pull/39465
1d20ec5b990085fb38cc0494435cd6f57e0e8b3e
22429e21129bd22c06c23f7d714b96d31063d495
2023-07-30T11:40:10Z
c++
2023-08-15T18:49:21Z
docs/api/command-line-switches.md
# Supported Command Line Switches > Command line switches supported by Electron. You can use [app.commandLine.appendSwitch][append-switch] to append them in your app's main script before the [ready][ready] event of the [app][app] module is emitted: ```javascript const { app } = require('electron') app.commandLine.appendSwitch('remote-debugging-port', '8315') app.commandLine.appendSwitch('host-rules', 'MAP * 127.0.0.1') app.whenReady().then(() => { // Your code here }) ``` ## Electron CLI Flags ### --auth-server-whitelist=`url` A comma-separated list of servers for which integrated authentication is enabled. For example: ```sh --auth-server-whitelist='*example.com, *foobar.com, *baz' ``` then any `url` ending with `example.com`, `foobar.com`, `baz` will be considered for integrated authentication. Without `*` prefix the URL has to match exactly. ### --auth-negotiate-delegate-whitelist=`url` A comma-separated list of servers for which delegation of user credentials is required. Without `*` prefix the URL has to match exactly. ### --disable-ntlm-v2 Disables NTLM v2 for posix platforms, no effect elsewhere. ### --disable-http-cache Disables the disk cache for HTTP requests. ### --disable-http2 Disable HTTP/2 and SPDY/3.1 protocols. ### --disable-renderer-backgrounding Prevents Chromium from lowering the priority of invisible pages' renderer processes. This flag is global to all renderer processes, if you only want to disable throttling in one window, you can take the hack of [playing silent audio][play-silent-audio]. ### --disk-cache-size=`size` Forces the maximum disk space to be used by the disk cache, in bytes. ### --enable-logging\[=file] Prints Chromium's logging to stderr (or a log file). The `ELECTRON_ENABLE_LOGGING` environment variable has the same effect as passing `--enable-logging`. Passing `--enable-logging` will result in logs being printed on stderr. Passing `--enable-logging=file` will result in logs being saved to the file specified by `--log-file=...`, or to `electron_debug.log` in the user-data directory if `--log-file` is not specified. > **Note:** On Windows, logs from child processes cannot be sent to stderr. > Logging to a file is the most reliable way to collect logs on Windows. See also `--log-file`, `--log-level`, `--v`, and `--vmodule`. ### --force-fieldtrials=`trials` Field trials to be forcefully enabled or disabled. For example: `WebRTC-Audio-Red-For-Opus/Enabled/` ### --host-rules=`rules` A comma-separated list of `rules` that control how hostnames are mapped. For example: * `MAP * 127.0.0.1` Forces all hostnames to be mapped to 127.0.0.1 * `MAP *.google.com proxy` Forces all google.com subdomains to be resolved to "proxy". * `MAP test.com [::1]:77` Forces "test.com" to resolve to IPv6 loopback. Will also force the port of the resulting socket address to be 77. * `MAP * baz, EXCLUDE www.google.com` Remaps everything to "baz", except for "www.google.com". These mappings apply to the endpoint host in a net request (the TCP connect and host resolver in a direct connection, and the `CONNECT` in an HTTP proxy connection, and the endpoint host in a `SOCKS` proxy connection). ### --host-resolver-rules=`rules` Like `--host-rules` but these `rules` only apply to the host resolver. ### --ignore-certificate-errors Ignores certificate related errors. ### --ignore-connections-limit=`domains` Ignore the connections limit for `domains` list separated by `,`. ### --js-flags=`flags` Specifies the flags passed to the Node.js engine. It has to be passed when starting Electron if you want to enable the `flags` in the main process. ```sh $ electron --js-flags="--harmony_proxies --harmony_collections" your-app ``` See the [Node.js documentation][node-cli] or run `node --help` in your terminal for a list of available flags. Additionally, run `node --v8-options` to see a list of flags that specifically refer to Node.js's V8 JavaScript engine. ### --lang Set a custom locale. ### --log-file=`path` If `--enable-logging` is specified, logs will be written to the given path. The parent directory must exist. Setting the `ELECTRON_LOG_FILE` environment variable is equivalent to passing this flag. If both are present, the command-line switch takes precedence. ### --log-net-log=`path` Enables net log events to be saved and writes them to `path`. ### --log-level=`N` Sets the verbosity of logging when used together with `--enable-logging`. `N` should be one of [Chrome's LogSeverities][severities]. Note that two complimentary logging mechanisms in Chromium -- `LOG()` and `VLOG()` -- are controlled by different switches. `--log-level` controls `LOG()` messages, while `--v` and `--vmodule` control `VLOG()` messages. So you may want to use a combination of these three switches depending on the granularity you want and what logging calls are made by the code you're trying to watch. See [Chromium Logging source][logging] for more information on how `LOG()` and `VLOG()` interact. Loosely speaking, `VLOG()` can be thought of as sub-levels / per-module levels inside `LOG(INFO)` to control the firehose of `LOG(INFO)` data. See also `--enable-logging`, `--log-level`, `--v`, and `--vmodule`. ### --no-proxy-server Don't use a proxy server and always make direct connections. Overrides any other proxy server flags that are passed. ### --no-sandbox Disables the Chromium [sandbox](https://www.chromium.org/developers/design-documents/sandbox). Forces renderer process and Chromium helper processes to run un-sandboxed. Should only be used for testing. ### --proxy-bypass-list=`hosts` Instructs Electron to bypass the proxy server for the given semi-colon-separated list of hosts. This flag has an effect only if used in tandem with `--proxy-server`. For example: ```javascript const { app } = require('electron') app.commandLine.appendSwitch('proxy-bypass-list', '<local>;*.google.com;*foo.com;1.2.3.4:5678') ``` Will use the proxy server for all hosts except for local addresses (`localhost`, `127.0.0.1` etc.), `google.com` subdomains, hosts that contain the suffix `foo.com` and anything at `1.2.3.4:5678`. ### --proxy-pac-url=`url` Uses the PAC script at the specified `url`. ### --proxy-server=`address:port` Use a specified proxy server, which overrides the system setting. This switch only affects requests with HTTP protocol, including HTTPS and WebSocket requests. It is also noteworthy that not all proxy servers support HTTPS and WebSocket requests. The proxy URL does not support username and password authentication [per Chromium issue](https://bugs.chromium.org/p/chromium/issues/detail?id=615947). ### --remote-debugging-port=`port` Enables remote debugging over HTTP on the specified `port`. ### --v=`log_level` Gives the default maximal active V-logging level; 0 is the default. Normally positive values are used for V-logging levels. This switch only works when `--enable-logging` is also passed. See also `--enable-logging`, `--log-level`, and `--vmodule`. ### --vmodule=`pattern` Gives the per-module maximal V-logging levels to override the value given by `--v`. E.g. `my_module=2,foo*=3` would change the logging level for all code in source files `my_module.*` and `foo*.*`. Any pattern containing a forward or backward slash will be tested against the whole pathname and not only the module. E.g. `*/foo/bar/*=2` would change the logging level for all code in the source files under a `foo/bar` directory. This switch only works when `--enable-logging` is also passed. See also `--enable-logging`, `--log-level`, and `--v`. ### --force_high_performance_gpu Force using discrete GPU when there are multiple GPUs available. ### --force_low_power_gpu Force using integrated GPU when there are multiple GPUs available. ## Node.js Flags Electron supports some of the [CLI flags][node-cli] supported by Node.js. **Note:** Passing unsupported command line switches to Electron when it is not running in `ELECTRON_RUN_AS_NODE` will have no effect. ### `--inspect-brk\[=\[host:]port]` Activate inspector on host:port and break at start of user script. Default host:port is 127.0.0.1:9229. Aliased to `--debug-brk=[host:]port`. #### `--inspect-brk-node[=[host:]port]` Activate inspector on `host:port` and break at start of the first internal JavaScript script executed when the inspector is available. Default `host:port` is `127.0.0.1:9229`. ### `--inspect-port=\[host:]port` Set the `host:port` to be used when the inspector is activated. Useful when activating the inspector by sending the SIGUSR1 signal. Default host is `127.0.0.1`. Aliased to `--debug-port=[host:]port`. ### `--inspect\[=\[host:]port]` Activate inspector on `host:port`. Default is `127.0.0.1:9229`. V8 inspector integration allows tools such as Chrome DevTools and IDEs to debug and profile Electron instances. The tools attach to Electron instances via a TCP port and communicate using the [Chrome DevTools Protocol](https://chromedevtools.github.io/devtools-protocol/). See the [Debugging the Main Process][debugging-main-process] guide for more details. Aliased to `--debug[=[host:]port`. ### `--inspect-publish-uid=stderr,http` Specify ways of the inspector web socket url exposure. By default inspector websocket url is available in stderr and under /json/list endpoint on http://host:port/json/list. ### `--no-deprecation` Silence deprecation warnings. ### `--throw-deprecation` Throw errors for deprecations. ### `--trace-deprecation` Print stack traces for deprecations. ### `--trace-warnings` Print stack traces for process warnings (including deprecations). ### `--dns-result-order=order` Set the default value of the `verbatim` parameter in the Node.js [`dns.lookup()`](https://nodejs.org/api/dns.html#dnslookuphostname-options-callback) and [`dnsPromises.lookup()`](https://nodejs.org/api/dns.html#dnspromiseslookuphostname-options) functions. The value could be: * `ipv4first`: sets default `verbatim` `false`. * `verbatim`: sets default `verbatim` `true`. The default is `verbatim` and `dns.setDefaultResultOrder()` have higher priority than `--dns-result-order`. [app]: app.md [append-switch]: command-line.md#commandlineappendswitchswitch-value [debugging-main-process]: ../tutorial/debugging-main-process.md [logging]: https://source.chromium.org/chromium/chromium/src/+/main:base/logging.h [node-cli]: https://nodejs.org/api/cli.html [play-silent-audio]: https://github.com/atom/atom/pull/9485/files [ready]: app.md#event-ready [severities]: https://source.chromium.org/chromium/chromium/src/+/main:base/logging.h?q=logging::LogSeverity&ss=chromium
closed
electron/electron
https://github.com/electron/electron
39,288
[Bug]: js-flags 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 25.3.1 ### What operating system are you using? macOS ### Operating System Version 10.15.7 ### What arch are you using? x64 ### Last Known Working Electron version no test ### Expected Behavior `electron --js-flags="--enable-source-maps" .` makes node supports sourcemap ### Actual Behavior Error: unrecognized flag --enable-source-maps Try --help for options ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/39288
https://github.com/electron/electron/pull/39465
1d20ec5b990085fb38cc0494435cd6f57e0e8b3e
22429e21129bd22c06c23f7d714b96d31063d495
2023-07-30T11:40:10Z
c++
2023-08-15T18:49:21Z
shell/app/node_main.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/app/node_main.h" #include <map> #include <memory> #include <string> #include <utility> #include <vector> #include "base/base_switches.h" #include "base/command_line.h" #include "base/containers/fixed_flat_set.h" #include "base/feature_list.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "base/task/single_thread_task_runner.h" #include "base/task/thread_pool/thread_pool_instance.h" #include "content/public/common/content_switches.h" #include "electron/electron_version.h" #include "gin/array_buffer.h" #include "gin/public/isolate_holder.h" #include "gin/v8_initializer.h" #include "shell/app/uv_task_runner.h" #include "shell/browser/javascript_environment.h" #include "shell/common/api/electron_bindings.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/node_bindings.h" #include "shell/common/node_includes.h" #if BUILDFLAG(IS_WIN) #include "chrome/child/v8_crashpad_support_win.h" #endif #if BUILDFLAG(IS_LINUX) #include "base/environment.h" #include "base/posix/global_descriptors.h" #include "base/strings/string_number_conversions.h" #include "components/crash/core/app/crash_switches.h" // nogncheck #include "content/public/common/content_descriptors.h" #endif #if !IS_MAS_BUILD() #include "components/crash/core/app/crashpad.h" // nogncheck #include "shell/app/electron_crash_reporter_client.h" #include "shell/common/crash_keys.h" #endif namespace { // Initialize Node.js cli options to pass to Node.js // See https://nodejs.org/api/cli.html#cli_options int SetNodeCliFlags() { // Options that are unilaterally disallowed static constexpr auto disallowed = base::MakeFixedFlatSet<base::StringPiece>({ "--enable-fips", "--force-fips", "--openssl-config", "--use-bundled-ca", "--use-openssl-ca", }); const auto argv = base::CommandLine::ForCurrentProcess()->argv(); std::vector<std::string> args; // TODO(codebytere): We need to set the first entry in args to the // process name owing to src/node_options-inl.h#L286-L290 but this is // redundant and so should be refactored upstream. args.reserve(argv.size() + 1); args.emplace_back("electron"); for (const auto& arg : argv) { #if BUILDFLAG(IS_WIN) const auto& option = base::WideToUTF8(arg); #else const auto& option = arg; #endif const auto stripped = base::StringPiece(option).substr(0, option.find('=')); if (disallowed.contains(stripped)) { LOG(ERROR) << "The Node.js cli flag " << stripped << " is not supported in Electron"; // Node.js returns 9 from ProcessGlobalArgs for any errors encountered // when setting up cli flags and env vars. Since we're outlawing these // flags (making them errors) return 9 here for consistency. return 9; } else { args.push_back(option); } } std::vector<std::string> errors; // Node.js itself will output parsing errors to // console so we don't need to handle that ourselves return ProcessGlobalArgs(&args, nullptr, &errors, node::kDisallowedInEnvironment); } #if IS_MAS_BUILD() void SetCrashKeyStub(const std::string& key, const std::string& value) {} void ClearCrashKeyStub(const std::string& key) {} #endif } // namespace namespace electron { v8::Local<v8::Value> GetParameters(v8::Isolate* isolate) { std::map<std::string, std::string> keys; #if !IS_MAS_BUILD() electron::crash_keys::GetCrashKeys(&keys); #endif return gin::ConvertToV8(isolate, keys); } int NodeMain(int argc, char* argv[]) { base::CommandLine::Init(argc, argv); #if BUILDFLAG(IS_WIN) v8_crashpad_support::SetUp(); #endif #if BUILDFLAG(IS_LINUX) auto os_env = base::Environment::Create(); std::string fd_string, pid_string; if (os_env->GetVar("CRASHDUMP_SIGNAL_FD", &fd_string) && os_env->GetVar("CRASHPAD_HANDLER_PID", &pid_string)) { int fd = -1, pid = -1; DCHECK(base::StringToInt(fd_string, &fd)); DCHECK(base::StringToInt(pid_string, &pid)); base::GlobalDescriptors::GetInstance()->Set(kCrashDumpSignal, fd); // Following API is unsafe in multi-threaded scenario, but at this point // we are still single threaded. os_env->UnSetVar("CRASHDUMP_SIGNAL_FD"); os_env->UnSetVar("CRASHPAD_HANDLER_PID"); } #endif int exit_code = 1; { // Feed gin::PerIsolateData with a task runner. uv_loop_t* loop = uv_default_loop(); auto uv_task_runner = base::MakeRefCounted<UvTaskRunner>(loop); base::SingleThreadTaskRunner::CurrentDefaultHandle handle(uv_task_runner); // Initialize feature list. auto feature_list = std::make_unique<base::FeatureList>(); feature_list->InitializeFromCommandLine("", ""); base::FeatureList::SetInstance(std::move(feature_list)); // Explicitly register electron's builtin bindings. NodeBindings::RegisterBuiltinBindings(); // Parse and set Node.js cli flags. int flags_exit_code = SetNodeCliFlags(); if (flags_exit_code != 0) exit(flags_exit_code); // Hack around with the argv pointer. Used for process.title = "blah". argv = uv_setup_args(argc, argv); std::vector<std::string> args(argv, argv + argc); std::unique_ptr<node::InitializationResult> result = node::InitializeOncePerProcess( args, {node::ProcessInitializationFlags::kNoInitializeV8, node::ProcessInitializationFlags::kNoInitializeNodeV8Platform}); for (const std::string& error : result->errors()) fprintf(stderr, "%s: %s\n", args[0].c_str(), error.c_str()); if (result->early_return() != 0) { return result->exit_code(); } #if BUILDFLAG(IS_LINUX) // On Linux, initialize crashpad after Nodejs init phase so that // crash and termination signal handlers can be set by the crashpad client. if (!pid_string.empty()) { auto* command_line = base::CommandLine::ForCurrentProcess(); command_line->AppendSwitchASCII( crash_reporter::switches::kCrashpadHandlerPid, pid_string); ElectronCrashReporterClient::Create(); crash_reporter::InitializeCrashpad(false, "node"); crash_keys::SetCrashKeysFromCommandLine( *base::CommandLine::ForCurrentProcess()); crash_keys::SetPlatformCrashKey(); // Ensure the flags and env variable does not propagate to userland. command_line->RemoveSwitch(crash_reporter::switches::kCrashpadHandlerPid); } #elif BUILDFLAG(IS_WIN) || (BUILDFLAG(IS_MAC) && !IS_MAS_BUILD()) ElectronCrashReporterClient::Create(); crash_reporter::InitializeCrashpad(false, "node"); crash_keys::SetCrashKeysFromCommandLine( *base::CommandLine::ForCurrentProcess()); crash_keys::SetPlatformCrashKey(); #endif gin::V8Initializer::LoadV8Snapshot( gin::V8SnapshotFileType::kWithAdditionalContext); // V8 requires a task scheduler. base::ThreadPoolInstance::CreateAndStartWithDefaultParams("Electron"); // Allow Node.js to track the amount of time the event loop has spent // idle in the kernel’s event provider . uv_loop_configure(loop, UV_METRICS_IDLE_TIME); // Initialize gin::IsolateHolder. bool setup_wasm_streaming = node::per_process::cli_options->get_per_isolate_options() ->get_per_env_options() ->experimental_fetch; JavascriptEnvironment gin_env(loop, setup_wasm_streaming); v8::Isolate* isolate = gin_env.isolate(); v8::Isolate::Scope isolate_scope(isolate); v8::Locker locker(isolate); node::Environment* env = nullptr; node::IsolateData* isolate_data = nullptr; { v8::HandleScope scope(isolate); isolate_data = node::CreateIsolateData(isolate, loop, gin_env.platform()); CHECK_NE(nullptr, isolate_data); uint64_t env_flags = node::EnvironmentFlags::kDefaultFlags | node::EnvironmentFlags::kHideConsoleWindows; env = node::CreateEnvironment( isolate_data, isolate->GetCurrentContext(), result->args(), result->exec_args(), static_cast<node::EnvironmentFlags::Flags>(env_flags)); CHECK_NE(nullptr, env); node::SetIsolateUpForNode(isolate); gin_helper::Dictionary process(isolate, env->process_object()); process.SetMethod("crash", &ElectronBindings::Crash); // Setup process.crashReporter in child node processes gin_helper::Dictionary reporter = gin::Dictionary::CreateEmpty(isolate); reporter.SetMethod("getParameters", &GetParameters); #if IS_MAS_BUILD() reporter.SetMethod("addExtraParameter", &SetCrashKeyStub); reporter.SetMethod("removeExtraParameter", &ClearCrashKeyStub); #else reporter.SetMethod("addExtraParameter", &electron::crash_keys::SetCrashKey); reporter.SetMethod("removeExtraParameter", &electron::crash_keys::ClearCrashKey); #endif process.Set("crashReporter", reporter); gin_helper::Dictionary versions; if (process.Get("versions", &versions)) { versions.SetReadOnly(ELECTRON_PROJECT_NAME, ELECTRON_VERSION_STRING); } } v8::HandleScope scope(isolate); node::LoadEnvironment(env, node::StartExecutionCallback{}); // Potential reasons we get Nothing here may include: the env // is stopping, or the user hooks process.emit('exit'). exit_code = node::SpinEventLoop(env).FromMaybe(1); node::ResetStdio(); node::Stop(env, node::StopFlags::kDoNotTerminateIsolate); node::FreeEnvironment(env); node::FreeIsolateData(isolate_data); } // According to "src/gin/shell/gin_main.cc": // // gin::IsolateHolder waits for tasks running in ThreadPool in its // destructor and thus must be destroyed before ThreadPool starts skipping // CONTINUE_ON_SHUTDOWN tasks. base::ThreadPoolInstance::Get()->Shutdown(); v8::V8::Dispose(); return exit_code; } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
39,288
[Bug]: js-flags 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 25.3.1 ### What operating system are you using? macOS ### Operating System Version 10.15.7 ### What arch are you using? x64 ### Last Known Working Electron version no test ### Expected Behavior `electron --js-flags="--enable-source-maps" .` makes node supports sourcemap ### Actual Behavior Error: unrecognized flag --enable-source-maps Try --help for options ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/39288
https://github.com/electron/electron/pull/39465
1d20ec5b990085fb38cc0494435cd6f57e0e8b3e
22429e21129bd22c06c23f7d714b96d31063d495
2023-07-30T11:40:10Z
c++
2023-08-15T18:49:21Z
shell/common/node_bindings.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/common/node_bindings.h" #include <algorithm> #include <string> #include <utility> #include <vector> #include "base/base_paths.h" #include "base/command_line.h" #include "base/containers/fixed_flat_set.h" #include "base/environment.h" #include "base/path_service.h" #include "base/run_loop.h" #include "base/strings/string_split.h" #include "base/strings/utf_string_conversions.h" #include "base/task/single_thread_task_runner.h" #include "base/trace_event/trace_event.h" #include "content/public/browser/browser_thread.h" #include "content/public/common/content_paths.h" #include "electron/buildflags/buildflags.h" #include "electron/fuses.h" #include "shell/browser/api/electron_api_app.h" #include "shell/common/api/electron_bindings.h" #include "shell/common/electron_command_line.h" #include "shell/common/gin_converters/file_path_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/gin_helper/event.h" #include "shell/common/gin_helper/event_emitter_caller.h" #include "shell/common/gin_helper/locker.h" #include "shell/common/gin_helper/microtasks_scope.h" #include "shell/common/mac/main_application_bundle.h" #include "third_party/blink/renderer/bindings/core/v8/v8_initializer.h" // nogncheck #include "third_party/electron_node/src/debug_utils.h" #if !IS_MAS_BUILD() #include "shell/common/crash_keys.h" #endif #define ELECTRON_BROWSER_BINDINGS(V) \ V(electron_browser_app) \ V(electron_browser_auto_updater) \ V(electron_browser_browser_view) \ V(electron_browser_content_tracing) \ V(electron_browser_crash_reporter) \ V(electron_browser_desktop_capturer) \ V(electron_browser_dialog) \ V(electron_browser_event_emitter) \ V(electron_browser_global_shortcut) \ V(electron_browser_in_app_purchase) \ V(electron_browser_menu) \ V(electron_browser_message_port) \ V(electron_browser_native_theme) \ V(electron_browser_net) \ V(electron_browser_notification) \ V(electron_browser_power_monitor) \ V(electron_browser_power_save_blocker) \ V(electron_browser_protocol) \ V(electron_browser_printing) \ V(electron_browser_push_notifications) \ V(electron_browser_safe_storage) \ V(electron_browser_session) \ V(electron_browser_screen) \ V(electron_browser_system_preferences) \ V(electron_browser_base_window) \ V(electron_browser_tray) \ V(electron_browser_utility_process) \ V(electron_browser_view) \ V(electron_browser_web_contents) \ V(electron_browser_web_contents_view) \ V(electron_browser_web_frame_main) \ V(electron_browser_web_view_manager) \ V(electron_browser_window) #define ELECTRON_COMMON_BINDINGS(V) \ V(electron_common_asar) \ V(electron_common_clipboard) \ V(electron_common_command_line) \ V(electron_common_crashpad_support) \ V(electron_common_environment) \ V(electron_common_features) \ V(electron_common_native_image) \ V(electron_common_shell) \ V(electron_common_v8_util) #define ELECTRON_RENDERER_BINDINGS(V) \ V(electron_renderer_context_bridge) \ V(electron_renderer_crash_reporter) \ V(electron_renderer_ipc) \ V(electron_renderer_web_frame) #define ELECTRON_UTILITY_BINDINGS(V) V(electron_utility_parent_port) #define ELECTRON_VIEWS_BINDINGS(V) V(electron_browser_image_view) #define ELECTRON_TESTING_BINDINGS(V) V(electron_common_testing) // This is used to load built-in bindings. Instead of using // __attribute__((constructor)), we call the _register_<modname> // function for each built-in bindings explicitly. This is only // forward declaration. The definitions are in each binding's // implementation when calling the NODE_LINKED_BINDING_CONTEXT_AWARE. #define V(modname) void _register_##modname(); ELECTRON_BROWSER_BINDINGS(V) ELECTRON_COMMON_BINDINGS(V) ELECTRON_RENDERER_BINDINGS(V) ELECTRON_UTILITY_BINDINGS(V) #if BUILDFLAG(ENABLE_VIEWS_API) ELECTRON_VIEWS_BINDINGS(V) #endif #if DCHECK_IS_ON() ELECTRON_TESTING_BINDINGS(V) #endif #undef V namespace { void stop_and_close_uv_loop(uv_loop_t* loop) { uv_stop(loop); auto const ensure_closing = [](uv_handle_t* handle, void*) { // We should be using the UvHandle wrapper everywhere, in which case // all handles should already be in a closing state... DCHECK(uv_is_closing(handle)); // ...but if a raw handle got through, through, do the right thing anyway if (!uv_is_closing(handle)) { uv_close(handle, nullptr); } }; uv_walk(loop, ensure_closing, nullptr); // All remaining handles are in a closing state now. // Pump the event loop so that they can finish closing. for (;;) if (uv_run(loop, UV_RUN_DEFAULT) == 0) break; DCHECK_EQ(0, uv_loop_alive(loop)); node::CheckedUvLoopClose(loop); } bool g_is_initialized = false; void V8FatalErrorCallback(const char* location, const char* message) { LOG(ERROR) << "Fatal error in V8: " << location << " " << message; #if !IS_MAS_BUILD() electron::crash_keys::SetCrashKey("electron.v8-fatal.message", message); electron::crash_keys::SetCrashKey("electron.v8-fatal.location", location); #endif volatile int* zero = nullptr; *zero = 0; } bool AllowWasmCodeGenerationCallback(v8::Local<v8::Context> context, v8::Local<v8::String> source) { // If we're running with contextIsolation enabled in the renderer process, // fall back to Blink's logic. if (node::Environment::GetCurrent(context) == nullptr) { if (!electron::IsRendererProcess()) return false; return blink::V8Initializer::WasmCodeGenerationCheckCallbackInMainThread( context, source); } return node::AllowWasmCodeGenerationCallback(context, source); } v8::ModifyCodeGenerationFromStringsResult ModifyCodeGenerationFromStrings( v8::Local<v8::Context> context, v8::Local<v8::Value> source, bool is_code_like) { if (node::Environment::GetCurrent(context) == nullptr) { // No node environment means we're in the renderer process, either in a // sandboxed renderer or in an unsandboxed renderer with context isolation // enabled. if (!electron::IsRendererProcess()) { NOTREACHED(); return {false, {}}; } return blink::V8Initializer::CodeGenerationCheckCallbackInMainThread( context, source, is_code_like); } // If we get here then we have a node environment, so either a) we're in the // non-rendrer process, or b) we're in the renderer process in a context that // has both node and blink, i.e. contextIsolation disabled. // If we're in the renderer with contextIsolation disabled, ask blink first // (for CSP), and iff that allows codegen, delegate to node. if (electron::IsRendererProcess()) { v8::ModifyCodeGenerationFromStringsResult result = blink::V8Initializer::CodeGenerationCheckCallbackInMainThread( context, source, is_code_like); if (!result.codegen_allowed) return result; } // If we're in the main process or utility process, delegate to node. return node::ModifyCodeGenerationFromStrings(context, source, is_code_like); } void ErrorMessageListener(v8::Local<v8::Message> message, v8::Local<v8::Value> data) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); node::Environment* env = node::Environment::GetCurrent(isolate); if (env) { gin_helper::MicrotasksScope microtasks_scope( isolate, env->context()->GetMicrotaskQueue(), v8::MicrotasksScope::kDoNotRunMicrotasks); // Emit the after() hooks now that the exception has been handled. // Analogous to node/lib/internal/process/execution.js#L176-L180 if (env->async_hooks()->fields()[node::AsyncHooks::kAfter]) { while (env->async_hooks()->fields()[node::AsyncHooks::kStackLength]) { node::AsyncWrap::EmitAfter(env, env->execution_async_id()); env->async_hooks()->pop_async_context(env->execution_async_id()); } } // Ensure that the async id stack is properly cleared so the async // hook stack does not become corrupted. env->async_hooks()->clear_async_id_stack(); } } // Only allow a specific subset of options in non-ELECTRON_RUN_AS_NODE mode. // If node CLI inspect support is disabled, allow no debug options. bool IsAllowedOption(base::StringPiece option) { static constexpr auto debug_options = base::MakeFixedFlatSet<base::StringPiece>({ "--debug", "--debug-brk", "--debug-port", "--inspect", "--inspect-brk", "--inspect-brk-node", "--inspect-port", "--inspect-publish-uid", }); // This should be aligned with what's possible to set via the process object. static constexpr auto options = base::MakeFixedFlatSet<base::StringPiece>({ "--trace-warnings", "--trace-deprecation", "--throw-deprecation", "--no-deprecation", "--dns-result-order", }); if (debug_options.contains(option)) return electron::fuses::IsNodeCliInspectEnabled(); return options.contains(option); } // Initialize NODE_OPTIONS to pass to Node.js // See https://nodejs.org/api/cli.html#cli_node_options_options void SetNodeOptions(base::Environment* env) { // Options that are unilaterally disallowed static constexpr auto disallowed = base::MakeFixedFlatSet<base::StringPiece>( {"--enable-fips", "--force-fips", "--openssl-config", "--use-bundled-ca", "--use-openssl-ca", "--experimental-policy"}); static constexpr auto pkg_opts = base::MakeFixedFlatSet<base::StringPiece>({ "--http-parser", "--max-http-header-size", }); if (env->HasVar("NODE_OPTIONS")) { if (electron::fuses::IsNodeOptionsEnabled()) { std::string options; env->GetVar("NODE_OPTIONS", &options); std::vector<std::string> parts = base::SplitString( options, " ", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY); bool is_packaged_app = electron::api::App::IsPackaged(); for (const auto& part : parts) { // Strip off values passed to individual NODE_OPTIONs std::string option = part.substr(0, part.find('=')); if (is_packaged_app && !pkg_opts.contains(option)) { // Explicitly disallow majority of NODE_OPTIONS in packaged apps LOG(ERROR) << "Most NODE_OPTIONs are not supported in packaged apps." << " See documentation for more details."; options.erase(options.find(option), part.length()); } else if (disallowed.contains(option)) { // Remove NODE_OPTIONS specifically disallowed for use in Node.js // through Electron owing to constraints like BoringSSL. LOG(ERROR) << "The NODE_OPTION " << option << " is not supported in Electron"; options.erase(options.find(option), part.length()); } } // overwrite new NODE_OPTIONS without unsupported variables env->SetVar("NODE_OPTIONS", options); } else { LOG(ERROR) << "NODE_OPTIONS have been disabled in this app"; env->SetVar("NODE_OPTIONS", ""); } } } } // namespace namespace electron { namespace { base::FilePath GetResourcesPath() { #if BUILDFLAG(IS_MAC) return MainApplicationBundlePath().Append("Contents").Append("Resources"); #else auto* command_line = base::CommandLine::ForCurrentProcess(); base::FilePath exec_path(command_line->GetProgram()); base::PathService::Get(base::FILE_EXE, &exec_path); return exec_path.DirName().Append(FILE_PATH_LITERAL("resources")); #endif } } // namespace NodeBindings::NodeBindings(BrowserEnvironment browser_env) : browser_env_(browser_env) { if (browser_env == BrowserEnvironment::kWorker) { uv_loop_init(&worker_loop_); uv_loop_ = &worker_loop_; } else { uv_loop_ = uv_default_loop(); } // Interrupt embed polling when a handle is started. uv_loop_configure(uv_loop_, UV_LOOP_INTERRUPT_ON_IO_CHANGE); } NodeBindings::~NodeBindings() { // Quit the embed thread. embed_closed_ = true; uv_sem_post(&embed_sem_); WakeupEmbedThread(); // Wait for everything to be done. uv_thread_join(&embed_thread_); // Clear uv. uv_sem_destroy(&embed_sem_); dummy_uv_handle_.reset(); // Clean up worker loop if (in_worker_loop()) stop_and_close_uv_loop(uv_loop_); } void NodeBindings::RegisterBuiltinBindings() { #define V(modname) _register_##modname(); if (IsBrowserProcess()) { ELECTRON_BROWSER_BINDINGS(V) #if BUILDFLAG(ENABLE_VIEWS_API) ELECTRON_VIEWS_BINDINGS(V) #endif } ELECTRON_COMMON_BINDINGS(V) if (IsRendererProcess()) { ELECTRON_RENDERER_BINDINGS(V) } if (IsUtilityProcess()) { ELECTRON_UTILITY_BINDINGS(V) } #if DCHECK_IS_ON() ELECTRON_TESTING_BINDINGS(V) #endif #undef V } bool NodeBindings::IsInitialized() { return g_is_initialized; } // Initialize Node.js cli options to pass to Node.js // See https://nodejs.org/api/cli.html#cli_options void NodeBindings::SetNodeCliFlags() { const auto argv = base::CommandLine::ForCurrentProcess()->argv(); std::vector<std::string> args; // TODO(codebytere): We need to set the first entry in args to the // process name owing to src/node_options-inl.h#L286-L290 but this is // redundant and so should be refactored upstream. args.reserve(argv.size() + 1); args.emplace_back("electron"); for (const auto& arg : argv) { #if BUILDFLAG(IS_WIN) const auto& option = base::WideToUTF8(arg); #else const auto& option = arg; #endif const auto stripped = base::StringPiece(option).substr(0, option.find('=')); // Only allow in no-op (--) option or a small set of debug // and trace related options. if (IsAllowedOption(stripped) || stripped == "--") args.push_back(option); } // We need to disable Node.js' fetch implementation to prevent // conflict with Blink's in renderer and worker processes. if (browser_env_ == BrowserEnvironment::kRenderer || browser_env_ == BrowserEnvironment::kWorker) { args.push_back("--no-experimental-fetch"); } std::vector<std::string> errors; const int exit_code = ProcessGlobalArgs(&args, nullptr, &errors, node::kDisallowedInEnvironment); const std::string err_str = "Error parsing Node.js cli flags "; if (exit_code != 0) { LOG(ERROR) << err_str; } else if (!errors.empty()) { LOG(ERROR) << err_str << base::JoinString(errors, " "); } } void NodeBindings::Initialize(v8::Local<v8::Context> context) { TRACE_EVENT0("electron", "NodeBindings::Initialize"); // Open node's error reporting system for browser process. #if BUILDFLAG(IS_LINUX) // Get real command line in renderer process forked by zygote. if (browser_env_ != BrowserEnvironment::kBrowser) ElectronCommandLine::InitializeFromCommandLine(); #endif // Explicitly register electron's builtin bindings. RegisterBuiltinBindings(); // Parse and set Node.js cli flags. SetNodeCliFlags(); auto env = base::Environment::Create(); SetNodeOptions(env.get()); std::vector<std::string> argv = {"electron"}; std::vector<std::string> exec_argv; std::vector<std::string> errors; uint64_t process_flags = node::ProcessFlags::kNoFlags; // We do not want the child processes spawned from the utility process // to inherit the custom stdio handles created for the parent. if (browser_env_ != BrowserEnvironment::kUtility) process_flags |= node::ProcessFlags::kEnableStdioInheritance; if (!fuses::IsNodeOptionsEnabled()) process_flags |= node::ProcessFlags::kDisableNodeOptionsEnv; int exit_code = node::InitializeNodeWithArgs( &argv, &exec_argv, &errors, static_cast<node::ProcessFlags::Flags>(process_flags)); for (const std::string& error : errors) fprintf(stderr, "%s: %s\n", argv[0].c_str(), error.c_str()); if (exit_code != 0) exit(exit_code); #if BUILDFLAG(IS_WIN) // uv_init overrides error mode to suppress the default crash dialog, bring // it back if user wants to show it. if (browser_env_ == BrowserEnvironment::kBrowser || env->HasVar("ELECTRON_DEFAULT_ERROR_MODE")) SetErrorMode(GetErrorMode() & ~SEM_NOGPFAULTERRORBOX); #endif gin_helper::internal::Event::GetConstructor(context); g_is_initialized = true; } node::Environment* NodeBindings::CreateEnvironment( v8::Handle<v8::Context> context, node::MultiIsolatePlatform* platform, std::vector<std::string> args, std::vector<std::string> exec_args) { // Feed node the path to initialization script. std::string process_type; switch (browser_env_) { case BrowserEnvironment::kBrowser: process_type = "browser"; break; case BrowserEnvironment::kRenderer: process_type = "renderer"; break; case BrowserEnvironment::kWorker: process_type = "worker"; break; case BrowserEnvironment::kUtility: process_type = "utility"; break; } v8::Isolate* isolate = context->GetIsolate(); gin_helper::Dictionary global(isolate, context->Global()); if (browser_env_ == BrowserEnvironment::kBrowser) { const std::vector<std::string> search_paths = {"app.asar", "app", "default_app.asar"}; const std::vector<std::string> app_asar_search_paths = {"app.asar"}; context->Global()->SetPrivate( context, v8::Private::ForApi( isolate, gin::ConvertToV8(isolate, "appSearchPaths").As<v8::String>()), gin::ConvertToV8(isolate, electron::fuses::IsOnlyLoadAppFromAsarEnabled() ? app_asar_search_paths : search_paths)); } base::FilePath resources_path = GetResourcesPath(); std::string init_script = "electron/js2c/" + process_type + "_init"; args.insert(args.begin() + 1, init_script); auto* isolate_data = node::CreateIsolateData(isolate, uv_loop_, platform); context->SetAlignedPointerInEmbedderData(kElectronContextEmbedderDataIndex, static_cast<void*>(isolate_data)); node::Environment* env; uint64_t flags = node::EnvironmentFlags::kDefaultFlags | node::EnvironmentFlags::kHideConsoleWindows | node::EnvironmentFlags::kNoGlobalSearchPaths; if (browser_env_ == BrowserEnvironment::kRenderer || browser_env_ == BrowserEnvironment::kWorker) { // Only one ESM loader can be registered per isolate - // in renderer processes this should be blink. We need to tell Node.js // not to register its handler (overriding blinks) in non-browser processes. // We also avoid overriding globals like setImmediate, clearImmediate // queueMicrotask etc during the bootstrap phase of Node.js // for processes that already have these defined by DOM. // Check //third_party/electron_node/lib/internal/bootstrap/node.js // for the list of overrides on globalThis. flags |= node::EnvironmentFlags::kNoRegisterESMLoader | node::EnvironmentFlags::kNoBrowserGlobals | node::EnvironmentFlags::kNoCreateInspector; } if (!electron::fuses::IsNodeCliInspectEnabled()) { // If --inspect and friends are disabled we also shouldn't listen for // SIGUSR1 flags |= node::EnvironmentFlags::kNoStartDebugSignalHandler; } { v8::TryCatch try_catch(isolate); env = node::CreateEnvironment( static_cast<node::IsolateData*>(isolate_data), context, args, exec_args, static_cast<node::EnvironmentFlags::Flags>(flags)); if (try_catch.HasCaught()) { std::string err_msg = "Failed to initialize node environment in process: " + process_type; v8::Local<v8::Message> message = try_catch.Message(); std::string msg; if (!message.IsEmpty() && gin::ConvertFromV8(isolate, message->Get(), &msg)) err_msg += " , with error: " + msg; LOG(ERROR) << err_msg; } } DCHECK(env); node::IsolateSettings is; // Use a custom fatal error callback to allow us to add // crash message and location to CrashReports. is.fatal_error_callback = V8FatalErrorCallback; // We don't want to abort either in the renderer or browser processes. // We already listen for uncaught exceptions and handle them there. // For utility process we expect the process to behave as standard // Node.js runtime and abort the process with appropriate exit // code depending on a handler being set for `uncaughtException` event. if (browser_env_ != BrowserEnvironment::kUtility) { is.should_abort_on_uncaught_exception_callback = [](v8::Isolate*) { return false; }; } // Use a custom callback here to allow us to leverage Blink's logic in the // renderer process. is.allow_wasm_code_generation_callback = AllowWasmCodeGenerationCallback; is.flags |= node::IsolateSettingsFlags:: ALLOW_MODIFY_CODE_GENERATION_FROM_STRINGS_CALLBACK; is.modify_code_generation_from_strings_callback = ModifyCodeGenerationFromStrings; if (browser_env_ == BrowserEnvironment::kBrowser || browser_env_ == BrowserEnvironment::kUtility) { // Node.js requires that microtask checkpoints be explicitly invoked. is.policy = v8::MicrotasksPolicy::kExplicit; } else { // Blink expects the microtasks policy to be kScoped, but Node.js expects it // to be kExplicit. In the renderer, there can be many contexts within the // same isolate, so we don't want to change the existing policy here, which // could be either kExplicit or kScoped depending on whether we're executing // from within a Node.js or a Blink entrypoint. Instead, the policy is // toggled to kExplicit when entering Node.js through UvRunOnce. is.policy = context->GetIsolate()->GetMicrotasksPolicy(); // We do not want to use Node.js' message listener as it interferes with // Blink's. is.flags &= ~node::IsolateSettingsFlags::MESSAGE_LISTENER_WITH_ERROR_LEVEL; // Isolate message listeners are additive (you can add multiple), so instead // we add an extra one here to ensure that the async hook stack is properly // cleared when errors are thrown. context->GetIsolate()->AddMessageListenerWithErrorLevel( ErrorMessageListener, v8::Isolate::kMessageError); // We do not want to use the promise rejection callback that Node.js uses, // because it does not send PromiseRejectionEvents to the global script // context. We need to use the one Blink already provides. is.flags |= node::IsolateSettingsFlags::SHOULD_NOT_SET_PROMISE_REJECTION_CALLBACK; // We do not want to use the stack trace callback that Node.js uses, // because it relies on Node.js being aware of the current Context and // that's not always the case. We need to use the one Blink already // provides. is.flags |= node::IsolateSettingsFlags::SHOULD_NOT_SET_PREPARE_STACK_TRACE_CALLBACK; } node::SetIsolateUpForNode(context->GetIsolate(), is); gin_helper::Dictionary process(context->GetIsolate(), env->process_object()); process.SetReadOnly("type", process_type); process.Set("resourcesPath", resources_path); // The path to helper app. base::FilePath helper_exec_path; base::PathService::Get(content::CHILD_PROCESS_EXE, &helper_exec_path); process.Set("helperExecPath", helper_exec_path); return env; } node::Environment* NodeBindings::CreateEnvironment( v8::Handle<v8::Context> context, node::MultiIsolatePlatform* platform) { #if BUILDFLAG(IS_WIN) auto& electron_args = ElectronCommandLine::argv(); std::vector<std::string> args(electron_args.size()); std::transform(electron_args.cbegin(), electron_args.cend(), args.begin(), [](auto& a) { return base::WideToUTF8(a); }); #else auto args = ElectronCommandLine::argv(); #endif return CreateEnvironment(context, platform, args, {}); } void NodeBindings::LoadEnvironment(node::Environment* env) { node::LoadEnvironment(env, node::StartExecutionCallback{}); gin_helper::EmitEvent(env->isolate(), env->process_object(), "loaded"); } void NodeBindings::PrepareEmbedThread() { // IOCP does not change for the process until the loop is recreated, // we ensure that there is only a single polling thread satisfying // the concurrency limit set from CreateIoCompletionPort call by // uv_loop_init for the lifetime of this process. // More background can be found at: // https://github.com/microsoft/vscode/issues/142786#issuecomment-1061673400 if (initialized_) return; // Add dummy handle for libuv, otherwise libuv would quit when there is // nothing to do. uv_async_init(uv_loop_, dummy_uv_handle_.get(), nullptr); // Start worker that will interrupt main loop when having uv events. uv_sem_init(&embed_sem_, 0); uv_thread_create(&embed_thread_, EmbedThreadRunner, this); } void NodeBindings::StartPolling() { // Avoid calling UvRunOnce if the loop is already active, // otherwise it can lead to situations were the number of active // threads processing on IOCP is greater than the concurrency limit. if (initialized_) return; initialized_ = true; // The MessageLoop should have been created, remember the one in main thread. task_runner_ = base::SingleThreadTaskRunner::GetCurrentDefault(); // Run uv loop for once to give the uv__io_poll a chance to add all events. UvRunOnce(); } void NodeBindings::UvRunOnce() { node::Environment* env = uv_env(); // When doing navigation without restarting renderer process, it may happen // that the node environment is destroyed but the message loop is still there. // In this case we should not run uv loop. if (!env) return; v8::HandleScope handle_scope(env->isolate()); // Enter node context while dealing with uv events. v8::Context::Scope context_scope(env->context()); // Node.js expects `kExplicit` microtasks policy and will run microtasks // checkpoints after every call into JavaScript. Since we use a different // policy in the renderer - switch to `kExplicit` and then drop back to the // previous policy value. v8::MicrotaskQueue* microtask_queue = env->context()->GetMicrotaskQueue(); auto old_policy = microtask_queue->microtasks_policy(); DCHECK_EQ(microtask_queue->GetMicrotasksScopeDepth(), 0); microtask_queue->set_microtasks_policy(v8::MicrotasksPolicy::kExplicit); if (browser_env_ != BrowserEnvironment::kBrowser) TRACE_EVENT_BEGIN0("devtools.timeline", "FunctionCall"); // Deal with uv events. int r = uv_run(uv_loop_, UV_RUN_NOWAIT); if (browser_env_ != BrowserEnvironment::kBrowser) TRACE_EVENT_END0("devtools.timeline", "FunctionCall"); microtask_queue->set_microtasks_policy(old_policy); if (r == 0) base::RunLoop().QuitWhenIdle(); // Quit from uv. // Tell the worker thread to continue polling. uv_sem_post(&embed_sem_); } void NodeBindings::WakeupMainThread() { DCHECK(task_runner_); task_runner_->PostTask(FROM_HERE, base::BindOnce(&NodeBindings::UvRunOnce, weak_factory_.GetWeakPtr())); } void NodeBindings::WakeupEmbedThread() { uv_async_send(dummy_uv_handle_.get()); } // static void NodeBindings::EmbedThreadRunner(void* arg) { auto* self = static_cast<NodeBindings*>(arg); while (true) { // Wait for the main loop to deal with events. uv_sem_wait(&self->embed_sem_); if (self->embed_closed_) break; // Wait for something to happen in uv loop. // Note that the PollEvents() is implemented by derived classes, so when // this class is being destructed the PollEvents() would not be available // anymore. Because of it we must make sure we only invoke PollEvents() // when this class is alive. self->PollEvents(); if (self->embed_closed_) break; // Deal with event in main thread. self->WakeupMainThread(); } } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
39,288
[Bug]: js-flags 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 25.3.1 ### What operating system are you using? macOS ### Operating System Version 10.15.7 ### What arch are you using? x64 ### Last Known Working Electron version no test ### Expected Behavior `electron --js-flags="--enable-source-maps" .` makes node supports sourcemap ### Actual Behavior Error: unrecognized flag --enable-source-maps Try --help for options ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/39288
https://github.com/electron/electron/pull/39465
1d20ec5b990085fb38cc0494435cd6f57e0e8b3e
22429e21129bd22c06c23f7d714b96d31063d495
2023-07-30T11:40:10Z
c++
2023-08-15T18:49:21Z
shell/common/node_bindings.h
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #ifndef ELECTRON_SHELL_COMMON_NODE_BINDINGS_H_ #define ELECTRON_SHELL_COMMON_NODE_BINDINGS_H_ #include <string> #include <type_traits> #include <vector> #include "base/files/file_path.h" #include "base/memory/raw_ptr.h" #include "base/memory/raw_ptr_exclusion.h" #include "base/memory/weak_ptr.h" #include "gin/public/context_holder.h" #include "gin/public/gin_embedders.h" #include "shell/common/node_includes.h" #include "uv.h" // NOLINT(build/include_directory) #include "v8/include/v8.h" namespace base { class SingleThreadTaskRunner; } namespace electron { // Choose a reasonable unique index that's higher than any Blink uses // and thus unlikely to collide with an existing index. static constexpr int kElectronContextEmbedderDataIndex = static_cast<int>(gin::kPerContextDataStartIndex) + static_cast<int>(gin::kEmbedderElectron); // A helper class to manage uv_handle_t types, e.g. uv_async_t. // // As per the uv docs: "uv_close() MUST be called on each handle before // memory is released. Moreover, the memory can only be released in // close_cb or after it has returned." This class encapsulates the work // needed to follow those requirements. template <typename T, typename std::enable_if< // these are the C-style 'subclasses' of uv_handle_t std::is_same<T, uv_async_t>::value || std::is_same<T, uv_check_t>::value || std::is_same<T, uv_fs_event_t>::value || std::is_same<T, uv_fs_poll_t>::value || std::is_same<T, uv_idle_t>::value || std::is_same<T, uv_pipe_t>::value || std::is_same<T, uv_poll_t>::value || std::is_same<T, uv_prepare_t>::value || std::is_same<T, uv_process_t>::value || std::is_same<T, uv_signal_t>::value || std::is_same<T, uv_stream_t>::value || std::is_same<T, uv_tcp_t>::value || std::is_same<T, uv_timer_t>::value || std::is_same<T, uv_tty_t>::value || std::is_same<T, uv_udp_t>::value>::type* = nullptr> class UvHandle { public: UvHandle() : t_(new T) {} ~UvHandle() { reset(); } T* get() { return t_; } uv_handle_t* handle() { return reinterpret_cast<uv_handle_t*>(t_); } void reset() { auto* h = handle(); if (h != nullptr) { DCHECK_EQ(0, uv_is_closing(h)); uv_close(h, OnClosed); t_ = nullptr; } } private: static void OnClosed(uv_handle_t* handle) { delete reinterpret_cast<T*>(handle); } RAW_PTR_EXCLUSION T* t_ = {}; }; class NodeBindings { public: enum class BrowserEnvironment { kBrowser, kRenderer, kUtility, kWorker }; static NodeBindings* Create(BrowserEnvironment browser_env); static void RegisterBuiltinBindings(); static bool IsInitialized(); virtual ~NodeBindings(); // Setup V8, libuv. void Initialize(v8::Local<v8::Context> context); void SetNodeCliFlags(); // Create the environment and load node.js. node::Environment* CreateEnvironment(v8::Handle<v8::Context> context, node::MultiIsolatePlatform* platform, std::vector<std::string> args, std::vector<std::string> exec_args); node::Environment* CreateEnvironment(v8::Handle<v8::Context> context, node::MultiIsolatePlatform* platform); // Load node.js in the environment. void LoadEnvironment(node::Environment* env); // Prepare embed thread for message loop integration. void PrepareEmbedThread(); // Notify embed thread to start polling after environment is loaded. void StartPolling(); // Clears the PerIsolateData. void clear_isolate_data(v8::Local<v8::Context> context) { context->SetAlignedPointerInEmbedderData(kElectronContextEmbedderDataIndex, nullptr); } node::IsolateData* isolate_data(v8::Local<v8::Context> context) const { if (context->GetNumberOfEmbedderDataFields() <= kElectronContextEmbedderDataIndex) { return nullptr; } auto* isolate_data = static_cast<node::IsolateData*>( context->GetAlignedPointerFromEmbedderData( kElectronContextEmbedderDataIndex)); CHECK(isolate_data); CHECK(isolate_data->event_loop()); return isolate_data; } // Gets/sets the environment to wrap uv loop. void set_uv_env(node::Environment* env) { uv_env_ = env; } node::Environment* uv_env() const { return uv_env_; } uv_loop_t* uv_loop() const { return uv_loop_; } bool in_worker_loop() const { return uv_loop_ == &worker_loop_; } // disable copy NodeBindings(const NodeBindings&) = delete; NodeBindings& operator=(const NodeBindings&) = delete; protected: explicit NodeBindings(BrowserEnvironment browser_env); // Called to poll events in new thread. virtual void PollEvents() = 0; // Run the libuv loop for once. void UvRunOnce(); // Make the main thread run libuv loop. void WakeupMainThread(); // Interrupt the PollEvents. void WakeupEmbedThread(); // Which environment we are running. const BrowserEnvironment browser_env_; // Current thread's MessageLoop. scoped_refptr<base::SingleThreadTaskRunner> task_runner_; // Current thread's libuv loop. raw_ptr<uv_loop_t> uv_loop_; private: // Thread to poll uv events. static void EmbedThreadRunner(void* arg); // Indicates whether polling thread has been created. bool initialized_ = false; // Whether the libuv loop has ended. bool embed_closed_ = false; // Loop used when constructed in WORKER mode uv_loop_t worker_loop_; // Dummy handle to make uv's loop not quit. UvHandle<uv_async_t> dummy_uv_handle_; // Thread for polling events. uv_thread_t embed_thread_; // Semaphore to wait for main loop in the embed thread. uv_sem_t embed_sem_; // Environment that to wrap the uv loop. raw_ptr<node::Environment> uv_env_ = nullptr; // Isolate data used in creating the environment raw_ptr<node::IsolateData> isolate_data_ = nullptr; base::WeakPtrFactory<NodeBindings> weak_factory_{this}; }; } // namespace electron #endif // ELECTRON_SHELL_COMMON_NODE_BINDINGS_H_
closed
electron/electron
https://github.com/electron/electron
39,413
[Bug]: App crashes with SIGTRAP while creating modal window on Mac
### 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 25.4.0 ### What operating system are you using? macOS ### Operating System Version 12.3 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version 25.1.1 ### Expected Behavior Not to crash:) ### Actual Behavior When I create new windows as modal to parent, I get crash with SIGTRAP Unfortunately, I couldn't reproduce this in small test project. Only fact I have, if I don't set new window as modal, app not crashes. ### Testcase Gist URL _No response_ ### Additional Information I can provide you part of stack trace and minidump <img width="872" alt="image" src="https://github.com/electron/electron/assets/25509934/ccfbba1b-13cd-4fee-a04c-1deff56d2dc3"> [2988dcae-9326-4b22-84d3-c0123f13e17f.dmp.zip](https://github.com/electron/electron/files/12292673/2988dcae-9326-4b22-84d3-c0123f13e17f.dmp.zip) There is very strange call for `ElectronPermissionMessageProvider::IsPrivilegeIncrease`. It seems like it never should be called. I also think it was affected here https://github.com/electron/electron/issues/38939
https://github.com/electron/electron/issues/39413
https://github.com/electron/electron/pull/39499
f7a7085019bf757700df3c2f8714e0de356203cd
1eb398b328d304f227deef0e89ca0be7b9e20755
2023-08-08T14:52:19Z
c++
2023-08-16T11:28:29Z
shell/browser/native_window_mac.mm
// 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_mac.h" #include <AvailabilityMacros.h> #include <objc/objc-runtime.h> #include <algorithm> #include <memory> #include <string> #include <utility> #include <vector> #include "base/mac/mac_util.h" #include "base/mac/scoped_cftyperef.h" #include "base/strings/sys_string_conversions.h" #include "components/remote_cocoa/app_shim/native_widget_ns_window_bridge.h" #include "components/remote_cocoa/browser/scoped_cg_window_id.h" #include "content/public/browser/browser_accessibility_state.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/desktop_media_id.h" #include "shell/browser/browser.h" #include "shell/browser/javascript_environment.h" #include "shell/browser/native_browser_view_mac.h" #include "shell/browser/ui/cocoa/electron_native_widget_mac.h" #include "shell/browser/ui/cocoa/electron_ns_window.h" #include "shell/browser/ui/cocoa/electron_ns_window_delegate.h" #include "shell/browser/ui/cocoa/electron_preview_item.h" #include "shell/browser/ui/cocoa/electron_touch_bar.h" #include "shell/browser/ui/cocoa/root_view_mac.h" #include "shell/browser/ui/cocoa/window_buttons_proxy.h" #include "shell/browser/ui/drag_util.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/window_list.h" #include "shell/common/gin_converters/gfx_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/node_includes.h" #include "shell/common/options_switches.h" #include "shell/common/process_util.h" #include "skia/ext/skia_utils_mac.h" #include "third_party/skia/include/core/SkRegion.h" #include "third_party/webrtc/modules/desktop_capture/mac/window_list_utils.h" #include "ui/base/hit_test.h" #include "ui/display/screen.h" #include "ui/gfx/skia_util.h" #include "ui/gl/gpu_switching_manager.h" #include "ui/views/background.h" #include "ui/views/cocoa/native_widget_mac_ns_window_host.h" #include "ui/views/widget/widget.h" #include "ui/views/window/native_frame_view_mac.h" #if !defined(__has_feature) || !__has_feature(objc_arc) #error "This file requires ARC support." #endif @interface ElectronProgressBar : NSProgressIndicator @end @implementation ElectronProgressBar - (void)drawRect:(NSRect)dirtyRect { if (self.style != NSProgressIndicatorStyleBar) return; // Draw edges of rounded rect. NSRect rect = NSInsetRect([self bounds], 1.0, 1.0); CGFloat radius = rect.size.height / 2; NSBezierPath* bezier_path = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [bezier_path setLineWidth:2.0]; [[NSColor grayColor] set]; [bezier_path stroke]; // Fill the rounded rect. rect = NSInsetRect(rect, 2.0, 2.0); radius = rect.size.height / 2; bezier_path = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [bezier_path setLineWidth:1.0]; [bezier_path addClip]; // Calculate the progress width. rect.size.width = floor(rect.size.width * ([self doubleValue] / [self maxValue])); // Fill the progress bar with color blue. [[NSColor colorWithSRGBRed:0.2 green:0.6 blue:1 alpha:1] set]; NSRectFill(rect); } @end namespace gin { template <> struct Converter<electron::NativeWindowMac::VisualEffectState> { static bool FromV8(v8::Isolate* isolate, v8::Handle<v8::Value> val, electron::NativeWindowMac::VisualEffectState* out) { using VisualEffectState = electron::NativeWindowMac::VisualEffectState; std::string visual_effect_state; if (!ConvertFromV8(isolate, val, &visual_effect_state)) return false; if (visual_effect_state == "followWindow") { *out = VisualEffectState::kFollowWindow; } else if (visual_effect_state == "active") { *out = VisualEffectState::kActive; } else if (visual_effect_state == "inactive") { *out = VisualEffectState::kInactive; } else { return false; } return true; } }; } // namespace gin namespace electron { namespace { bool IsFramelessWindow(NSView* view) { NSWindow* nswindow = [view window]; if (![nswindow respondsToSelector:@selector(shell)]) return false; NativeWindow* window = [static_cast<ElectronNSWindow*>(nswindow) shell]; return window && !window->has_frame(); } IMP original_set_frame_size = nullptr; IMP original_view_did_move_to_superview = nullptr; // This method is directly called by NSWindow during a window resize on OSX // 10.10.0, beta 2. We must override it to prevent the content view from // shrinking. void SetFrameSize(NSView* self, SEL _cmd, NSSize size) { if (!IsFramelessWindow(self)) { auto original = reinterpret_cast<decltype(&SetFrameSize)>(original_set_frame_size); return original(self, _cmd, size); } // For frameless window, resize the view to cover full window. if ([self superview]) size = [[self superview] bounds].size; auto super_impl = reinterpret_cast<decltype(&SetFrameSize)>( [[self superclass] instanceMethodForSelector:_cmd]); super_impl(self, _cmd, size); } // The contentView gets moved around during certain full-screen operations. // This is less than ideal, and should eventually be removed. void ViewDidMoveToSuperview(NSView* self, SEL _cmd) { if (!IsFramelessWindow(self)) { // [BridgedContentView viewDidMoveToSuperview]; auto original = reinterpret_cast<decltype(&ViewDidMoveToSuperview)>( original_view_did_move_to_superview); if (original) original(self, _cmd); return; } [self setFrame:[[self superview] bounds]]; } // -[NSWindow orderWindow] does not handle reordering for children // windows. Their order is fixed to the attachment order (the last attached // window is on the top). Therefore, work around it by re-parenting in our // desired order. void ReorderChildWindowAbove(NSWindow* child_window, NSWindow* other_window) { NSWindow* parent = [child_window parentWindow]; DCHECK(parent); // `ordered_children` sorts children windows back to front. NSArray<NSWindow*>* children = [[child_window parentWindow] childWindows]; std::vector<std::pair<NSInteger, NSWindow*>> ordered_children; for (NSWindow* child in children) ordered_children.push_back({[child orderedIndex], child}); std::sort(ordered_children.begin(), ordered_children.end(), std::greater<>()); // If `other_window` is nullptr, place `child_window` in front of // all other children windows. if (other_window == nullptr) other_window = ordered_children.back().second; if (child_window == other_window) return; for (NSWindow* child in children) [parent removeChildWindow:child]; const bool relative_to_parent = parent == other_window; if (relative_to_parent) [parent addChildWindow:child_window ordered:NSWindowAbove]; // Re-parent children windows in the desired order. for (auto [ordered_index, child] : ordered_children) { if (child != child_window && child != other_window) { [parent addChildWindow:child ordered:NSWindowAbove]; } else if (child == other_window && !relative_to_parent) { [parent addChildWindow:other_window ordered:NSWindowAbove]; [parent addChildWindow:child_window ordered:NSWindowAbove]; } } } } // namespace NativeWindowMac::NativeWindowMac(const gin_helper::Dictionary& options, NativeWindow* parent) : NativeWindow(options, parent), root_view_(new RootViewMac(this)) { ui::NativeTheme::GetInstanceForNativeUi()->AddObserver(this); display::Screen::GetScreen()->AddObserver(this); int width = 800, height = 600; options.Get(options::kWidth, &width); options.Get(options::kHeight, &height); NSRect main_screen_rect = [[[NSScreen screens] firstObject] frame]; gfx::Rect bounds(round((NSWidth(main_screen_rect) - width) / 2), round((NSHeight(main_screen_rect) - height) / 2), width, height); bool resizable = true; options.Get(options::kResizable, &resizable); options.Get(options::kZoomToPageWidth, &zoom_to_page_width_); options.Get(options::kSimpleFullScreen, &always_simple_fullscreen_); options.GetOptional(options::kTrafficLightPosition, &traffic_light_position_); options.Get(options::kVisualEffectState, &visual_effect_state_); if (options.Has(options::kFullscreenWindowTitle)) { EmitWarning( node::Environment::GetCurrent(JavascriptEnvironment::GetIsolate()), "\"fullscreenWindowTitle\" option has been deprecated and is " "no-op now.", "electron"); } bool minimizable = true; options.Get(options::kMinimizable, &minimizable); bool maximizable = true; options.Get(options::kMaximizable, &maximizable); bool closable = true; options.Get(options::kClosable, &closable); std::string tabbingIdentifier; options.Get(options::kTabbingIdentifier, &tabbingIdentifier); std::string windowType; options.Get(options::kType, &windowType); bool hiddenInMissionControl = false; options.Get(options::kHiddenInMissionControl, &hiddenInMissionControl); bool useStandardWindow = true; // eventually deprecate separate "standardWindow" option in favor of // standard / textured window types options.Get(options::kStandardWindow, &useStandardWindow); if (windowType == "textured") { useStandardWindow = false; } // The window without titlebar is treated the same with frameless window. if (title_bar_style_ != TitleBarStyle::kNormal) set_has_frame(false); NSUInteger styleMask = NSWindowStyleMaskTitled; // The NSWindowStyleMaskFullSizeContentView style removes rounded corners // for frameless window. bool rounded_corner = true; options.Get(options::kRoundedCorners, &rounded_corner); if (!rounded_corner && !has_frame()) styleMask = NSWindowStyleMaskBorderless; if (minimizable) styleMask |= NSWindowStyleMaskMiniaturizable; if (closable) styleMask |= NSWindowStyleMaskClosable; if (resizable) styleMask |= NSWindowStyleMaskResizable; if (!useStandardWindow || transparent() || !has_frame()) styleMask |= NSWindowStyleMaskTexturedBackground; // Create views::Widget and assign window_ with it. // TODO(zcbenz): Get rid of the window_ in future. 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.native_widget = new ElectronNativeWidgetMac(this, windowType, styleMask, widget()); widget()->Init(std::move(params)); SetCanResize(resizable); window_ = static_cast<ElectronNSWindow*>( widget()->GetNativeWindow().GetNativeNSWindow()); RegisterDeleteDelegateCallback(base::BindOnce( [](NativeWindowMac* window) { if (window->window_) window->window_ = nil; if (window->buttons_proxy_) window->buttons_proxy_ = nil; }, this)); [window_ setEnableLargerThanScreen:enable_larger_than_screen()]; window_delegate_ = [[ElectronNSWindowDelegate alloc] initWithShell:this]; [window_ setDelegate:window_delegate_]; // Only use native parent window for non-modal windows. if (parent && !is_modal()) { SetParentWindow(parent); } if (transparent()) { // Setting the background color to clear will also hide the shadow. [window_ setBackgroundColor:[NSColor clearColor]]; } if (windowType == "desktop") { [window_ setLevel:kCGDesktopWindowLevel - 1]; [window_ setDisableKeyOrMainWindow:YES]; [window_ setCollectionBehavior:(NSWindowCollectionBehaviorCanJoinAllSpaces | NSWindowCollectionBehaviorStationary | NSWindowCollectionBehaviorIgnoresCycle)]; } if (windowType == "panel") { [window_ setLevel:NSFloatingWindowLevel]; } bool focusable; if (options.Get(options::kFocusable, &focusable) && !focusable) [window_ setDisableKeyOrMainWindow:YES]; if (transparent() || !has_frame()) { // Don't show title bar. [window_ setTitlebarAppearsTransparent:YES]; [window_ setTitleVisibility:NSWindowTitleHidden]; // Remove non-transparent corners, see // https://github.com/electron/electron/issues/517. [window_ setOpaque:NO]; // Show window buttons if titleBarStyle is not "normal". if (title_bar_style_ == TitleBarStyle::kNormal) { InternalSetWindowButtonVisibility(false); } else { buttons_proxy_ = [[WindowButtonsProxy alloc] initWithWindow:window_]; [buttons_proxy_ setHeight:titlebar_overlay_height()]; if (traffic_light_position_) { [buttons_proxy_ setMargin:*traffic_light_position_]; } else if (title_bar_style_ == TitleBarStyle::kHiddenInset) { // For macOS >= 11, while this value does not match official macOS apps // like Safari or Notes, it matches titleBarStyle's old implementation // before Electron <= 12. [buttons_proxy_ setMargin:gfx::Point(12, 11)]; } if (title_bar_style_ == TitleBarStyle::kCustomButtonsOnHover) { [buttons_proxy_ setShowOnHover:YES]; } else { // customButtonsOnHover does not show buttons initially. InternalSetWindowButtonVisibility(true); } } } // Create a tab only if tabbing identifier is specified and window has // a native title bar. if (tabbingIdentifier.empty() || transparent() || !has_frame()) { [window_ setTabbingMode:NSWindowTabbingModeDisallowed]; } else { [window_ setTabbingIdentifier:base::SysUTF8ToNSString(tabbingIdentifier)]; } // Resize to content bounds. bool use_content_size = false; options.Get(options::kUseContentSize, &use_content_size); if (!has_frame() || use_content_size) SetContentSize(gfx::Size(width, height)); // Enable the NSView to accept first mouse event. bool acceptsFirstMouse = false; options.Get(options::kAcceptFirstMouse, &acceptsFirstMouse); [window_ setAcceptsFirstMouse:acceptsFirstMouse]; // Disable auto-hiding cursor. bool disableAutoHideCursor = false; options.Get(options::kDisableAutoHideCursor, &disableAutoHideCursor); [window_ setDisableAutoHideCursor:disableAutoHideCursor]; SetHiddenInMissionControl(hiddenInMissionControl); // Set maximizable state last to ensure zoom button does not get reset // by calls to other APIs. SetMaximizable(maximizable); // Default content view. SetContentView(new views::View()); AddContentViewLayers(); UpdateWindowOriginalFrame(); original_level_ = [window_ level]; } NativeWindowMac::~NativeWindowMac() = default; void NativeWindowMac::SetContentView(views::View* view) { views::View* root_view = GetContentsView(); if (content_view()) root_view->RemoveChildView(content_view()); set_content_view(view); root_view->AddChildView(content_view()); root_view->Layout(); } void NativeWindowMac::Close() { if (!IsClosable()) { WindowList::WindowCloseCancelled(this); return; } if (fullscreen_transition_state() != FullScreenTransitionState::kNone) { SetHasDeferredWindowClose(true); return; } // Ensure we're detached from the parent window before closing. RemoveChildFromParentWindow(); while (!child_windows_.empty()) { auto* child = child_windows_.back(); child->RemoveChildFromParentWindow(); } // If a sheet is attached to the window when we call // [window_ performClose:nil], the window won't close properly // even after the user has ended the sheet. // Ensure it's closed before calling [window_ performClose:nil]. if ([window_ attachedSheet]) [window_ endSheet:[window_ attachedSheet]]; [window_ performClose:nil]; // Closing a sheet doesn't trigger windowShouldClose, // so we need to manually call it ourselves here. if (is_modal() && parent() && IsVisible()) { NotifyWindowCloseButtonClicked(); } } void NativeWindowMac::CloseImmediately() { // Ensure we're detached from the parent window before closing. RemoveChildFromParentWindow(); while (!child_windows_.empty()) { auto* child = child_windows_.back(); child->RemoveChildFromParentWindow(); } [window_ close]; } void NativeWindowMac::Focus(bool focus) { if (!IsVisible()) return; if (focus) { [[NSApplication sharedApplication] activateIgnoringOtherApps:NO]; [window_ makeKeyAndOrderFront:nil]; } else { [window_ orderOut:nil]; [window_ orderBack:nil]; } } bool NativeWindowMac::IsFocused() { return [window_ isKeyWindow]; } void NativeWindowMac::Show() { if (is_modal() && parent()) { NSWindow* window = parent()->GetNativeWindow().GetNativeNSWindow(); if ([window_ sheetParent] == nil) [window beginSheet:window_ completionHandler:^(NSModalResponse){ }]; return; } // Reattach the window to the parent to actually show it. if (parent()) InternalSetParentWindow(parent(), true); // This method is supposed to put focus on window, however if the app does not // have focus then "makeKeyAndOrderFront" will only show the window. [NSApp activateIgnoringOtherApps:YES]; [window_ makeKeyAndOrderFront:nil]; } void NativeWindowMac::ShowInactive() { // Reattach the window to the parent to actually show it. if (parent()) InternalSetParentWindow(parent(), true); [window_ orderFrontRegardless]; } void NativeWindowMac::Hide() { // If a sheet is attached to the window when we call [window_ orderOut:nil], // the sheet won't be able to show again on the same window. // Ensure it's closed before calling [window_ orderOut:nil]. if ([window_ attachedSheet]) [window_ endSheet:[window_ attachedSheet]]; if (is_modal() && parent()) { [window_ orderOut:nil]; [parent()->GetNativeWindow().GetNativeNSWindow() endSheet:window_]; return; } DetachChildren(); // Detach the window from the parent before. if (parent()) InternalSetParentWindow(parent(), false); [window_ orderOut:nil]; } bool NativeWindowMac::IsVisible() { bool occluded = [window_ occlusionState] == NSWindowOcclusionStateVisible; return [window_ isVisible] && !occluded && !IsMinimized(); } bool NativeWindowMac::IsEnabled() { return [window_ attachedSheet] == nil; } void NativeWindowMac::SetEnabled(bool enable) { if (!enable) { NSRect frame = [window_ frame]; NSWindow* window = [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, frame.size.width, frame.size.height) styleMask:NSWindowStyleMaskTitled backing:NSBackingStoreBuffered defer:NO]; [window setAlphaValue:0.5]; [window_ beginSheet:window completionHandler:^(NSModalResponse returnCode) { NSLog(@"main window disabled"); return; }]; } else if ([window_ attachedSheet]) { [window_ endSheet:[window_ attachedSheet]]; } } void NativeWindowMac::Maximize() { const bool is_visible = [window_ isVisible]; if (IsMaximized()) { if (!is_visible) ShowInactive(); return; } // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); [window_ zoom:nil]; if (!is_visible) { ShowInactive(); NotifyWindowMaximize(); } } void NativeWindowMac::Unmaximize() { // Bail if the last user set bounds were the same size as the window // screen (e.g. the user set the window to maximized via setBounds) // // Per docs during zoom: // > If there’s no saved user state because there has been no previous // > zoom,the size and location of the window don’t change. // // However, in classic Apple fashion, this is not the case in practice, // and the frame inexplicably becomes very tiny. We should prevent // zoom from being called if the window is being unmaximized and its // unmaximized window bounds are themselves functionally maximized. if (!IsMaximized() || user_set_bounds_maximized_) return; [window_ zoom:nil]; } bool NativeWindowMac::IsMaximized() { // It's possible for [window_ isZoomed] to be true // when the window is minimized or fullscreened. if (IsMinimized() || IsFullscreen()) return false; if (HasStyleMask(NSWindowStyleMaskResizable) != 0) return [window_ isZoomed]; NSRect rectScreen = GetAspectRatio() > 0.0 ? default_frame_for_zoom() : [[NSScreen mainScreen] visibleFrame]; return NSEqualRects([window_ frame], rectScreen); } void NativeWindowMac::Minimize() { if (IsMinimized()) return; // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); [window_ miniaturize:nil]; } void NativeWindowMac::Restore() { [window_ deminiaturize:nil]; } bool NativeWindowMac::IsMinimized() { return [window_ isMiniaturized]; } bool NativeWindowMac::HandleDeferredClose() { if (has_deferred_window_close_) { SetHasDeferredWindowClose(false); Close(); return true; } return false; } void NativeWindowMac::RemoveChildWindow(NativeWindow* child) { child_windows_.remove_if([&child](NativeWindow* w) { return (w == child); }); [window_ removeChildWindow:child->GetNativeWindow().GetNativeNSWindow()]; } void NativeWindowMac::RemoveChildFromParentWindow() { if (parent() && !is_modal()) { parent()->RemoveChildWindow(this); NativeWindow::SetParentWindow(nullptr); } } void NativeWindowMac::AttachChildren() { for (auto* child : child_windows_) { auto* child_nswindow = child->GetNativeWindow().GetNativeNSWindow(); if ([child_nswindow parentWindow] == window_) continue; // Attaching a window as a child window resets its window level, so // save and restore it afterwards. NSInteger level = window_.level; [window_ addChildWindow:child_nswindow ordered:NSWindowAbove]; [window_ setLevel:level]; } } void NativeWindowMac::DetachChildren() { DCHECK(child_windows_.size() == [[window_ childWindows] count]); // Hide all children before hiding/minimizing the window. // NativeWidgetNSWindowBridge::NotifyVisibilityChangeDown() // will DCHECK otherwise. for (auto* child : child_windows_) { [child->GetNativeWindow().GetNativeNSWindow() orderOut:nil]; } } void NativeWindowMac::SetFullScreen(bool fullscreen) { if (!has_frame() && !HasStyleMask(NSWindowStyleMaskTitled)) return; // [NSWindow -toggleFullScreen] is an asynchronous operation, which means // that it's possible to call it while a fullscreen transition is currently // in process. This can create weird behavior (incl. phantom windows), // so we want to schedule a transition for when the current one has completed. if (fullscreen_transition_state() != FullScreenTransitionState::kNone) { if (!pending_transitions_.empty()) { bool last_pending = pending_transitions_.back(); // Only push new transitions if they're different than the last transition // in the queue. if (last_pending != fullscreen) pending_transitions_.push(fullscreen); } else { pending_transitions_.push(fullscreen); } return; } if (fullscreen == IsFullscreen() || !IsFullScreenable()) return; // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); // This needs to be set here because it can be the case that // SetFullScreen is called by a user before windowWillEnterFullScreen // or windowWillExitFullScreen are invoked, and so a potential transition // could be dropped. fullscreen_transition_state_ = fullscreen ? FullScreenTransitionState::kEntering : FullScreenTransitionState::kExiting; [window_ toggleFullScreenMode:nil]; } bool NativeWindowMac::IsFullscreen() const { return HasStyleMask(NSWindowStyleMaskFullScreen); } void NativeWindowMac::SetBounds(const gfx::Rect& bounds, bool animate) { // Do nothing if in fullscreen mode. if (IsFullscreen()) return; // Check size constraints since setFrame does not check it. gfx::Size size = bounds.size(); size.SetToMax(GetMinimumSize()); gfx::Size max_size = GetMaximumSize(); if (!max_size.IsEmpty()) size.SetToMin(max_size); NSRect cocoa_bounds = NSMakeRect(bounds.x(), 0, size.width(), size.height()); // Flip coordinates based on the primary screen. NSScreen* screen = [[NSScreen screens] firstObject]; cocoa_bounds.origin.y = NSHeight([screen frame]) - size.height() - bounds.y(); [window_ setFrame:cocoa_bounds display:YES animate:animate]; user_set_bounds_maximized_ = IsMaximized() ? true : false; UpdateWindowOriginalFrame(); } gfx::Rect NativeWindowMac::GetBounds() { NSRect frame = [window_ frame]; gfx::Rect bounds(frame.origin.x, 0, NSWidth(frame), NSHeight(frame)); NSScreen* screen = [[NSScreen screens] firstObject]; bounds.set_y(NSHeight([screen frame]) - NSMaxY(frame)); return bounds; } bool NativeWindowMac::IsNormal() { return NativeWindow::IsNormal() && !IsSimpleFullScreen(); } gfx::Rect NativeWindowMac::GetNormalBounds() { if (IsNormal()) { return GetBounds(); } NSRect frame = original_frame_; gfx::Rect bounds(frame.origin.x, 0, NSWidth(frame), NSHeight(frame)); NSScreen* screen = [[NSScreen screens] firstObject]; bounds.set_y(NSHeight([screen frame]) - NSMaxY(frame)); return bounds; // Works on OS_WIN ! // return widget()->GetRestoredBounds(); } void NativeWindowMac::SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints) { auto convertSize = [this](const gfx::Size& size) { // Our frameless window still has titlebar attached, so setting contentSize // will result in actual content size being larger. if (!has_frame()) { NSRect frame = NSMakeRect(0, 0, size.width(), size.height()); NSRect content = [window_ originalContentRectForFrameRect:frame]; return content.size; } else { return NSMakeSize(size.width(), size.height()); } }; NSView* content = [window_ contentView]; if (size_constraints.HasMinimumSize()) { NSSize min_size = convertSize(size_constraints.GetMinimumSize()); [window_ setContentMinSize:[content convertSize:min_size toView:nil]]; } if (size_constraints.HasMaximumSize()) { NSSize max_size = convertSize(size_constraints.GetMaximumSize()); [window_ setContentMaxSize:[content convertSize:max_size toView:nil]]; } NativeWindow::SetContentSizeConstraints(size_constraints); } bool NativeWindowMac::MoveAbove(const std::string& sourceId) { const content::DesktopMediaID id = content::DesktopMediaID::Parse(sourceId); if (id.type != content::DesktopMediaID::TYPE_WINDOW) return false; // Check if the window source is valid. const CGWindowID window_id = id.id; if (!webrtc::GetWindowOwnerPid(window_id)) return false; if (!parent()) { [window_ orderWindow:NSWindowAbove relativeTo:window_id]; } else { NSWindow* other_window = [NSApp windowWithWindowNumber:window_id]; ReorderChildWindowAbove(window_, other_window); } return true; } void NativeWindowMac::MoveTop() { if (!parent()) [window_ orderWindow:NSWindowAbove relativeTo:0]; else ReorderChildWindowAbove(window_, nullptr); } void NativeWindowMac::SetResizable(bool resizable) { ScopedDisableResize disable_resize; SetStyleMask(resizable, NSWindowStyleMaskResizable); // Right now, resizable and fullscreenable are decoupled in // documentation and on Windows/Linux. Chromium disables // fullscreenability if resizability is false on macOS as well // as disabling the maximize traffic light unless the window // is both resizable and maximizable. To work around this, we want // to match behavior on other platforms by disabiliting the maximize // button but keeping fullscreenability enabled. // TODO(codebytere): refactor this once we have a better solution. SetCanResize(resizable); if (!resizable) { SetFullScreenable(true); [[window_ standardWindowButton:NSWindowZoomButton] setEnabled:false]; } else { SetFullScreenable(true); [[window_ standardWindowButton:NSWindowZoomButton] setEnabled:IsFullScreenable()]; } } bool NativeWindowMac::IsResizable() { bool in_fs_transition = fullscreen_transition_state() != FullScreenTransitionState::kNone; bool has_rs_mask = HasStyleMask(NSWindowStyleMaskResizable); return has_rs_mask && !IsFullscreen() && !in_fs_transition; } void NativeWindowMac::SetMovable(bool movable) { [window_ setMovable:movable]; } bool NativeWindowMac::IsMovable() { return [window_ isMovable]; } void NativeWindowMac::SetMinimizable(bool minimizable) { SetStyleMask(minimizable, NSWindowStyleMaskMiniaturizable); } bool NativeWindowMac::IsMinimizable() { return HasStyleMask(NSWindowStyleMaskMiniaturizable); } void NativeWindowMac::SetMaximizable(bool maximizable) { maximizable_ = maximizable; [[window_ standardWindowButton:NSWindowZoomButton] setEnabled:maximizable]; } bool NativeWindowMac::IsMaximizable() { return [[window_ standardWindowButton:NSWindowZoomButton] isEnabled]; } void NativeWindowMac::SetFullScreenable(bool fullscreenable) { SetCollectionBehavior(fullscreenable, NSWindowCollectionBehaviorFullScreenPrimary); // On EL Capitan this flag is required to hide fullscreen button. SetCollectionBehavior(!fullscreenable, NSWindowCollectionBehaviorFullScreenAuxiliary); } bool NativeWindowMac::IsFullScreenable() { NSUInteger collectionBehavior = [window_ collectionBehavior]; return collectionBehavior & NSWindowCollectionBehaviorFullScreenPrimary; } void NativeWindowMac::SetClosable(bool closable) { SetStyleMask(closable, NSWindowStyleMaskClosable); } bool NativeWindowMac::IsClosable() { return HasStyleMask(NSWindowStyleMaskClosable); } void NativeWindowMac::SetAlwaysOnTop(ui::ZOrderLevel z_order, const std::string& level_name, int relative_level) { if (z_order == ui::ZOrderLevel::kNormal) { SetWindowLevel(NSNormalWindowLevel); return; } int level = NSNormalWindowLevel; if (level_name == "floating") { level = NSFloatingWindowLevel; } else if (level_name == "torn-off-menu") { level = NSTornOffMenuWindowLevel; } else if (level_name == "modal-panel") { level = NSModalPanelWindowLevel; } else if (level_name == "main-menu") { level = NSMainMenuWindowLevel; } else if (level_name == "status") { level = NSStatusWindowLevel; } else if (level_name == "pop-up-menu") { level = NSPopUpMenuWindowLevel; } else if (level_name == "screen-saver") { level = NSScreenSaverWindowLevel; } SetWindowLevel(level + relative_level); } std::string NativeWindowMac::GetAlwaysOnTopLevel() { std::string level_name = "normal"; int level = [window_ level]; if (level == NSFloatingWindowLevel) { level_name = "floating"; } else if (level == NSTornOffMenuWindowLevel) { level_name = "torn-off-menu"; } else if (level == NSModalPanelWindowLevel) { level_name = "modal-panel"; } else if (level == NSMainMenuWindowLevel) { level_name = "main-menu"; } else if (level == NSStatusWindowLevel) { level_name = "status"; } else if (level == NSPopUpMenuWindowLevel) { level_name = "pop-up-menu"; } else if (level == NSScreenSaverWindowLevel) { level_name = "screen-saver"; } return level_name; } void NativeWindowMac::SetWindowLevel(int unbounded_level) { int level = std::min( std::max(unbounded_level, CGWindowLevelForKey(kCGMinimumWindowLevelKey)), CGWindowLevelForKey(kCGMaximumWindowLevelKey)); ui::ZOrderLevel z_order_level = level == NSNormalWindowLevel ? ui::ZOrderLevel::kNormal : ui::ZOrderLevel::kFloatingWindow; bool did_z_order_level_change = z_order_level != GetZOrderLevel(); was_maximizable_ = IsMaximizable(); // We need to explicitly keep the NativeWidget up to date, since it stores the // window level in a local variable, rather than reading it from the NSWindow. // Unfortunately, it results in a second setLevel call. It's not ideal, but we // don't expect this to cause any user-visible jank. widget()->SetZOrderLevel(z_order_level); [window_ setLevel:level]; // Set level will make the zoom button revert to default, probably // a bug of Cocoa or macOS. SetMaximizable(was_maximizable_); // This must be notified at the very end or IsAlwaysOnTop // will not yet have been updated to reflect the new status if (did_z_order_level_change) NativeWindow::NotifyWindowAlwaysOnTopChanged(); } ui::ZOrderLevel NativeWindowMac::GetZOrderLevel() { return widget()->GetZOrderLevel(); } void NativeWindowMac::Center() { [window_ center]; } void NativeWindowMac::Invalidate() { [[window_ contentView] setNeedsDisplay:YES]; } void NativeWindowMac::SetTitle(const std::string& title) { [window_ setTitle:base::SysUTF8ToNSString(title)]; if (buttons_proxy_) [buttons_proxy_ redraw]; } std::string NativeWindowMac::GetTitle() { return base::SysNSStringToUTF8([window_ title]); } void NativeWindowMac::FlashFrame(bool flash) { if (flash) { attention_request_id_ = [NSApp requestUserAttention:NSInformationalRequest]; } else { [NSApp cancelUserAttentionRequest:attention_request_id_]; attention_request_id_ = 0; } } void NativeWindowMac::SetSkipTaskbar(bool skip) {} bool NativeWindowMac::IsExcludedFromShownWindowsMenu() { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); return [window isExcludedFromWindowsMenu]; } void NativeWindowMac::SetExcludedFromShownWindowsMenu(bool excluded) { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); [window setExcludedFromWindowsMenu:excluded]; } void NativeWindowMac::OnDisplayMetricsChanged(const display::Display& display, uint32_t changed_metrics) { // We only want to force screen recalibration if we're in simpleFullscreen // mode. if (!is_simple_fullscreen_) return; content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&NativeWindow::UpdateFrame, GetWeakPtr())); } void NativeWindowMac::SetSimpleFullScreen(bool simple_fullscreen) { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); if (simple_fullscreen && !is_simple_fullscreen_) { is_simple_fullscreen_ = true; // Take note of the current window size and level if (IsNormal()) { UpdateWindowOriginalFrame(); original_level_ = [window_ level]; } simple_fullscreen_options_ = [NSApp currentSystemPresentationOptions]; simple_fullscreen_mask_ = [window styleMask]; // We can simulate the pre-Lion fullscreen by auto-hiding the dock and menu // bar NSApplicationPresentationOptions options = NSApplicationPresentationAutoHideDock | NSApplicationPresentationAutoHideMenuBar; [NSApp setPresentationOptions:options]; was_maximizable_ = IsMaximizable(); was_movable_ = IsMovable(); NSRect fullscreenFrame = [window.screen frame]; // If our app has dock hidden, set the window level higher so another app's // menu bar doesn't appear on top of our fullscreen app. if ([[NSRunningApplication currentApplication] activationPolicy] != NSApplicationActivationPolicyRegular) { window.level = NSPopUpMenuWindowLevel; } // Always hide the titlebar in simple fullscreen mode. // // Note that we must remove the NSWindowStyleMaskTitled style instead of // using the [window_ setTitleVisibility:], as the latter would leave the // window with rounded corners. SetStyleMask(false, NSWindowStyleMaskTitled); if (!window_button_visibility_.has_value()) { // Lets keep previous behaviour - hide window controls in titled // fullscreen mode when not specified otherwise. InternalSetWindowButtonVisibility(false); } [window setFrame:fullscreenFrame display:YES animate:YES]; // Fullscreen windows can't be resized, minimized, maximized, or moved SetMinimizable(false); SetResizable(false); SetMaximizable(false); SetMovable(false); } else if (!simple_fullscreen && is_simple_fullscreen_) { is_simple_fullscreen_ = false; [window setFrame:original_frame_ display:YES animate:YES]; window.level = original_level_; [NSApp setPresentationOptions:simple_fullscreen_options_]; // Restore original style mask ScopedDisableResize disable_resize; [window_ setStyleMask:simple_fullscreen_mask_]; // Restore window manipulation abilities SetMaximizable(was_maximizable_); SetMovable(was_movable_); // Restore default window controls visibility state. if (!window_button_visibility_.has_value()) { bool visibility; if (has_frame()) visibility = true; else visibility = title_bar_style_ != TitleBarStyle::kNormal; InternalSetWindowButtonVisibility(visibility); } if (buttons_proxy_) [buttons_proxy_ redraw]; } } bool NativeWindowMac::IsSimpleFullScreen() { return is_simple_fullscreen_; } void NativeWindowMac::SetKiosk(bool kiosk) { if (kiosk && !is_kiosk_) { kiosk_options_ = [NSApp currentSystemPresentationOptions]; NSApplicationPresentationOptions options = NSApplicationPresentationHideDock | NSApplicationPresentationHideMenuBar | NSApplicationPresentationDisableAppleMenu | NSApplicationPresentationDisableProcessSwitching | NSApplicationPresentationDisableForceQuit | NSApplicationPresentationDisableSessionTermination | NSApplicationPresentationDisableHideApplication; [NSApp setPresentationOptions:options]; is_kiosk_ = true; fullscreen_before_kiosk_ = IsFullscreen(); if (!fullscreen_before_kiosk_) SetFullScreen(true); } else if (!kiosk && is_kiosk_) { is_kiosk_ = false; if (!fullscreen_before_kiosk_) SetFullScreen(false); // Set presentation options *after* asynchronously exiting // fullscreen to ensure they take effect. [NSApp setPresentationOptions:kiosk_options_]; } } bool NativeWindowMac::IsKiosk() { return is_kiosk_; } void NativeWindowMac::SetBackgroundColor(SkColor color) { base::ScopedCFTypeRef<CGColorRef> cgcolor( skia::CGColorCreateFromSkColor(color)); [[[window_ contentView] layer] setBackgroundColor:cgcolor]; } SkColor NativeWindowMac::GetBackgroundColor() { CGColorRef color = [[[window_ contentView] layer] backgroundColor]; if (!color) return SK_ColorTRANSPARENT; return skia::CGColorRefToSkColor(color); } void NativeWindowMac::SetHasShadow(bool has_shadow) { [window_ setHasShadow:has_shadow]; } bool NativeWindowMac::HasShadow() { return [window_ hasShadow]; } void NativeWindowMac::InvalidateShadow() { [window_ invalidateShadow]; } void NativeWindowMac::SetOpacity(const double opacity) { const double boundedOpacity = std::clamp(opacity, 0.0, 1.0); [window_ setAlphaValue:boundedOpacity]; } double NativeWindowMac::GetOpacity() { return [window_ alphaValue]; } void NativeWindowMac::SetRepresentedFilename(const std::string& filename) { [window_ setRepresentedFilename:base::SysUTF8ToNSString(filename)]; if (buttons_proxy_) [buttons_proxy_ redraw]; } std::string NativeWindowMac::GetRepresentedFilename() { return base::SysNSStringToUTF8([window_ representedFilename]); } void NativeWindowMac::SetDocumentEdited(bool edited) { [window_ setDocumentEdited:edited]; if (buttons_proxy_) [buttons_proxy_ redraw]; } bool NativeWindowMac::IsDocumentEdited() { return [window_ isDocumentEdited]; } bool NativeWindowMac::IsHiddenInMissionControl() { NSUInteger collectionBehavior = [window_ collectionBehavior]; return collectionBehavior & NSWindowCollectionBehaviorTransient; } void NativeWindowMac::SetHiddenInMissionControl(bool hidden) { SetCollectionBehavior(hidden, NSWindowCollectionBehaviorTransient); } void NativeWindowMac::SetIgnoreMouseEvents(bool ignore, bool forward) { [window_ setIgnoresMouseEvents:ignore]; if (!ignore) { SetForwardMouseMessages(NO); } else { SetForwardMouseMessages(forward); } } void NativeWindowMac::SetContentProtection(bool enable) { [window_ setSharingType:enable ? NSWindowSharingNone : NSWindowSharingReadOnly]; } void NativeWindowMac::SetFocusable(bool focusable) { // No known way to unfocus the window if it had the focus. Here we do not // want to call Focus(false) because it moves the window to the back, i.e. // at the bottom in term of z-order. [window_ setDisableKeyOrMainWindow:!focusable]; } bool NativeWindowMac::IsFocusable() { return ![window_ disableKeyOrMainWindow]; } void NativeWindowMac::AddBrowserView(NativeBrowserView* view) { [CATransaction begin]; [CATransaction setDisableActions:YES]; if (!view) { [CATransaction commit]; return; } add_browser_view(view); if (view->GetInspectableWebContentsView()) { auto* native_view = view->GetInspectableWebContentsView() ->GetNativeView() .GetNativeNSView(); [[window_ contentView] addSubview:native_view positioned:NSWindowAbove relativeTo:nil]; native_view.hidden = NO; } [CATransaction commit]; } void NativeWindowMac::RemoveBrowserView(NativeBrowserView* view) { [CATransaction begin]; [CATransaction setDisableActions:YES]; if (!view) { [CATransaction commit]; return; } if (view->GetInspectableWebContentsView()) [view->GetInspectableWebContentsView()->GetNativeView().GetNativeNSView() removeFromSuperview]; remove_browser_view(view); [CATransaction commit]; } void NativeWindowMac::SetTopBrowserView(NativeBrowserView* view) { [CATransaction begin]; [CATransaction setDisableActions:YES]; if (!view) { [CATransaction commit]; return; } remove_browser_view(view); add_browser_view(view); if (view->GetInspectableWebContentsView()) { auto* native_view = view->GetInspectableWebContentsView() ->GetNativeView() .GetNativeNSView(); [[window_ contentView] addSubview:native_view positioned:NSWindowAbove relativeTo:nil]; native_view.hidden = NO; } [CATransaction commit]; } void NativeWindowMac::SetParentWindow(NativeWindow* parent) { InternalSetParentWindow(parent, IsVisible()); } gfx::NativeView NativeWindowMac::GetNativeView() const { return [window_ contentView]; } gfx::NativeWindow NativeWindowMac::GetNativeWindow() const { return window_; } gfx::AcceleratedWidget NativeWindowMac::GetAcceleratedWidget() const { return [window_ windowNumber]; } content::DesktopMediaID NativeWindowMac::GetDesktopMediaID() const { auto desktop_media_id = content::DesktopMediaID( content::DesktopMediaID::TYPE_WINDOW, GetAcceleratedWidget()); // c.f. // https://source.chromium.org/chromium/chromium/src/+/main:chrome/browser/media/webrtc/native_desktop_media_list.cc;l=775-780;drc=79502ab47f61bff351426f57f576daef02b1a8dc // Refs https://github.com/electron/electron/pull/30507 // TODO(deepak1556): Match upstream for `kWindowCaptureMacV2` #if 0 if (remote_cocoa::ScopedCGWindowID::Get(desktop_media_id.id)) { desktop_media_id.window_id = desktop_media_id.id; } #endif return desktop_media_id; } NativeWindowHandle NativeWindowMac::GetNativeWindowHandle() const { return [window_ contentView]; } void NativeWindowMac::SetProgressBar(double progress, const NativeWindow::ProgressState state) { NSDockTile* dock_tile = [NSApp dockTile]; // Sometimes macOS would install a default contentView for dock, we must // verify whether NSProgressIndicator has been installed. bool first_time = !dock_tile.contentView || [[dock_tile.contentView subviews] count] == 0 || ![[[dock_tile.contentView subviews] lastObject] isKindOfClass:[NSProgressIndicator class]]; // For the first time API invoked, we need to create a ContentView in // DockTile. if (first_time) { NSImageView* image_view = [[NSImageView alloc] init]; [image_view setImage:[NSApp applicationIconImage]]; [dock_tile setContentView:image_view]; NSRect frame = NSMakeRect(0.0f, 0.0f, dock_tile.size.width, 15.0); NSProgressIndicator* progress_indicator = [[ElectronProgressBar alloc] initWithFrame:frame]; [progress_indicator setStyle:NSProgressIndicatorStyleBar]; [progress_indicator setIndeterminate:NO]; [progress_indicator setBezeled:YES]; [progress_indicator setMinValue:0]; [progress_indicator setMaxValue:1]; [progress_indicator setHidden:NO]; [dock_tile.contentView addSubview:progress_indicator]; } NSProgressIndicator* progress_indicator = static_cast<NSProgressIndicator*>( [[[dock_tile contentView] subviews] lastObject]); if (progress < 0) { [progress_indicator setHidden:YES]; } else if (progress > 1) { [progress_indicator setHidden:NO]; [progress_indicator setIndeterminate:YES]; [progress_indicator setDoubleValue:1]; } else { [progress_indicator setHidden:NO]; [progress_indicator setDoubleValue:progress]; } [dock_tile display]; } void NativeWindowMac::SetOverlayIcon(const gfx::Image& overlay, const std::string& description) {} void NativeWindowMac::SetVisibleOnAllWorkspaces(bool visible, bool visibleOnFullScreen, bool skipTransformProcessType) { // In order for NSWindows to be visible on fullscreen we need to invoke // app.dock.hide() since Apple changed the underlying functionality of // NSWindows starting with 10.14 to disallow NSWindows from floating on top of // fullscreen apps. if (!skipTransformProcessType) { if (visibleOnFullScreen) { Browser::Get()->DockHide(); } else { Browser::Get()->DockShow(JavascriptEnvironment::GetIsolate()); } } SetCollectionBehavior(visible, NSWindowCollectionBehaviorCanJoinAllSpaces); SetCollectionBehavior(visibleOnFullScreen, NSWindowCollectionBehaviorFullScreenAuxiliary); } bool NativeWindowMac::IsVisibleOnAllWorkspaces() { NSUInteger collectionBehavior = [window_ collectionBehavior]; return collectionBehavior & NSWindowCollectionBehaviorCanJoinAllSpaces; } void NativeWindowMac::SetAutoHideCursor(bool auto_hide) { [window_ setDisableAutoHideCursor:!auto_hide]; } void NativeWindowMac::UpdateVibrancyRadii(bool fullscreen) { NSVisualEffectView* vibrantView = [window_ vibrantView]; if (vibrantView != nil && !vibrancy_type_.empty()) { const bool no_rounded_corner = !HasStyleMask(NSWindowStyleMaskTitled); if (!has_frame() && !is_modal() && !no_rounded_corner) { CGFloat radius; if (fullscreen) { radius = 0.0f; } else if (@available(macOS 11.0, *)) { radius = 9.0f; } else { // Smaller corner radius on versions prior to Big Sur. radius = 5.0f; } CGFloat dimension = 2 * radius + 1; NSSize size = NSMakeSize(dimension, dimension); NSImage* maskImage = [NSImage imageWithSize:size flipped:NO drawingHandler:^BOOL(NSRect rect) { NSBezierPath* bezierPath = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [[NSColor blackColor] set]; [bezierPath fill]; return YES; }]; [maskImage setCapInsets:NSEdgeInsetsMake(radius, radius, radius, radius)]; [maskImage setResizingMode:NSImageResizingModeStretch]; [vibrantView setMaskImage:maskImage]; [window_ setCornerMask:maskImage]; } } } void NativeWindowMac::UpdateWindowOriginalFrame() { original_frame_ = [window_ frame]; } void NativeWindowMac::SetVibrancy(const std::string& type) { NSVisualEffectView* vibrantView = [window_ vibrantView]; if (type.empty()) { if (vibrantView == nil) return; [vibrantView removeFromSuperview]; [window_ setVibrantView:nil]; return; } NSVisualEffectMaterial vibrancyType{}; if (type == "titlebar") { vibrancyType = NSVisualEffectMaterialTitlebar; } else if (type == "selection") { vibrancyType = NSVisualEffectMaterialSelection; } else if (type == "menu") { vibrancyType = NSVisualEffectMaterialMenu; } else if (type == "popover") { vibrancyType = NSVisualEffectMaterialPopover; } else if (type == "sidebar") { vibrancyType = NSVisualEffectMaterialSidebar; } else if (type == "header") { vibrancyType = NSVisualEffectMaterialHeaderView; } else if (type == "sheet") { vibrancyType = NSVisualEffectMaterialSheet; } else if (type == "window") { vibrancyType = NSVisualEffectMaterialWindowBackground; } else if (type == "hud") { vibrancyType = NSVisualEffectMaterialHUDWindow; } else if (type == "fullscreen-ui") { vibrancyType = NSVisualEffectMaterialFullScreenUI; } else if (type == "tooltip") { vibrancyType = NSVisualEffectMaterialToolTip; } else if (type == "content") { vibrancyType = NSVisualEffectMaterialContentBackground; } else if (type == "under-window") { vibrancyType = NSVisualEffectMaterialUnderWindowBackground; } else if (type == "under-page") { vibrancyType = NSVisualEffectMaterialUnderPageBackground; } if (vibrancyType) { vibrancy_type_ = type; if (vibrantView == nil) { vibrantView = [[NSVisualEffectView alloc] initWithFrame:[[window_ contentView] bounds]]; [window_ setVibrantView:vibrantView]; [vibrantView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable]; [vibrantView setBlendingMode:NSVisualEffectBlendingModeBehindWindow]; if (visual_effect_state_ == VisualEffectState::kActive) { [vibrantView setState:NSVisualEffectStateActive]; } else if (visual_effect_state_ == VisualEffectState::kInactive) { [vibrantView setState:NSVisualEffectStateInactive]; } else { [vibrantView setState:NSVisualEffectStateFollowsWindowActiveState]; } [[window_ contentView] addSubview:vibrantView positioned:NSWindowBelow relativeTo:nil]; UpdateVibrancyRadii(IsFullscreen()); } [vibrantView setMaterial:vibrancyType]; } } void NativeWindowMac::SetWindowButtonVisibility(bool visible) { window_button_visibility_ = visible; if (buttons_proxy_) { if (visible) [buttons_proxy_ redraw]; [buttons_proxy_ setVisible:visible]; } if (title_bar_style_ != TitleBarStyle::kCustomButtonsOnHover) InternalSetWindowButtonVisibility(visible); NotifyLayoutWindowControlsOverlay(); } bool NativeWindowMac::GetWindowButtonVisibility() const { return ![window_ standardWindowButton:NSWindowZoomButton].hidden || ![window_ standardWindowButton:NSWindowMiniaturizeButton].hidden || ![window_ standardWindowButton:NSWindowCloseButton].hidden; } void NativeWindowMac::SetWindowButtonPosition( absl::optional<gfx::Point> position) { traffic_light_position_ = std::move(position); if (buttons_proxy_) { [buttons_proxy_ setMargin:traffic_light_position_]; NotifyLayoutWindowControlsOverlay(); } } absl::optional<gfx::Point> NativeWindowMac::GetWindowButtonPosition() const { return traffic_light_position_; } void NativeWindowMac::RedrawTrafficLights() { if (buttons_proxy_ && !IsFullscreen()) [buttons_proxy_ redraw]; } // In simpleFullScreen mode, update the frame for new bounds. void NativeWindowMac::UpdateFrame() { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); NSRect fullscreenFrame = [window.screen frame]; [window setFrame:fullscreenFrame display:YES animate:YES]; } void NativeWindowMac::SetTouchBar( std::vector<gin_helper::PersistentDictionary> items) { touch_bar_ = [[ElectronTouchBar alloc] initWithDelegate:window_delegate_ window:this settings:std::move(items)]; [window_ setTouchBar:nil]; } void NativeWindowMac::RefreshTouchBarItem(const std::string& item_id) { if (touch_bar_ && [window_ touchBar]) [touch_bar_ refreshTouchBarItem:[window_ touchBar] id:item_id]; } void NativeWindowMac::SetEscapeTouchBarItem( gin_helper::PersistentDictionary item) { if (touch_bar_ && [window_ touchBar]) [touch_bar_ setEscapeTouchBarItem:std::move(item) forTouchBar:[window_ touchBar]]; } void NativeWindowMac::SelectPreviousTab() { [window_ selectPreviousTab:nil]; } void NativeWindowMac::SelectNextTab() { [window_ selectNextTab:nil]; } void NativeWindowMac::ShowAllTabs() { [window_ toggleTabOverview:nil]; } void NativeWindowMac::MergeAllWindows() { [window_ mergeAllWindows:nil]; } void NativeWindowMac::MoveTabToNewWindow() { [window_ moveTabToNewWindow:nil]; } void NativeWindowMac::ToggleTabBar() { [window_ toggleTabBar:nil]; } bool NativeWindowMac::AddTabbedWindow(NativeWindow* window) { if (window_ == window->GetNativeWindow().GetNativeNSWindow()) { return false; } else { [window_ addTabbedWindow:window->GetNativeWindow().GetNativeNSWindow() ordered:NSWindowAbove]; } return true; } void NativeWindowMac::SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) { NativeWindow::SetAspectRatio(aspect_ratio, extra_size); // Reset the behaviour to default if aspect_ratio is set to 0 or less. if (aspect_ratio > 0.0) { NSSize aspect_ratio_size = NSMakeSize(aspect_ratio, 1.0); if (has_frame()) [window_ setContentAspectRatio:aspect_ratio_size]; else [window_ setAspectRatio:aspect_ratio_size]; } else { [window_ setResizeIncrements:NSMakeSize(1.0, 1.0)]; } } void NativeWindowMac::PreviewFile(const std::string& path, const std::string& display_name) { preview_item_ = [[ElectronPreviewItem alloc] initWithURL:[NSURL fileURLWithPath:base::SysUTF8ToNSString(path)] title:base::SysUTF8ToNSString(display_name)]; [[QLPreviewPanel sharedPreviewPanel] makeKeyAndOrderFront:nil]; } void NativeWindowMac::CloseFilePreview() { if ([QLPreviewPanel sharedPreviewPanelExists]) { [[QLPreviewPanel sharedPreviewPanel] close]; } } gfx::Rect NativeWindowMac::ContentBoundsToWindowBounds( const gfx::Rect& bounds) const { if (has_frame()) { gfx::Rect window_bounds( [window_ frameRectForContentRect:bounds.ToCGRect()]); int frame_height = window_bounds.height() - bounds.height(); window_bounds.set_y(window_bounds.y() - frame_height); return window_bounds; } else { return bounds; } } gfx::Rect NativeWindowMac::WindowBoundsToContentBounds( const gfx::Rect& bounds) const { if (has_frame()) { gfx::Rect content_bounds( [window_ contentRectForFrameRect:bounds.ToCGRect()]); int frame_height = bounds.height() - content_bounds.height(); content_bounds.set_y(content_bounds.y() + frame_height); return content_bounds; } else { return bounds; } } void NativeWindowMac::NotifyWindowEnterFullScreen() { NativeWindow::NotifyWindowEnterFullScreen(); // Restore the window title under fullscreen mode. if (buttons_proxy_) [window_ setTitleVisibility:NSWindowTitleVisible]; } void NativeWindowMac::NotifyWindowLeaveFullScreen() { NativeWindow::NotifyWindowLeaveFullScreen(); // Restore window buttons. if (buttons_proxy_ && window_button_visibility_.value_or(true)) { [buttons_proxy_ redraw]; [buttons_proxy_ setVisible:YES]; } } void NativeWindowMac::NotifyWindowWillEnterFullScreen() { UpdateVibrancyRadii(true); } void NativeWindowMac::NotifyWindowWillLeaveFullScreen() { if (buttons_proxy_) { // Hide window title when leaving fullscreen. [window_ setTitleVisibility:NSWindowTitleHidden]; // Hide the container otherwise traffic light buttons jump. [buttons_proxy_ setVisible:NO]; } UpdateVibrancyRadii(false); } void NativeWindowMac::SetActive(bool is_key) { is_active_ = is_key; } bool NativeWindowMac::IsActive() const { return is_active_; } void NativeWindowMac::Cleanup() { DCHECK(!IsClosed()); ui::NativeTheme::GetInstanceForNativeUi()->RemoveObserver(this); display::Screen::GetScreen()->RemoveObserver(this); } class NativeAppWindowFrameViewMac : public views::NativeFrameViewMac { public: NativeAppWindowFrameViewMac(views::Widget* frame, NativeWindowMac* window) : views::NativeFrameViewMac(frame), native_window_(window) {} NativeAppWindowFrameViewMac(const NativeAppWindowFrameViewMac&) = delete; NativeAppWindowFrameViewMac& operator=(const NativeAppWindowFrameViewMac&) = delete; ~NativeAppWindowFrameViewMac() override = default; // NonClientFrameView: int NonClientHitTest(const gfx::Point& point) override { if (!bounds().Contains(point)) return HTNOWHERE; if (GetWidget()->IsFullscreen()) return HTCLIENT; // Check for possible draggable region in the client area for the frameless // window. int contents_hit_test = native_window_->NonClientHitTest(point); if (contents_hit_test != HTNOWHERE) return contents_hit_test; return HTCLIENT; } private: // Weak. raw_ptr<NativeWindowMac> const native_window_; }; std::unique_ptr<views::NonClientFrameView> NativeWindowMac::CreateNonClientFrameView(views::Widget* widget) { return std::make_unique<NativeAppWindowFrameViewMac>(widget, this); } bool NativeWindowMac::HasStyleMask(NSUInteger flag) const { return [window_ styleMask] & flag; } void NativeWindowMac::SetStyleMask(bool on, NSUInteger flag) { // Changing the styleMask of a frameless windows causes it to change size so // we explicitly disable resizing while setting it. ScopedDisableResize disable_resize; if (on) [window_ setStyleMask:[window_ styleMask] | flag]; else [window_ setStyleMask:[window_ styleMask] & (~flag)]; // Change style mask will make the zoom button revert to default, probably // a bug of Cocoa or macOS. SetMaximizable(maximizable_); } void NativeWindowMac::SetCollectionBehavior(bool on, NSUInteger flag) { if (on) [window_ setCollectionBehavior:[window_ collectionBehavior] | flag]; else [window_ setCollectionBehavior:[window_ collectionBehavior] & (~flag)]; // Change collectionBehavior will make the zoom button revert to default, // probably a bug of Cocoa or macOS. SetMaximizable(maximizable_); } views::View* NativeWindowMac::GetContentsView() { return root_view_.get(); } bool NativeWindowMac::CanMaximize() const { return maximizable_; } void NativeWindowMac::OnNativeThemeUpdated(ui::NativeTheme* observed_theme) { content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&NativeWindow::RedrawTrafficLights, GetWeakPtr())); } void NativeWindowMac::AddContentViewLayers() { // Make sure the bottom corner is rounded for non-modal windows: // http://crbug.com/396264. if (!is_modal()) { // For normal window, we need to explicitly set layer for contentView to // make setBackgroundColor work correctly. // There is no need to do so for frameless window, and doing so would make // titleBarStyle stop working. if (has_frame()) { CALayer* background_layer = [[CALayer alloc] init]; [background_layer setAutoresizingMask:kCALayerWidthSizable | kCALayerHeightSizable]; [[window_ contentView] setLayer:background_layer]; } [[window_ contentView] setWantsLayer:YES]; } } void NativeWindowMac::InternalSetWindowButtonVisibility(bool visible) { [[window_ standardWindowButton:NSWindowCloseButton] setHidden:!visible]; [[window_ standardWindowButton:NSWindowMiniaturizeButton] setHidden:!visible]; [[window_ standardWindowButton:NSWindowZoomButton] setHidden:!visible]; } void NativeWindowMac::InternalSetParentWindow(NativeWindow* new_parent, bool attach) { if (is_modal()) return; // Do not remove/add if we are already properly attached. if (attach && new_parent && [window_ parentWindow] == new_parent->GetNativeWindow().GetNativeNSWindow()) return; // Remove current parent window. RemoveChildFromParentWindow(); // Set new parent window. if (new_parent) { new_parent->add_child_window(this); if (attach) new_parent->AttachChildren(); } NativeWindow::SetParentWindow(new_parent); } void NativeWindowMac::SetForwardMouseMessages(bool forward) { [window_ setAcceptsMouseMovedEvents:forward]; } gfx::Rect NativeWindowMac::GetWindowControlsOverlayRect() { if (titlebar_overlay_ && buttons_proxy_ && window_button_visibility_.value_or(true)) { NSRect buttons = [buttons_proxy_ getButtonsContainerBounds]; gfx::Rect overlay; overlay.set_width(GetContentSize().width() - NSWidth(buttons)); if ([buttons_proxy_ useCustomHeight]) { overlay.set_height(titlebar_overlay_height()); } else { overlay.set_height(NSHeight(buttons)); } if (!base::i18n::IsRTL()) overlay.set_x(NSMaxX(buttons)); return overlay; } return gfx::Rect(); } // static NativeWindow* NativeWindow::Create(const gin_helper::Dictionary& options, NativeWindow* parent) { return new NativeWindowMac(options, parent); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
39,413
[Bug]: App crashes with SIGTRAP while creating modal window on Mac
### 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 25.4.0 ### What operating system are you using? macOS ### Operating System Version 12.3 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version 25.1.1 ### Expected Behavior Not to crash:) ### Actual Behavior When I create new windows as modal to parent, I get crash with SIGTRAP Unfortunately, I couldn't reproduce this in small test project. Only fact I have, if I don't set new window as modal, app not crashes. ### Testcase Gist URL _No response_ ### Additional Information I can provide you part of stack trace and minidump <img width="872" alt="image" src="https://github.com/electron/electron/assets/25509934/ccfbba1b-13cd-4fee-a04c-1deff56d2dc3"> [2988dcae-9326-4b22-84d3-c0123f13e17f.dmp.zip](https://github.com/electron/electron/files/12292673/2988dcae-9326-4b22-84d3-c0123f13e17f.dmp.zip) There is very strange call for `ElectronPermissionMessageProvider::IsPrivilegeIncrease`. It seems like it never should be called. I also think it was affected here https://github.com/electron/electron/issues/38939
https://github.com/electron/electron/issues/39413
https://github.com/electron/electron/pull/39499
f7a7085019bf757700df3c2f8714e0de356203cd
1eb398b328d304f227deef0e89ca0be7b9e20755
2023-08-08T14:52:19Z
c++
2023-08-16T11:28:29Z
spec/api-browser-window-spec.ts
import { expect } from 'chai'; import * as childProcess from 'node:child_process'; import * as path from 'node:path'; import * as fs from 'node:fs'; import * as qs from 'node:querystring'; import * as http from 'node:http'; import * as os from 'node:os'; import { AddressInfo } from 'node:net'; import { app, BrowserWindow, BrowserView, dialog, ipcMain, OnBeforeSendHeadersListenerDetails, protocol, screen, webContents, webFrameMain, session, WebContents, WebFrameMain } from 'electron/main'; import { emittedUntil, emittedNTimes } from './lib/events-helpers'; import { ifit, ifdescribe, defer, listen } from './lib/spec-helpers'; import { closeWindow, closeAllWindows } from './lib/window-helpers'; import { areColorsSimilar, captureScreen, HexColors, getPixelColor } from './lib/screen-helpers'; import { once } from 'node:events'; import { setTimeout } from 'node:timers/promises'; const fixtures = path.resolve(__dirname, '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', () => { it('sets the correct class name on the prototype', () => { expect(BrowserWindow.prototype.constructor.name).to.equal('BrowserWindow'); }); 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(fixtures, 'apps', 'xwindow-icon'); const appProcess = childProcess.spawn(process.execPath, [appPath]); await once(appProcess, 'exit'); }); 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. const wr = new WeakRef(w); await setTimeout(); // 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 setTimeout(); expect(wr.deref()).to.not.be.undefined(); }); }); describe('BrowserWindow.close()', () => { let w: 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 = once(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 = once(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 allow access to id after destruction', async () => { const closed = once(w, 'closed'); w.destroy(); await closed; expect(w.id).to.be.a('number'); }); it('should emit unload handler', async () => { await w.loadFile(path.join(fixtures, 'api', 'unload.html')); const closed = once(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 once(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 = once(w, 'closed'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' }); w.close(); await closed; }); describe('when invoked synchronously inside navigation observer', () => { let server: http.Server; let url: string; before(async () => { 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}`); } }); url = (await listen(server)).url; }); 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 = once(w.webContents, 'destroyed'); w.webContents.loadURL(url + path); await destroyed; }); } }); }); describe('window.close()', () => { let w: 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 once(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 once(w.webContents, 'before-unload-fired'); }); }); describe('BrowserWindow.destroy()', () => { let w: 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: 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: http.Server; let url: string; let postData = null as any; before(async () => { 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(req.url && req.url.includes('slow') ? 200 : 0).then(respond); }); url = (await listen(server)).url; }); after(() => { server.close(); }); it('should emit did-start-loading event', async () => { const didStartLoading = once(w.webContents, 'did-start-loading'); w.loadURL('about:blank'); await didStartLoading; }); it('should emit ready-to-show event', async () => { const readyToShow = once(w, 'ready-to-show'); w.loadURL('about:blank'); await readyToShow; }); // DISABLED-FIXME(deepak1556): The error code now seems to be `ERR_FAILED`, verify what // changed and adjust the test. it('should emit did-fail-load event for files that do not exist', async () => { const didFailLoad = once(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 = once(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 not emit did-fail-load for a successfully loaded media file', async () => { w.webContents.on('did-fail-load', () => { expect.fail('did-fail-load should not emit on media file loads'); }); const mediaStarted = once(w.webContents, 'media-started-playing'); w.loadFile(path.join(fixtures, 'cat-spin.mp4')); await mediaStarted; }); it('should set `mainFrame = false` on did-fail-load events in iframes', async () => { const didFailLoad = once(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 = once(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: 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: http.Server; let url: string; before(async () => { server = http.createServer((req, res) => { if (req.url === '/navigate-top') { res.end('<a target=_top href="/">navigate _top</a>'); } else { res.end(''); } }); url = (await listen(server)).url; }); after(() => { server.close(); }); it('allows the window to be closed from the event listener', async () => { const event = once(w.webContents, 'will-navigate'); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); await event; w.close(); }); 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 () => { w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-top"></iframe>`); await emittedUntil(w.webContents, 'did-frame-finish-load', (e: any, isMainFrame: boolean) => !isMainFrame); let initiator: WebFrameMain | undefined; w.webContents.on('will-navigate', (e) => { initiator = e.initiator; }); const subframe = w.webContents.mainFrame.frames[0]; subframe.executeJavaScript('document.getElementsByTagName("a")[0].click()', true); await once(w.webContents, 'did-navigate'); expect(initiator).not.to.be.undefined(); expect(initiator).to.equal(subframe); }); }); describe('will-frame-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 if (req.url === '/navigate-iframe') { res.end('<a href="/test">navigate iframe</a>'); } else if (req.url === '/navigate-iframe?navigated') { res.end('Successfully navigated'); } else if (req.url === '/navigate-iframe-immediately') { res.end(` <script type="text/javascript" charset="utf-8"> location.href += '?navigated' </script> `); } else if (req.url === '/navigate-iframe-immediately?navigated') { res.end('Successfully navigated'); } 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-frame-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-frame-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('can be prevented when navigating subframe', (done) => { let willNavigate = false; w.webContents.on('did-frame-navigate', (_event, _url, _httpResponseCode, _httpStatusText, isMainFrame, frameProcessId, frameRoutingId) => { if (isMainFrame) return; w.webContents.once('will-frame-navigate', (e) => { willNavigate = true; e.preventDefault(); }); w.webContents.on('did-stop-loading', () => { const frame = webFrameMain.fromId(frameProcessId, frameRoutingId); expect(frame).to.not.be.undefined(); if (willNavigate) { // i.e. it shouldn't have had '?navigated' appended to it. try { expect(frame!.url.endsWith('/navigate-iframe-immediately')).to.be.true(); done(); } catch (e) { done(e); } } }); }); w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-iframe-immediately"></iframe>`); }); 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-frame-navigate', (e) => { e.preventDefault(); resolve(e.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-frame-navigate', (e) => { e.preventDefault(); resolve(e.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 setTimeout(1000); let willFrameNavigateEmitted = false; let isMainFrameValue; w.webContents.on('will-frame-navigate', (event) => { willFrameNavigateEmitted = true; isMainFrameValue = event.isMainFrame; }); const didNavigatePromise = once(w.webContents, 'did-navigate'); 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); await didNavigatePromise; expect(willFrameNavigateEmitted).to.be.true(); expect(isMainFrameValue).to.be.true(); }); it('is triggered when a cross-origin iframe navigates itself', async () => { await w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-iframe"></iframe>`); await setTimeout(1000); let willNavigateEmitted = false; let isMainFrameValue; w.webContents.on('will-frame-navigate', (event) => { willNavigateEmitted = true; isMainFrameValue = event.isMainFrame; }); const didNavigatePromise = once(w.webContents, 'did-frame-navigate'); 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); await didNavigatePromise; expect(willNavigateEmitted).to.be.true(); expect(isMainFrameValue).to.be.false(); }); it('can cancel when a cross-origin iframe navigates itself', async () => { }); }); describe('will-redirect event', () => { let server: http.Server; let url: string; before(async () => { 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(); } }); url = (await listen(server)).url; }); after(() => { server.close(); }); it('is emitted on redirects', async () => { const willRedirect = once(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 = once(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 = once(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', async () => { const event = once(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await event; w.close(); }); 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('ordering', () => { let server = null as unknown as http.Server; let url = null as unknown as string; const navigationEvents = [ 'did-start-navigation', 'did-navigate-in-page', 'will-frame-navigate', 'will-navigate', 'will-redirect', 'did-redirect-navigation', 'did-frame-navigate', 'did-navigate' ]; before((done) => { server = http.createServer((req, res) => { if (req.url === '/navigate') { res.end('<a href="/">navigate</a>'); } else if (req.url === '/redirect') { res.end('<a href="/redirect2">redirect</a>'); } else if (req.url === '/redirect2') { res.statusCode = 302; res.setHeader('location', url); res.end(); } else if (req.url === '/in-page') { res.end('<a href="#in-page">redirect</a><div id="in-page"></div>'); } else { res.end(''); } }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/`; done(); }); }); it('for initial navigation, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'did-frame-navigate', 'did-navigate' ]; const allEvents = Promise.all(navigationEvents.map(event => once(w.webContents, event).then(() => firedEvents.push(event)) )); const timeout = setTimeout(1000); w.loadURL(url); await Promise.race([allEvents, timeout]); expect(firedEvents).to.deep.equal(expectedEventOrder); }); it('for second navigation, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'will-frame-navigate', 'will-navigate', 'did-frame-navigate', 'did-navigate' ]; w.loadURL(`${url}navigate`); await once(w.webContents, 'did-navigate'); await setTimeout(2000); Promise.all(navigationEvents.map(event => once(w.webContents, event).then(() => firedEvents.push(event)) )); const navigationFinished = once(w.webContents, 'did-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: pageTarget.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); await navigationFinished; expect(firedEvents).to.deep.equal(expectedEventOrder); }); it('when navigating with redirection, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'will-frame-navigate', 'will-navigate', 'will-redirect', 'did-redirect-navigation', 'did-frame-navigate', 'did-navigate' ]; w.loadURL(`${url}redirect`); await once(w.webContents, 'did-navigate'); await setTimeout(2000); Promise.all(navigationEvents.map(event => once(w.webContents, event).then(() => firedEvents.push(event)) )); const navigationFinished = once(w.webContents, 'did-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: pageTarget.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); await navigationFinished; expect(firedEvents).to.deep.equal(expectedEventOrder); }); it('when navigating in-page, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'did-navigate-in-page' ]; w.loadURL(`${url}in-page`); await once(w.webContents, 'did-navigate'); await setTimeout(2000); Promise.all(navigationEvents.map(event => once(w.webContents, event).then(() => firedEvents.push(event)) )); const navigationFinished = once(w.webContents, 'did-navigate-in-page'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: pageTarget.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); await navigationFinished; expect(firedEvents).to.deep.equal(expectedEventOrder); }); }); }); } describe('focus and visibility', () => { let w: 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', async () => { const p = once(w, 'focus'); w.show(); await p; expect(w.isFocused()).to.equal(true); }); it('should make the window visible', async () => { const p = once(w, 'focus'); w.show(); await p; expect(w.isVisible()).to.equal(true); }); it('emits when window is shown', async () => { const show = once(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 = once(w, 'show'); w.show(); await shown; const hidden = once(w, 'hide'); w.hide(); await hidden; expect(w.isVisible()).to.equal(false); }); }); describe('BrowserWindow.minimize()', () => { // TODO(codebytere): Enable for Linux once maximize/minimize events work in CI. ifit(process.platform !== 'linux')('should not be visible when the window is minimized', async () => { const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMinimized()).to.equal(true); 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 = once(w, 'maximize'); const shown = once(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 setTimeout(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); }); ifit(process.platform !== 'win32')('focuses a blurred window', async () => { { const isBlurred = once(w, 'blur'); const isShown = once(w, 'show'); w.show(); w.blur(); await isShown; await isBlurred; } expect(w.isFocused()).to.equal(false); w.focus(); expect(w.isFocused()).to.equal(true); }); ifit(process.platform !== 'linux')('acquires focus status from the other windows', async () => { const w1 = new BrowserWindow({ show: false }); const w2 = new BrowserWindow({ show: false }); const w3 = new BrowserWindow({ show: false }); { const isFocused3 = once(w3, 'focus'); const isShown1 = once(w1, 'show'); const isShown2 = once(w2, 'show'); const isShown3 = once(w3, 'show'); w1.show(); w2.show(); w3.show(); await isShown1; await isShown2; await isShown3; await isFocused3; } // TODO(RaisinTen): Investigate why this assertion fails only on Linux. expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); w1.focus(); expect(w1.isFocused()).to.equal(true); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(false); w2.focus(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(true); expect(w3.isFocused()).to.equal(false); w3.focus(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); { const isClosed1 = once(w1, 'closed'); const isClosed2 = once(w2, 'closed'); const isClosed3 = once(w3, 'closed'); w1.destroy(); w2.destroy(); w3.destroy(); await isClosed1; await isClosed2; await isClosed3; } }); }); // TODO(RaisinTen): Make this work on Windows too. // Refs: https://github.com/electron/electron/issues/20464. ifdescribe(process.platform !== 'win32')('BrowserWindow.blur()', () => { it('removes focus from window', async () => { { const isFocused = once(w, 'focus'); const isShown = once(w, 'show'); w.show(); await isShown; await isFocused; } expect(w.isFocused()).to.equal(true); w.blur(); expect(w.isFocused()).to.equal(false); }); ifit(process.platform !== 'linux')('transfers focus status to the next window', async () => { const w1 = new BrowserWindow({ show: false }); const w2 = new BrowserWindow({ show: false }); const w3 = new BrowserWindow({ show: false }); { const isFocused3 = once(w3, 'focus'); const isShown1 = once(w1, 'show'); const isShown2 = once(w2, 'show'); const isShown3 = once(w3, 'show'); w1.show(); w2.show(); w3.show(); await isShown1; await isShown2; await isShown3; await isFocused3; } // TODO(RaisinTen): Investigate why this assertion fails only on Linux. expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); w3.blur(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(true); expect(w3.isFocused()).to.equal(false); w2.blur(); expect(w1.isFocused()).to.equal(true); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(false); w1.blur(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); { const isClosed1 = once(w1, 'closed'); const isClosed2 = once(w2, 'closed'); const isClosed3 = once(w3, 'closed'); w1.destroy(); w2.destroy(); w3.destroy(); await isClosed1; await isClosed2; await isClosed3; } }); }); describe('BrowserWindow.getFocusedWindow()', () => { it('returns the opener window when dev tools window is focused', async () => { const p = once(w, 'focus'); w.show(); await p; w.webContents.openDevTools({ mode: 'undocked' }); await once(w.webContents, 'devtools-focused'); expect(BrowserWindow.getFocusedWindow()).to.equal(w); }); }); describe('BrowserWindow.moveTop()', () => { it('should not steal focus', async () => { const posDelta = 50; const wShownInactive = once(w, 'show'); w.showInactive(); await wShownInactive; expect(w.isFocused()).to.equal(false); const otherWindow = new BrowserWindow({ show: false, title: 'otherWindow' }); const otherWindowShown = once(otherWindow, 'show'); const otherWindowFocused = once(otherWindow, 'focus'); otherWindow.show(); await otherWindowShown; await otherWindowFocused; expect(otherWindow.isFocused()).to.equal(true); w.moveTop(); const wPos = w.getPosition(); const wMoving = once(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 = once(w, 'focus'); const otherWindowBlurred = once(otherWindow, 'blur'); w.focus(); await wFocused; await otherWindowBlurred; expect(w.isFocused()).to.equal(true); otherWindow.moveTop(); const otherWindowPos = otherWindow.getPosition(); const otherWindowMoving = once(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); }); }); describe('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 = once(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 = once(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: 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 = { ...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(once(w, 'resized')).to.eventually.be.fulfilled(); }); }); }); describe('BrowserWindow.setSize(width, height)', () => { it('sets the window size', async () => { const size = [300, 400]; const resized = once(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(once(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 = once(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 = once(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 = once(w, 'resize'); w.setContentBounds(bounds); await resize; await setTimeout(); 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 = once(w, 'resize'); w.setContentBounds(bounds); await resize; await setTimeout(); 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); }); it('returns correct color with multiple passed formats', () => { w.destroy(); w = new BrowserWindow({}); w.setBackgroundColor('#AABBFF'); expect(w.getBackgroundColor()).to.equal('#AABBFF'); w.setBackgroundColor('blueviolet'); expect(w.getBackgroundColor()).to.equal('#8A2BE2'); w.setBackgroundColor('rgb(255, 0, 185)'); expect(w.getBackgroundColor()).to.equal('#FF00B9'); w.setBackgroundColor('rgba(245, 40, 145, 0.8)'); expect(w.getBackgroundColor()).to.equal('#F52891'); w.setBackgroundColor('hsl(155, 100%, 50%)'); expect(w.getBackgroundColor()).to.equal('#00FF95'); }); }); describe('BrowserWindow.getNormalBounds()', () => { describe('Normal state', () => { it('checks normal bounds after resize', async () => { const size = [300, 400]; const resize = once(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 = once(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 = once(w, 'maximize'); w.show(); w.maximize(); await maximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after resize and maximize', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('updates normal bounds after move and maximize', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('checks normal bounds when unmaximized', async () => { const bounds = w.getBounds(); w.once('maximize', () => { w.unmaximize(); }); const unmaximize = once(w, 'unmaximize'); w.show(); w.maximize(); await unmaximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('correctly reports maximized state after maximizing then minimizing', async () => { w.destroy(); w = new BrowserWindow({ show: false }); w.show(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMaximized()).to.equal(false); expect(w.isMinimized()).to.equal(true); }); it('correctly reports maximized state after maximizing then fullscreening', async () => { w.destroy(); w = new BrowserWindow({ show: false }); w.show(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; expect(w.isMaximized()).to.equal(false); expect(w.isFullScreen()).to.equal(true); }); it('checks normal bounds for maximized transparent window', async () => { w.destroy(); w = new BrowserWindow({ transparent: true, show: false }); w.show(); const bounds = w.getNormalBounds(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; 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 = once(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 = once(w, 'maximize'); w.show(); w.maximize(); await maximize; expect(w.isMaximized()).to.equal(true); const unmaximize = once(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 = once(w, 'maximize'); 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 = once(w, 'minimize'); w.show(); w.minimize(); await minimize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after move and minimize', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const minimize = once(w, 'minimize'); w.minimize(); await minimize; const normal = w.getNormalBounds(); expect(original).to.deep.equal(normal); expectBoundsEqual(normal, w.getBounds()); }); it('updates normal bounds after resize and minimize', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const minimize = once(w, 'minimize'); w.minimize(); await minimize; const normal = w.getNormalBounds(); expect(original).to.deep.equal(normal); expectBoundsEqual(normal, w.getBounds()); }); it('checks normal bounds when restored', async () => { const bounds = w.getBounds(); w.once('minimize', () => { w.restore(); }); const restore = once(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 = once(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('does not go fullscreen if roundedCorners are enabled', async () => { w = new BrowserWindow({ frame: false, roundedCorners: false, fullscreen: true }); expect(w.fullScreen).to.be.false(); }); 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 = once(w, 'enter-full-screen'); w.show(); w.fullScreen = true; await enterFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after resize and fullscreen', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.fullScreen = true; await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('updates normal bounds after move and fullscreen', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.fullScreen = true; await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('checks normal bounds when unfullscreen\'ed', async () => { const bounds = w.getBounds(); w.once('enter-full-screen', () => { w.fullScreen = false; }); const leaveFullScreen = once(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 = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after resize and fullscreen', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.setFullScreen(true); await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('updates normal bounds after move and fullscreen', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.setFullScreen(true); await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('checks normal bounds when unfullscreen\'ed', async () => { const bounds = w.getBounds(); w.show(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); }); }); }); ifdescribe(process.platform === 'darwin')('tabbed windows', () => { let w: 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.showAllTabs()', () => { it('does not throw', () => { expect(() => { w.showAllTabs(); }).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); }); ifit(process.platform === 'darwin')('honors the stayHidden argument', async () => { const w = new BrowserWindow({ webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.hide(); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } await w.capturePage({ x: 0, y: 0, width: 0, height: 0 }, { stayHidden: true }); const visible = await w.webContents.executeJavaScript('document.visibilityState'); expect(visible).to.equal('hidden'); }); it('resolves after the window is hidden', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixtures, 'pages', 'a.html')); await once(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('resolves after the window is hidden and capturer count is non-zero', async () => { const w = new BrowserWindow({ show: false }); w.webContents.setBackgroundThrottling(false); w.loadFile(path.join(fixtures, 'pages', 'a.html')); await once(w, 'ready-to-show'); const image = await w.capturePage(); expect(image.isEmpty()).to.equal(false); }); it('preserves transparency', async () => { const w = new BrowserWindow({ show: false, transparent: true }); w.loadFile(path.join(fixtures, 'pages', 'theme-color.html')); await once(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: 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: 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', async () => { expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); const minimized = once(w, 'minimize'); w.minimize(); await minimized; expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); const restored = once(w, 'restore'); w.restore(); await restored; 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 = once(w, 'always-on-top-changed') as Promise<[any, boolean]>; 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: BrowserWindow; let server: http.Server; let url: 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++; }); url = (await listen(server)).url; }); 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 = once(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: 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); }); it('correctly updates when entering/exiting fullscreen for hidden style', async () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hidden' }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; const leaveFS = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFS; w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); it('correctly updates when entering/exiting fullscreen for hiddenInset style', async () => { 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); const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; const leaveFS = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFS; w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setVibrancy(type)', () => { afterEach(closeAllWindows); it('allows setting, changing, and removing the vibrancy', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setVibrancy('titlebar'); w.setVibrancy('selection'); w.setVibrancy(null); w.setVibrancy('menu'); 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(); }); }); ifdescribe(process.platform === 'darwin')('trafficLightPosition', () => { const pos = { x: 10, y: 10 }; afterEach(closeAllWindows); describe('BrowserWindow.getWindowButtonPosition(pos)', () => { it('returns null when there is no custom position', () => { const w = new BrowserWindow({ show: false }); expect(w.getWindowButtonPosition()).to.be.null('getWindowButtonPosition'); }); it('gets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); expect(w.getWindowButtonPosition()).to.deep.equal(pos); }); it('gets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); expect(w.getWindowButtonPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setWindowButtonPosition(pos)', () => { it('resets the position when null is passed', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); w.setWindowButtonPosition(null); expect(w.getWindowButtonPosition()).to.be.null('setWindowButtonPosition'); }); it('sets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setWindowButtonPosition(newPos); expect(w.getWindowButtonPosition()).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.setWindowButtonPosition(newPos); expect(w.getWindowButtonPosition()).to.deep.equal(newPos); }); }); // The set/getTrafficLightPosition APIs are deprecated. describe('BrowserWindow.getTrafficLightPosition(pos)', () => { it('returns { x: 0, y: 0 } when there is no custom position', () => { const w = new BrowserWindow({ show: false }); expect(w.getTrafficLightPosition()).to.deep.equal({ x: 0, y: 0 }); }); 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('resets the position when { x: 0, y: 0 } is passed', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); w.setTrafficLightPosition({ x: 0, y: 0 }); expect(w.getTrafficLightPosition()).to.deep.equal({ x: 0, y: 0 }); }); 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('Opening a BrowserWindow from a link', () => { let appProcess: childProcess.ChildProcessWithoutNullStreams | undefined; afterEach(() => { if (appProcess && !appProcess.killed) { appProcess.kill(); appProcess = undefined; } }); it('can properly open and load a new window from a link', async () => { const appPath = path.join(__dirname, 'fixtures', 'apps', 'open-new-window-from-link'); appProcess = childProcess.spawn(process.execPath, [appPath]); const [code] = await once(appProcess, 'exit'); expect(code).to.equal(0); }); }); 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 typeof ElectronInternal.WebContents).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.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 = once(w.webContents, 'did-attach-webview'); const [, webviewContents] = await once(app, 'web-contents-created') as [any, WebContents]; expect(BrowserWindow.fromWebContents(webviewContents)!.id).to.equal(w.id); await p; }); it('is usable immediately on browser-window-created', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.executeJavaScript('window.open(""); null'); const [win, winFromWebContents] = await new Promise<any>((resolve) => { app.once('browser-window-created', (e, win) => { resolve([win, BrowserWindow.fromWebContents(win.webContents)]); }); }); expect(winFromWebContents).to.equal(win); }); }); 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.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.destroy(); bv2.webContents.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.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(['win32', 'darwin'].includes(process.platform))('"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 = once(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 = once(ipcMain, 'geometrychange'); w.setBounds({ width: 800 }); const [, newOverlayRect] = await geometryChange; expect(newOverlayRect.width).to.equal(overlayRect.width + 400); }; afterEach(async () => { await closeAllWindows(); 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')('when an invalid titleBarStyle is initially set', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { color: '#0000f0', symbolColor: '#ffffff' }, titleBarStyle: 'hiddenInset' }); }); afterEach(async () => { await closeAllWindows(); }); it('does not crash changing minimizability ', () => { expect(() => { w.setMinimizable(false); }).to.not.throw(); }); it('does not crash changing maximizability', () => { expect(() => { w.setMaximizable(false); }).to.not.throw(); }); }); }); ifdescribe(['win32', 'darwin'].includes(process.platform))('"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 = once(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()'); if (!w.isMaximized()) { const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; } expect(w.isMaximized()).to.be.true('not maximized'); 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(async () => { await closeAllWindows(); ipcMain.removeAllListeners('geometrychange'); }); it('sets Window Control Overlay with title bar height of 40', async () => { await testWindowsOverlayHeight(40); }); }); ifdescribe(process.platform === 'win32')('BrowserWindow.setTitlebarOverlay', () => { afterEach(async () => { await closeAllWindows(); ipcMain.removeAllListeners('geometrychange'); }); it('does not crash when an invalid titleBarStyle was initially set', () => { const win = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { color: '#0000f0', symbolColor: '#ffffff' }, titleBarStyle: 'hiddenInset' }); expect(() => { win.setTitleBarOverlay({ color: '#000000' }); }).to.not.throw(); }); it('correctly updates the height of the overlay', async () => { const testOverlay = async (w: BrowserWindow, size: Number, firstRun: boolean) => { const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); const overlayReady = once(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); if (firstRun) { await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const { height: preMaxHeight } = await w.webContents.executeJavaScript('getJSOverlayProperties()'); if (!w.isMaximized()) { const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; } expect(w.isMaximized()).to.be.true('not maximized'); const { x, y, width, height } = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(x).to.equal(0); expect(y).to.equal(0); expect(width).to.be.greaterThan(0); expect(height).to.equal(size); expect(preMaxHeight).to.equal(size); }; const INITIAL_SIZE = 40; const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden', webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { height: INITIAL_SIZE } }); await testOverlay(w, INITIAL_SIZE, true); w.setTitleBarOverlay({ height: INITIAL_SIZE + 10 }); await testOverlay(w, INITIAL_SIZE + 10, false); }); }); 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-next-line no-new */ new BrowserWindow({ tabbingIdentifier: 'group1' }); /* eslint-disable-next-line no-new */ new BrowserWindow({ tabbingIdentifier: 'group2', frame: false }); }).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 once(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 once(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 once(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-isolated 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 once(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 once(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 once(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 once(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 once(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 once(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; let serverUrl: string; before(async () => { 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}`); } }); serverUrl = (await listen(server)).url; }); 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 once(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 once(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 once(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 once(ipcMain, 'answer'); const expectedUrl = process.platform === 'win32' ? 'file:///' + htmlPath.replace(/\\/g, '/') : pageUrl; expect(url).to.equal(expectedUrl); }); it('exposes full EventEmitter object to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload: path.join(fixtures, 'module', 'preload-eventemitter.js') } }); w.loadURL('about:blank'); const [, rendererEventEmitterProperties] = await once(ipcMain, 'answer'); const { EventEmitter } = require('node:events'); const emitter = new EventEmitter(); const browserEventEmitterProperties = []; let currentObj = emitter; do { browserEventEmitterProperties.push(...Object.getOwnPropertyNames(currentObj)); } while ((currentObj = Object.getPrototypeOf(currentObj))); expect(rendererEventEmitterProperties).to.deep.equal(browserEventEmitterProperties); }); 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 = once(ipcMain, 'answer'); w.loadURL(pageUrl); const [, { url, frameName, options }] = await once(w.webContents, 'did-create-window') as [BrowserWindow, Electron.DidCreateWindowDetails]; 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 once(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 once(app, 'browser-window-created') as [any, BrowserWindow]; // Ask the popup window for details. const detailsAnswer = once(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 = once(ipcMain, 'answer'); w.webContents.send('touch-the-popup'); const [, popupAccessMessage] = await touchPopupResult; // Ask the popup to access the opener. const touchOpenerResult = once(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 once(ipcMain, 'answer'); expect(argv).to.include('--enable-sandbox'); }); it('should open windows with the options configured via setWindowOpenHandler handlers', 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([ once(app, 'web-contents-created') as Promise<[any, WebContents]>, once(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 => once(ipcMain, name))); w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'verify-ipc-sender' }); await done; }); describe('event handling', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); }); it('works for window events', async () => { const pageTitleUpdated = once(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 => once(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 => once(w.webContents, name))); w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'webcontents-events' }); await done; }); }); 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 once(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'); expect(test.nodeEvents).to.equal(true); expect(test.nodeTimers).to.equal(true); expect(test.nodeUrl).to.equal(true); 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 = once(w.webContents, 'did-attach-webview') as Promise<[any, WebContents]>; const webviewDomReady = once(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; 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 = once(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 = once(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 = once(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 = once(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 once(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 once(ipcMain, 'answer'); expect(content).to.equal('function'); } w.reload(); { const [, content] = await once(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, preload } } })); const webviewLoaded = once(ipcMain, 'webview-loaded'); w.loadFile(path.join(fixtures, 'api', 'new-window-webview.html')); await webviewLoaded; }); it('should open windows with the options configured via setWindowOpenHandler handlers', 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([ once(app, 'web-contents-created') as Promise<[any, WebContents]>, once(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 once(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 once(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 = once(w.webContents, 'enter-html-full-screen'); w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true); await enterHtmlFullScreen; expect(w.getSize()).to.deep.equal(size); }); }); describe('"defaultFontFamily" option', () => { it('can change the standard font family', async () => { const w = new BrowserWindow({ show: false, webPreferences: { defaultFontFamily: { standard: 'Impact' } } }); await w.loadFile(path.join(fixtures, 'pages', 'content.html')); const fontFamily = await w.webContents.executeJavaScript("window.getComputedStyle(document.getElementsByTagName('p')[0])['font-family']", true); expect(fontFamily).to.equal('Impact'); }); }); }); describe('beforeunload handler', function () { let w: 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 = once(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 once(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 once(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 once(w.webContents, 'console-message'); w.close(); await once(w.webContents, 'before-unload-fired'); w.close(); await once(w.webContents, 'before-unload-fired'); w.webContents.removeListener('destroyed', destroyListener); const wait = once(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 once(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 once(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 once(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'); }); }); // TODO(codebytere): figure out how to make these pass in CI on Windows. ifdescribe(process.platform !== 'win32')('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 once(ipcMain, 'pong'); expect(readyToShow).to.be.false('ready to show'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); }); it('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 once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.hide(); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } }); it('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 once(w, 'show'); } w.hide(); w.show(); const [, visibilityState] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); }); it('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 once(w, 'show'); } w.hide(); w.showInactive(); const [, visibilityState] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); }); 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 once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.minimize(); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } }); it('visibilityState remains visible if backgroundThrottling is disabled', async () => { const w = new BrowserWindow({ show: false, width: 100, height: 100, webPreferences: { backgroundThrottling: false, nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await once(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 = once(w, 'show'); w.show(); await shown1; const hidden = once(w, 'hide'); w.hide(); await hidden; const shown2 = once(w, 'show'); w.show(); await shown2; } finally { ipcMain.removeAllListeners('pong'); } }); }); 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 = once(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 = once(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 = once(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 = once(w, 'maximize'); const unmaximize = once(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 = once(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 }); let called = false; w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); w.webContents.on('dom-ready', () => { w.webContents.beginFrameSubscription(function () { // This callback might be called twice. if (called) return; called = true; // Pending endFrameSubscription to next tick can reliably reproduce // a crash which happens when nothing is returned in the callback. setTimeout().then(() => { 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 () => { /* Use temp directory for saving MHTML file since the write handle * gets passed to untrusted process and chromium will deny exec access to * the path. To perform this task, chromium requires that the path is one * of the browser controlled paths, refs https://chromium-review.googlesource.com/c/chromium/src/+/3774416 */ const tmpDir = await fs.promises.mkdtemp(path.resolve(os.tmpdir(), 'electron-mhtml-save-')); const savePageMHTMLPath = path.join(tmpDir, 'save_page.html'); const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageMHTMLPath, 'MHTML'); expect(fs.existsSync(savePageMHTMLPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.false('js path'); expect(fs.existsSync(savePageCssPath)).to.be.false('css path'); try { await fs.promises.unlink(savePageMHTMLPath); await fs.promises.rmdir(tmpDir); } catch {} }); 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(); }); // TODO(zcbenz): // This test does not run on Linux CI. See: // https://github.com/electron/electron/issues/28699 ifit(process.platform === 'linux' && !process.env.CI)('should bring a minimized maximized window back to maximized state', async () => { const w = new BrowserWindow({}); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMaximized()).to.equal(false); const restore = once(w, 'restore'); w.restore(); await restore; expect(w.isMaximized()).to.equal(true); }); }); // TODO(dsanders11): Enable once maximize event works on Linux again on CI ifdescribe(process.platform !== 'linux')('BrowserWindow.maximize()', () => { afterEach(closeAllWindows); it('should show the window if it is not currently shown', async () => { const w = new BrowserWindow({ show: false }); const hidden = once(w, 'hide'); let shown = once(w, 'show'); const maximize = once(w, 'maximize'); expect(w.isVisible()).to.be.false('visible'); w.maximize(); await maximize; await shown; expect(w.isMaximized()).to.be.true('maximized'); expect(w.isVisible()).to.be.true('visible'); // Even if the window is already maximized w.hide(); await hidden; expect(w.isVisible()).to.be.false('visible'); shown = once(w, 'show'); w.maximize(); await shown; expect(w.isVisible()).to.be.true('visible'); }); }); 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 = once(w, 'minimize'); w.minimize(); await minimize; w.unmaximize(); await setTimeout(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 setTimeout(1000); expectBoundsEqual(w.getSize(), initialSize); expectBoundsEqual(w.getPosition(), initialPosition); }); ifit(process.platform === 'darwin')('should not change size or position of a window which is functionally maximized', async () => { const { workArea } = screen.getPrimaryDisplay(); const bounds = { x: workArea.x, y: workArea.y, width: workArea.width, height: workArea.height }; const w = new BrowserWindow(bounds); w.unmaximize(); await setTimeout(1000); expectBoundsEqual(w.getBounds(), bounds); }); }); 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 = once(w, 'show'); // start fullscreen and hidden w.setFullScreen(true); w.show(); await shown; const leftFullScreen = once(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 = once(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 once(w, 'enter-full-screen'); // Wait a tick for the full-screen state to 'stick' await setTimeout(); w.setFullScreen(false); await once(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 = once(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 = once(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 = once(c, 'closed'); c.close(); await closed; // The child window list is not immediately cleared, so wait a tick until it's ready. await setTimeout(); expect(w.getChildWindows().length).to.equal(0); }); it('can handle child window close and reparent multiple times', async () => { const w = new BrowserWindow({ show: false }); let c: BrowserWindow | null; for (let i = 0; i < 5; i++) { c = new BrowserWindow({ show: false, parent: w }); const closed = once(c, 'closed'); c.close(); await closed; } await setTimeout(); expect(w.getChildWindows().length).to.equal(0); }); ifit(process.platform === 'darwin')('child window matches visibility when visibility changes', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); const wShow = once(w, 'show'); const cShow = once(c, 'show'); w.show(); c.show(); await Promise.all([wShow, cShow]); const minimized = once(w, 'minimize'); w.minimize(); await minimized; expect(w.isVisible()).to.be.false('parent is visible'); expect(c.isVisible()).to.be.false('child is visible'); const restored = once(w, 'restore'); w.restore(); await restored; expect(w.isVisible()).to.be.true('parent is visible'); expect(c.isVisible()).to.be.true('child is visible'); }); ifit(process.platform === 'darwin')('matches child window visibility when visibility changes', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); const wShow = once(w, 'show'); const cShow = once(c, 'show'); w.show(); c.show(); await Promise.all([wShow, cShow]); const minimized = once(c, 'minimize'); c.minimize(); await minimized; expect(c.isVisible()).to.be.false('child is visible'); const restored = once(c, 'restore'); c.restore(); await restored; expect(w.isVisible()).to.be.true('parent is visible'); expect(c.isVisible()).to.be.true('child is visible'); }); it('closes a grandchild window when a middle child window is destroyed', (done) => { const w = new BrowserWindow(); w.loadFile(path.join(fixtures, 'pages', 'base-page.html')); w.webContents.executeJavaScript('window.open("")'); w.webContents.on('did-create-window', async (window) => { const childWindow = new BrowserWindow({ parent: window }); await setTimeout(); window.close(); childWindow.on('closed', () => { expect(() => { BrowserWindow.getFocusedWindow(); }).to.not.throw(); done(); }); }); }); 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 = once(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 setTimeout(); expect(w.getChildWindows().length).to.equal(0); }); ifit(process.platform === 'darwin')('can reparent when the first parent is destroyed', async () => { const w1 = new BrowserWindow({ show: false }); const w2 = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); c.setParentWindow(w1); expect(w1.getChildWindows().length).to.equal(1); const closed = once(w1, 'closed'); w1.destroy(); await closed; c.setParentWindow(w2); await setTimeout(); const children = w2.getChildWindows(); expect(children[0]).to.equal(c); }); }); 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 = once(two, 'show'); two.show(); await twoShown; setTimeout(500).then(() => two.close()); await once(two, 'closed'); }; const one = new BrowserWindow({ width: 600, height: 400, parent: parentWindow, modal: true, show: false }); const oneShown = once(one, 'show'); one.show(); await oneShown; setTimeout(500).then(() => one.destroy()); await once(one, 'closed'); await createTwo(); }); ifit(process.platform !== 'darwin')('can disable and enable a window', () => { const w = new BrowserWindow({ show: false }); w.setEnabled(false); expect(w.isEnabled()).to.be.false('w.isEnabled()'); w.setEnabled(true); expect(w.isEnabled()).to.be.true('!w.isEnabled()'); }); 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 = once(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 = once(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; let serverUrl: string; before(async () => { server = http.createServer((request, response) => { response.end(); }); serverUrl = (await listen(server)).url; }); after(() => { server.close(); }); it('is true when the main frame is loading', async () => { const w = new BrowserWindow({ show: false }); const didStartLoading = once(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 = once(w.webContents, 'did-stop-loading'); w.webContents.loadURL(serverUrl); await didStopLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); const didStartLoading = once(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 = once(w.webContents, 'did-stop-loading'); w.webContents.loadURL(serverUrl); await didStopLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); const didStartLoading = once(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')('when fullscreen state is changed', () => { it('correctly remembers state prior to fullscreen change', async () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); w.setMenuBarVisibility(false); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; expect(w.fullScreen).to.be.true('not fullscreen'); const exitFS = once(w, 'leave-full-screen'); w.setFullScreen(false); await exitFS; expect(w.fullScreen).to.be.false('not fullscreen'); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); }); it('correctly remembers state prior to fullscreen change with autoHide', async () => { const w = new BrowserWindow({ show: false }); expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); w.autoHideMenuBar = true; expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); w.setMenuBarVisibility(false); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; expect(w.fullScreen).to.be.true('not fullscreen'); const exitFS = once(w, 'leave-full-screen'); w.setFullScreen(false); await exitFS; expect(w.fullScreen).to.be.false('not fullscreen'); expect(w.isMenuBarVisible()).to.be.false('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'); }); }); }); ifdescribe(process.platform === 'darwin')('isHiddenInMissionControl state', () => { it('with functions', () => { it('can be set with ignoreMissionControl constructor option', () => { const w = new BrowserWindow({ show: false, hiddenInMissionControl: true }); expect(w.isHiddenInMissionControl()).to.be.true('isHiddenInMissionControl'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isHiddenInMissionControl()).to.be.false('isHiddenInMissionControl'); w.setHiddenInMissionControl(true); expect(w.isHiddenInMissionControl()).to.be.true('isHiddenInMissionControl'); w.setHiddenInMissionControl(false); expect(w.isHiddenInMissionControl()).to.be.false('isHiddenInMissionControl'); }); }); }); // 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 = once(w, 'enter-full-screen'); w.kiosk = true; expect(w.isKiosk()).to.be.true('isKiosk'); await enterFullScreen; await setTimeout(); const leaveFullScreen = once(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 = once(w, 'enter-full-screen'); w.setKiosk(true); expect(w.isKiosk()).to.be.true('isKiosk'); await enterFullScreen; await setTimeout(); const leaveFullScreen = once(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 false and restored', async () => { const w = new BrowserWindow({ resizable: false }); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.resizable).to.be.false('resizable'); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.resizable).to.be.false('resizable'); }); it('default resizable flag should be restored after entering/exiting fullscreen', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.resizable).to.be.false('resizable'); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.resizable).to.be.true('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 = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; }); it('should be able to load a URL while transitioning to fullscreen', async () => { const w = new BrowserWindow({ fullscreen: true }); w.loadFile(path.join(fixtures, 'pages', 'c.html')); const load = once(w.webContents, 'did-finish-load'); const enterFS = once(w, 'enter-full-screen'); await Promise.all([enterFS, load]); expect(w.fullScreen).to.be.true(); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; }); it('can be changed with setFullScreen method', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await setTimeout(); const leaveFullScreen = once(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 setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); }); it('handles several HTML fullscreen transitions', async () => { const w = new BrowserWindow(); await w.loadFile(path.join(fixtures, 'pages', 'a.html')); expect(w.isFullScreen()).to.be.false('is fullscreen'); const enterFullScreen = once(w, 'enter-full-screen'); const leaveFullScreen = once(w, 'leave-full-screen'); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await enterFullScreen; await w.webContents.executeJavaScript('document.exitFullscreen()', true); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); await setTimeout(); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await enterFullScreen; await w.webContents.executeJavaScript('document.exitFullscreen()', true); 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'); const enterFS = emittedNTimes(w, 'enter-full-screen', 2); const leaveFS = emittedNTimes(w, 'leave-full-screen', 2); w.setFullScreen(true); w.setFullScreen(false); w.setFullScreen(true); w.setFullScreen(false); await Promise.all([enterFS, leaveFS]); expect(w.isFullScreen()).to.be.false('not fullscreen'); }); it('handles several chromium-initiated transitions in close proximity', async () => { const w = new BrowserWindow(); await w.loadFile(path.join(fixtures, 'pages', 'a.html')); expect(w.isFullScreen()).to.be.false('is fullscreen'); let enterCount = 0; let exitCount = 0; const done = new Promise<void>(resolve => { const checkDone = () => { if (enterCount === 2 && exitCount === 2) resolve(); }; w.webContents.on('enter-html-full-screen', () => { enterCount++; checkDone(); }); w.webContents.on('leave-html-full-screen', () => { exitCount++; checkDone(); }); }); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await done; }); it('handles HTML fullscreen transitions when fullscreenable is false', async () => { const w = new BrowserWindow({ fullscreenable: false }); await w.loadFile(path.join(fixtures, 'pages', 'a.html')); expect(w.isFullScreen()).to.be.false('is fullscreen'); let enterCount = 0; let exitCount = 0; const done = new Promise<void>((resolve, reject) => { const checkDone = () => { if (enterCount === 2 && exitCount === 2) resolve(); }; w.webContents.on('enter-html-full-screen', async () => { enterCount++; if (w.isFullScreen()) reject(new Error('w.isFullScreen should be false')); const isFS = await w.webContents.executeJavaScript('!!document.fullscreenElement'); if (!isFS) reject(new Error('Document should have fullscreen element')); checkDone(); }); w.webContents.on('leave-html-full-screen', () => { exitCount++; if (w.isFullScreen()) reject(new Error('w.isFullScreen should be false')); checkDone(); }); }); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await expect(done).to.eventually.be.fulfilled(); }); it('does not crash when exiting simpleFullScreen (properties)', async () => { const w = new BrowserWindow(); w.setSimpleFullScreen(true); await setTimeout(1000); w.setFullScreen(!w.isFullScreen()); }); it('does not crash when exiting simpleFullScreen (functions)', async () => { const w = new BrowserWindow(); w.simpleFullScreen = true; await setTimeout(1000); w.setFullScreen(!w.isFullScreen()); }); it('should not be changed by setKiosk method', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setKiosk(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); const leaveFullScreen = once(w, 'leave-full-screen'); w.setKiosk(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('isFullScreen'); }); it('should stay fullscreen if fullscreen before kiosk', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); w.setKiosk(true); w.setKiosk(false); // Wait enough time for a fullscreen change to take effect. await setTimeout(2000); expect(w.isFullScreen()).to.be.true('isFullScreen'); }); it('multiple windows inherit correct fullscreen state', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await setTimeout(1000); const w2 = new BrowserWindow({ show: false }); const enterFullScreen2 = once(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 = once(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(); }); it('should not call BrowserWindow show event', async () => { const w = new BrowserWindow({ show: false }); const shown = once(w, 'show'); w.show(); await shown; let showCalled = false; w.on('show', () => { showCalled = true; }); w.previewFile(__filename); await setTimeout(500); expect(showCalled).to.equal(false, 'should not have called show twice'); }); }); // TODO (jkleinsc) renable these tests on mas arm64 ifdescribe(!process.mas || process.arch !== 'arm64')('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 = once(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 = once(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 = once(app, 'browser-window-created') as Promise<[any, BrowserWindow]>; 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 = once(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 = once(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 = once(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 = once(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 = once(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 = once(w1, 'focus'); w1.webContents.focus(); await w1Focused; expect(w1.webContents.isFocused()).to.be.true('focuses window'); }); }); describe('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 = once(w.webContents, 'paint') as Promise<[any, Electron.Rectangle, Electron.NativeImage]>; 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 = once(w.webContents, 'paint') as Promise<[any, Electron.Rectangle, Electron.NativeImage]>; 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 = once(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 = once(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.stopPainting(); w.webContents.startPainting(); await once(w.webContents, 'paint') as [any, Electron.Rectangle, Electron.NativeImage]; 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 once(w.webContents, 'paint') as [any, Electron.Rectangle, Electron.NativeImage]; expect(w.webContents.getFrameRate()).to.equal(60); }); it('has default frame rate (property)', async () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await once(w.webContents, 'paint') as [any, Electron.Rectangle, Electron.NativeImage]; expect(w.webContents.frameRate).to.equal(60); }); it('sets custom frame rate (function)', async () => { const domReady = once(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.setFrameRate(30); await once(w.webContents, 'paint') as [any, Electron.Rectangle, Electron.NativeImage]; expect(w.webContents.getFrameRate()).to.equal(30); }); it('sets custom frame rate (property)', async () => { const domReady = once(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.frameRate = 30; await once(w.webContents, 'paint') as [any, Electron.Rectangle, Electron.NativeImage]; expect(w.webContents.frameRate).to.equal(30); }); }); }); describe('"transparent" option', () => { afterEach(closeAllWindows); ifit(process.platform !== 'linux')('correctly returns isMaximized() when the window is maximized then minimized', async () => { const w = new BrowserWindow({ frame: false, transparent: true }); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMaximized()).to.be.false(); expect(w.isMinimized()).to.be.true(); }); // 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 once(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 === 'darwin' && process.arch === 'x64')('should not display a visible background', async () => { const display = screen.getPrimaryDisplay(); const backgroundWindow = new BrowserWindow({ ...display.bounds, frame: false, backgroundColor: HexColors.GREEN, hasShadow: false }); await backgroundWindow.loadURL('about:blank'); const foregroundWindow = new BrowserWindow({ ...display.bounds, show: true, transparent: true, frame: false, hasShadow: false }); const colorFile = path.join(__dirname, 'fixtures', 'pages', 'half-background-color.html'); await foregroundWindow.loadFile(colorFile); await setTimeout(1000); 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, HexColors.GREEN)).to.be.true(); expect(areColorsSimilar(rightHalfColor, HexColors.RED)).to.be.true(); }); ifit(process.platform === 'darwin')('Allows setting a transparent window via CSS', async () => { const display = screen.getPrimaryDisplay(); const backgroundWindow = new BrowserWindow({ ...display.bounds, frame: false, backgroundColor: HexColors.PURPLE, hasShadow: false }); await backgroundWindow.loadURL('about:blank'); const foregroundWindow = new BrowserWindow({ ...display.bounds, frame: false, transparent: true, hasShadow: false, webPreferences: { contextIsolation: false, nodeIntegration: true } }); foregroundWindow.loadFile(path.join(__dirname, 'fixtures', 'pages', 'css-transparent.html')); await once(ipcMain, 'set-transparent'); await setTimeout(); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); expect(areColorsSimilar(centerColor, HexColors.PURPLE)).to.be.true(); }); // Linux and arm64 platforms (WOA and macOS) do not return any capture sources ifit(process.platform === 'darwin' && process.arch === 'x64')('should not make background transparent if falsy', async () => { const display = screen.getPrimaryDisplay(); for (const transparent of [false, undefined]) { const window = new BrowserWindow({ ...display.bounds, transparent }); await once(window, 'show'); await window.webContents.loadURL('data:text/html,<head><meta name="color-scheme" content="dark"></head>'); await setTimeout(500); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); window.close(); // color-scheme is set to dark so background should not be white expect(areColorsSimilar(centerColor, HexColors.WHITE)).to.be.false(); } }); }); describe('"backgroundColor" option', () => { afterEach(closeAllWindows); // Linux/WOA doesn't return any capture sources. ifit(process.platform === 'darwin')('should display the set color', async () => { const display = screen.getPrimaryDisplay(); const w = new BrowserWindow({ ...display.bounds, show: true, backgroundColor: HexColors.BLUE }); w.loadURL('about:blank'); await once(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, HexColors.BLUE)).to.be.true(); }); }); });
closed
electron/electron
https://github.com/electron/electron
39,413
[Bug]: App crashes with SIGTRAP while creating modal window on Mac
### 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 25.4.0 ### What operating system are you using? macOS ### Operating System Version 12.3 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version 25.1.1 ### Expected Behavior Not to crash:) ### Actual Behavior When I create new windows as modal to parent, I get crash with SIGTRAP Unfortunately, I couldn't reproduce this in small test project. Only fact I have, if I don't set new window as modal, app not crashes. ### Testcase Gist URL _No response_ ### Additional Information I can provide you part of stack trace and minidump <img width="872" alt="image" src="https://github.com/electron/electron/assets/25509934/ccfbba1b-13cd-4fee-a04c-1deff56d2dc3"> [2988dcae-9326-4b22-84d3-c0123f13e17f.dmp.zip](https://github.com/electron/electron/files/12292673/2988dcae-9326-4b22-84d3-c0123f13e17f.dmp.zip) There is very strange call for `ElectronPermissionMessageProvider::IsPrivilegeIncrease`. It seems like it never should be called. I also think it was affected here https://github.com/electron/electron/issues/38939
https://github.com/electron/electron/issues/39413
https://github.com/electron/electron/pull/39499
f7a7085019bf757700df3c2f8714e0de356203cd
1eb398b328d304f227deef0e89ca0be7b9e20755
2023-08-08T14:52:19Z
c++
2023-08-16T11:28:29Z
shell/browser/native_window_mac.mm
// 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_mac.h" #include <AvailabilityMacros.h> #include <objc/objc-runtime.h> #include <algorithm> #include <memory> #include <string> #include <utility> #include <vector> #include "base/mac/mac_util.h" #include "base/mac/scoped_cftyperef.h" #include "base/strings/sys_string_conversions.h" #include "components/remote_cocoa/app_shim/native_widget_ns_window_bridge.h" #include "components/remote_cocoa/browser/scoped_cg_window_id.h" #include "content/public/browser/browser_accessibility_state.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/desktop_media_id.h" #include "shell/browser/browser.h" #include "shell/browser/javascript_environment.h" #include "shell/browser/native_browser_view_mac.h" #include "shell/browser/ui/cocoa/electron_native_widget_mac.h" #include "shell/browser/ui/cocoa/electron_ns_window.h" #include "shell/browser/ui/cocoa/electron_ns_window_delegate.h" #include "shell/browser/ui/cocoa/electron_preview_item.h" #include "shell/browser/ui/cocoa/electron_touch_bar.h" #include "shell/browser/ui/cocoa/root_view_mac.h" #include "shell/browser/ui/cocoa/window_buttons_proxy.h" #include "shell/browser/ui/drag_util.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/window_list.h" #include "shell/common/gin_converters/gfx_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/node_includes.h" #include "shell/common/options_switches.h" #include "shell/common/process_util.h" #include "skia/ext/skia_utils_mac.h" #include "third_party/skia/include/core/SkRegion.h" #include "third_party/webrtc/modules/desktop_capture/mac/window_list_utils.h" #include "ui/base/hit_test.h" #include "ui/display/screen.h" #include "ui/gfx/skia_util.h" #include "ui/gl/gpu_switching_manager.h" #include "ui/views/background.h" #include "ui/views/cocoa/native_widget_mac_ns_window_host.h" #include "ui/views/widget/widget.h" #include "ui/views/window/native_frame_view_mac.h" #if !defined(__has_feature) || !__has_feature(objc_arc) #error "This file requires ARC support." #endif @interface ElectronProgressBar : NSProgressIndicator @end @implementation ElectronProgressBar - (void)drawRect:(NSRect)dirtyRect { if (self.style != NSProgressIndicatorStyleBar) return; // Draw edges of rounded rect. NSRect rect = NSInsetRect([self bounds], 1.0, 1.0); CGFloat radius = rect.size.height / 2; NSBezierPath* bezier_path = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [bezier_path setLineWidth:2.0]; [[NSColor grayColor] set]; [bezier_path stroke]; // Fill the rounded rect. rect = NSInsetRect(rect, 2.0, 2.0); radius = rect.size.height / 2; bezier_path = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [bezier_path setLineWidth:1.0]; [bezier_path addClip]; // Calculate the progress width. rect.size.width = floor(rect.size.width * ([self doubleValue] / [self maxValue])); // Fill the progress bar with color blue. [[NSColor colorWithSRGBRed:0.2 green:0.6 blue:1 alpha:1] set]; NSRectFill(rect); } @end namespace gin { template <> struct Converter<electron::NativeWindowMac::VisualEffectState> { static bool FromV8(v8::Isolate* isolate, v8::Handle<v8::Value> val, electron::NativeWindowMac::VisualEffectState* out) { using VisualEffectState = electron::NativeWindowMac::VisualEffectState; std::string visual_effect_state; if (!ConvertFromV8(isolate, val, &visual_effect_state)) return false; if (visual_effect_state == "followWindow") { *out = VisualEffectState::kFollowWindow; } else if (visual_effect_state == "active") { *out = VisualEffectState::kActive; } else if (visual_effect_state == "inactive") { *out = VisualEffectState::kInactive; } else { return false; } return true; } }; } // namespace gin namespace electron { namespace { bool IsFramelessWindow(NSView* view) { NSWindow* nswindow = [view window]; if (![nswindow respondsToSelector:@selector(shell)]) return false; NativeWindow* window = [static_cast<ElectronNSWindow*>(nswindow) shell]; return window && !window->has_frame(); } IMP original_set_frame_size = nullptr; IMP original_view_did_move_to_superview = nullptr; // This method is directly called by NSWindow during a window resize on OSX // 10.10.0, beta 2. We must override it to prevent the content view from // shrinking. void SetFrameSize(NSView* self, SEL _cmd, NSSize size) { if (!IsFramelessWindow(self)) { auto original = reinterpret_cast<decltype(&SetFrameSize)>(original_set_frame_size); return original(self, _cmd, size); } // For frameless window, resize the view to cover full window. if ([self superview]) size = [[self superview] bounds].size; auto super_impl = reinterpret_cast<decltype(&SetFrameSize)>( [[self superclass] instanceMethodForSelector:_cmd]); super_impl(self, _cmd, size); } // The contentView gets moved around during certain full-screen operations. // This is less than ideal, and should eventually be removed. void ViewDidMoveToSuperview(NSView* self, SEL _cmd) { if (!IsFramelessWindow(self)) { // [BridgedContentView viewDidMoveToSuperview]; auto original = reinterpret_cast<decltype(&ViewDidMoveToSuperview)>( original_view_did_move_to_superview); if (original) original(self, _cmd); return; } [self setFrame:[[self superview] bounds]]; } // -[NSWindow orderWindow] does not handle reordering for children // windows. Their order is fixed to the attachment order (the last attached // window is on the top). Therefore, work around it by re-parenting in our // desired order. void ReorderChildWindowAbove(NSWindow* child_window, NSWindow* other_window) { NSWindow* parent = [child_window parentWindow]; DCHECK(parent); // `ordered_children` sorts children windows back to front. NSArray<NSWindow*>* children = [[child_window parentWindow] childWindows]; std::vector<std::pair<NSInteger, NSWindow*>> ordered_children; for (NSWindow* child in children) ordered_children.push_back({[child orderedIndex], child}); std::sort(ordered_children.begin(), ordered_children.end(), std::greater<>()); // If `other_window` is nullptr, place `child_window` in front of // all other children windows. if (other_window == nullptr) other_window = ordered_children.back().second; if (child_window == other_window) return; for (NSWindow* child in children) [parent removeChildWindow:child]; const bool relative_to_parent = parent == other_window; if (relative_to_parent) [parent addChildWindow:child_window ordered:NSWindowAbove]; // Re-parent children windows in the desired order. for (auto [ordered_index, child] : ordered_children) { if (child != child_window && child != other_window) { [parent addChildWindow:child ordered:NSWindowAbove]; } else if (child == other_window && !relative_to_parent) { [parent addChildWindow:other_window ordered:NSWindowAbove]; [parent addChildWindow:child_window ordered:NSWindowAbove]; } } } } // namespace NativeWindowMac::NativeWindowMac(const gin_helper::Dictionary& options, NativeWindow* parent) : NativeWindow(options, parent), root_view_(new RootViewMac(this)) { ui::NativeTheme::GetInstanceForNativeUi()->AddObserver(this); display::Screen::GetScreen()->AddObserver(this); int width = 800, height = 600; options.Get(options::kWidth, &width); options.Get(options::kHeight, &height); NSRect main_screen_rect = [[[NSScreen screens] firstObject] frame]; gfx::Rect bounds(round((NSWidth(main_screen_rect) - width) / 2), round((NSHeight(main_screen_rect) - height) / 2), width, height); bool resizable = true; options.Get(options::kResizable, &resizable); options.Get(options::kZoomToPageWidth, &zoom_to_page_width_); options.Get(options::kSimpleFullScreen, &always_simple_fullscreen_); options.GetOptional(options::kTrafficLightPosition, &traffic_light_position_); options.Get(options::kVisualEffectState, &visual_effect_state_); if (options.Has(options::kFullscreenWindowTitle)) { EmitWarning( node::Environment::GetCurrent(JavascriptEnvironment::GetIsolate()), "\"fullscreenWindowTitle\" option has been deprecated and is " "no-op now.", "electron"); } bool minimizable = true; options.Get(options::kMinimizable, &minimizable); bool maximizable = true; options.Get(options::kMaximizable, &maximizable); bool closable = true; options.Get(options::kClosable, &closable); std::string tabbingIdentifier; options.Get(options::kTabbingIdentifier, &tabbingIdentifier); std::string windowType; options.Get(options::kType, &windowType); bool hiddenInMissionControl = false; options.Get(options::kHiddenInMissionControl, &hiddenInMissionControl); bool useStandardWindow = true; // eventually deprecate separate "standardWindow" option in favor of // standard / textured window types options.Get(options::kStandardWindow, &useStandardWindow); if (windowType == "textured") { useStandardWindow = false; } // The window without titlebar is treated the same with frameless window. if (title_bar_style_ != TitleBarStyle::kNormal) set_has_frame(false); NSUInteger styleMask = NSWindowStyleMaskTitled; // The NSWindowStyleMaskFullSizeContentView style removes rounded corners // for frameless window. bool rounded_corner = true; options.Get(options::kRoundedCorners, &rounded_corner); if (!rounded_corner && !has_frame()) styleMask = NSWindowStyleMaskBorderless; if (minimizable) styleMask |= NSWindowStyleMaskMiniaturizable; if (closable) styleMask |= NSWindowStyleMaskClosable; if (resizable) styleMask |= NSWindowStyleMaskResizable; if (!useStandardWindow || transparent() || !has_frame()) styleMask |= NSWindowStyleMaskTexturedBackground; // Create views::Widget and assign window_ with it. // TODO(zcbenz): Get rid of the window_ in future. 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.native_widget = new ElectronNativeWidgetMac(this, windowType, styleMask, widget()); widget()->Init(std::move(params)); SetCanResize(resizable); window_ = static_cast<ElectronNSWindow*>( widget()->GetNativeWindow().GetNativeNSWindow()); RegisterDeleteDelegateCallback(base::BindOnce( [](NativeWindowMac* window) { if (window->window_) window->window_ = nil; if (window->buttons_proxy_) window->buttons_proxy_ = nil; }, this)); [window_ setEnableLargerThanScreen:enable_larger_than_screen()]; window_delegate_ = [[ElectronNSWindowDelegate alloc] initWithShell:this]; [window_ setDelegate:window_delegate_]; // Only use native parent window for non-modal windows. if (parent && !is_modal()) { SetParentWindow(parent); } if (transparent()) { // Setting the background color to clear will also hide the shadow. [window_ setBackgroundColor:[NSColor clearColor]]; } if (windowType == "desktop") { [window_ setLevel:kCGDesktopWindowLevel - 1]; [window_ setDisableKeyOrMainWindow:YES]; [window_ setCollectionBehavior:(NSWindowCollectionBehaviorCanJoinAllSpaces | NSWindowCollectionBehaviorStationary | NSWindowCollectionBehaviorIgnoresCycle)]; } if (windowType == "panel") { [window_ setLevel:NSFloatingWindowLevel]; } bool focusable; if (options.Get(options::kFocusable, &focusable) && !focusable) [window_ setDisableKeyOrMainWindow:YES]; if (transparent() || !has_frame()) { // Don't show title bar. [window_ setTitlebarAppearsTransparent:YES]; [window_ setTitleVisibility:NSWindowTitleHidden]; // Remove non-transparent corners, see // https://github.com/electron/electron/issues/517. [window_ setOpaque:NO]; // Show window buttons if titleBarStyle is not "normal". if (title_bar_style_ == TitleBarStyle::kNormal) { InternalSetWindowButtonVisibility(false); } else { buttons_proxy_ = [[WindowButtonsProxy alloc] initWithWindow:window_]; [buttons_proxy_ setHeight:titlebar_overlay_height()]; if (traffic_light_position_) { [buttons_proxy_ setMargin:*traffic_light_position_]; } else if (title_bar_style_ == TitleBarStyle::kHiddenInset) { // For macOS >= 11, while this value does not match official macOS apps // like Safari or Notes, it matches titleBarStyle's old implementation // before Electron <= 12. [buttons_proxy_ setMargin:gfx::Point(12, 11)]; } if (title_bar_style_ == TitleBarStyle::kCustomButtonsOnHover) { [buttons_proxy_ setShowOnHover:YES]; } else { // customButtonsOnHover does not show buttons initially. InternalSetWindowButtonVisibility(true); } } } // Create a tab only if tabbing identifier is specified and window has // a native title bar. if (tabbingIdentifier.empty() || transparent() || !has_frame()) { [window_ setTabbingMode:NSWindowTabbingModeDisallowed]; } else { [window_ setTabbingIdentifier:base::SysUTF8ToNSString(tabbingIdentifier)]; } // Resize to content bounds. bool use_content_size = false; options.Get(options::kUseContentSize, &use_content_size); if (!has_frame() || use_content_size) SetContentSize(gfx::Size(width, height)); // Enable the NSView to accept first mouse event. bool acceptsFirstMouse = false; options.Get(options::kAcceptFirstMouse, &acceptsFirstMouse); [window_ setAcceptsFirstMouse:acceptsFirstMouse]; // Disable auto-hiding cursor. bool disableAutoHideCursor = false; options.Get(options::kDisableAutoHideCursor, &disableAutoHideCursor); [window_ setDisableAutoHideCursor:disableAutoHideCursor]; SetHiddenInMissionControl(hiddenInMissionControl); // Set maximizable state last to ensure zoom button does not get reset // by calls to other APIs. SetMaximizable(maximizable); // Default content view. SetContentView(new views::View()); AddContentViewLayers(); UpdateWindowOriginalFrame(); original_level_ = [window_ level]; } NativeWindowMac::~NativeWindowMac() = default; void NativeWindowMac::SetContentView(views::View* view) { views::View* root_view = GetContentsView(); if (content_view()) root_view->RemoveChildView(content_view()); set_content_view(view); root_view->AddChildView(content_view()); root_view->Layout(); } void NativeWindowMac::Close() { if (!IsClosable()) { WindowList::WindowCloseCancelled(this); return; } if (fullscreen_transition_state() != FullScreenTransitionState::kNone) { SetHasDeferredWindowClose(true); return; } // Ensure we're detached from the parent window before closing. RemoveChildFromParentWindow(); while (!child_windows_.empty()) { auto* child = child_windows_.back(); child->RemoveChildFromParentWindow(); } // If a sheet is attached to the window when we call // [window_ performClose:nil], the window won't close properly // even after the user has ended the sheet. // Ensure it's closed before calling [window_ performClose:nil]. if ([window_ attachedSheet]) [window_ endSheet:[window_ attachedSheet]]; [window_ performClose:nil]; // Closing a sheet doesn't trigger windowShouldClose, // so we need to manually call it ourselves here. if (is_modal() && parent() && IsVisible()) { NotifyWindowCloseButtonClicked(); } } void NativeWindowMac::CloseImmediately() { // Ensure we're detached from the parent window before closing. RemoveChildFromParentWindow(); while (!child_windows_.empty()) { auto* child = child_windows_.back(); child->RemoveChildFromParentWindow(); } [window_ close]; } void NativeWindowMac::Focus(bool focus) { if (!IsVisible()) return; if (focus) { [[NSApplication sharedApplication] activateIgnoringOtherApps:NO]; [window_ makeKeyAndOrderFront:nil]; } else { [window_ orderOut:nil]; [window_ orderBack:nil]; } } bool NativeWindowMac::IsFocused() { return [window_ isKeyWindow]; } void NativeWindowMac::Show() { if (is_modal() && parent()) { NSWindow* window = parent()->GetNativeWindow().GetNativeNSWindow(); if ([window_ sheetParent] == nil) [window beginSheet:window_ completionHandler:^(NSModalResponse){ }]; return; } // Reattach the window to the parent to actually show it. if (parent()) InternalSetParentWindow(parent(), true); // This method is supposed to put focus on window, however if the app does not // have focus then "makeKeyAndOrderFront" will only show the window. [NSApp activateIgnoringOtherApps:YES]; [window_ makeKeyAndOrderFront:nil]; } void NativeWindowMac::ShowInactive() { // Reattach the window to the parent to actually show it. if (parent()) InternalSetParentWindow(parent(), true); [window_ orderFrontRegardless]; } void NativeWindowMac::Hide() { // If a sheet is attached to the window when we call [window_ orderOut:nil], // the sheet won't be able to show again on the same window. // Ensure it's closed before calling [window_ orderOut:nil]. if ([window_ attachedSheet]) [window_ endSheet:[window_ attachedSheet]]; if (is_modal() && parent()) { [window_ orderOut:nil]; [parent()->GetNativeWindow().GetNativeNSWindow() endSheet:window_]; return; } DetachChildren(); // Detach the window from the parent before. if (parent()) InternalSetParentWindow(parent(), false); [window_ orderOut:nil]; } bool NativeWindowMac::IsVisible() { bool occluded = [window_ occlusionState] == NSWindowOcclusionStateVisible; return [window_ isVisible] && !occluded && !IsMinimized(); } bool NativeWindowMac::IsEnabled() { return [window_ attachedSheet] == nil; } void NativeWindowMac::SetEnabled(bool enable) { if (!enable) { NSRect frame = [window_ frame]; NSWindow* window = [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, frame.size.width, frame.size.height) styleMask:NSWindowStyleMaskTitled backing:NSBackingStoreBuffered defer:NO]; [window setAlphaValue:0.5]; [window_ beginSheet:window completionHandler:^(NSModalResponse returnCode) { NSLog(@"main window disabled"); return; }]; } else if ([window_ attachedSheet]) { [window_ endSheet:[window_ attachedSheet]]; } } void NativeWindowMac::Maximize() { const bool is_visible = [window_ isVisible]; if (IsMaximized()) { if (!is_visible) ShowInactive(); return; } // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); [window_ zoom:nil]; if (!is_visible) { ShowInactive(); NotifyWindowMaximize(); } } void NativeWindowMac::Unmaximize() { // Bail if the last user set bounds were the same size as the window // screen (e.g. the user set the window to maximized via setBounds) // // Per docs during zoom: // > If there’s no saved user state because there has been no previous // > zoom,the size and location of the window don’t change. // // However, in classic Apple fashion, this is not the case in practice, // and the frame inexplicably becomes very tiny. We should prevent // zoom from being called if the window is being unmaximized and its // unmaximized window bounds are themselves functionally maximized. if (!IsMaximized() || user_set_bounds_maximized_) return; [window_ zoom:nil]; } bool NativeWindowMac::IsMaximized() { // It's possible for [window_ isZoomed] to be true // when the window is minimized or fullscreened. if (IsMinimized() || IsFullscreen()) return false; if (HasStyleMask(NSWindowStyleMaskResizable) != 0) return [window_ isZoomed]; NSRect rectScreen = GetAspectRatio() > 0.0 ? default_frame_for_zoom() : [[NSScreen mainScreen] visibleFrame]; return NSEqualRects([window_ frame], rectScreen); } void NativeWindowMac::Minimize() { if (IsMinimized()) return; // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); [window_ miniaturize:nil]; } void NativeWindowMac::Restore() { [window_ deminiaturize:nil]; } bool NativeWindowMac::IsMinimized() { return [window_ isMiniaturized]; } bool NativeWindowMac::HandleDeferredClose() { if (has_deferred_window_close_) { SetHasDeferredWindowClose(false); Close(); return true; } return false; } void NativeWindowMac::RemoveChildWindow(NativeWindow* child) { child_windows_.remove_if([&child](NativeWindow* w) { return (w == child); }); [window_ removeChildWindow:child->GetNativeWindow().GetNativeNSWindow()]; } void NativeWindowMac::RemoveChildFromParentWindow() { if (parent() && !is_modal()) { parent()->RemoveChildWindow(this); NativeWindow::SetParentWindow(nullptr); } } void NativeWindowMac::AttachChildren() { for (auto* child : child_windows_) { auto* child_nswindow = child->GetNativeWindow().GetNativeNSWindow(); if ([child_nswindow parentWindow] == window_) continue; // Attaching a window as a child window resets its window level, so // save and restore it afterwards. NSInteger level = window_.level; [window_ addChildWindow:child_nswindow ordered:NSWindowAbove]; [window_ setLevel:level]; } } void NativeWindowMac::DetachChildren() { DCHECK(child_windows_.size() == [[window_ childWindows] count]); // Hide all children before hiding/minimizing the window. // NativeWidgetNSWindowBridge::NotifyVisibilityChangeDown() // will DCHECK otherwise. for (auto* child : child_windows_) { [child->GetNativeWindow().GetNativeNSWindow() orderOut:nil]; } } void NativeWindowMac::SetFullScreen(bool fullscreen) { if (!has_frame() && !HasStyleMask(NSWindowStyleMaskTitled)) return; // [NSWindow -toggleFullScreen] is an asynchronous operation, which means // that it's possible to call it while a fullscreen transition is currently // in process. This can create weird behavior (incl. phantom windows), // so we want to schedule a transition for when the current one has completed. if (fullscreen_transition_state() != FullScreenTransitionState::kNone) { if (!pending_transitions_.empty()) { bool last_pending = pending_transitions_.back(); // Only push new transitions if they're different than the last transition // in the queue. if (last_pending != fullscreen) pending_transitions_.push(fullscreen); } else { pending_transitions_.push(fullscreen); } return; } if (fullscreen == IsFullscreen() || !IsFullScreenable()) return; // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); // This needs to be set here because it can be the case that // SetFullScreen is called by a user before windowWillEnterFullScreen // or windowWillExitFullScreen are invoked, and so a potential transition // could be dropped. fullscreen_transition_state_ = fullscreen ? FullScreenTransitionState::kEntering : FullScreenTransitionState::kExiting; [window_ toggleFullScreenMode:nil]; } bool NativeWindowMac::IsFullscreen() const { return HasStyleMask(NSWindowStyleMaskFullScreen); } void NativeWindowMac::SetBounds(const gfx::Rect& bounds, bool animate) { // Do nothing if in fullscreen mode. if (IsFullscreen()) return; // Check size constraints since setFrame does not check it. gfx::Size size = bounds.size(); size.SetToMax(GetMinimumSize()); gfx::Size max_size = GetMaximumSize(); if (!max_size.IsEmpty()) size.SetToMin(max_size); NSRect cocoa_bounds = NSMakeRect(bounds.x(), 0, size.width(), size.height()); // Flip coordinates based on the primary screen. NSScreen* screen = [[NSScreen screens] firstObject]; cocoa_bounds.origin.y = NSHeight([screen frame]) - size.height() - bounds.y(); [window_ setFrame:cocoa_bounds display:YES animate:animate]; user_set_bounds_maximized_ = IsMaximized() ? true : false; UpdateWindowOriginalFrame(); } gfx::Rect NativeWindowMac::GetBounds() { NSRect frame = [window_ frame]; gfx::Rect bounds(frame.origin.x, 0, NSWidth(frame), NSHeight(frame)); NSScreen* screen = [[NSScreen screens] firstObject]; bounds.set_y(NSHeight([screen frame]) - NSMaxY(frame)); return bounds; } bool NativeWindowMac::IsNormal() { return NativeWindow::IsNormal() && !IsSimpleFullScreen(); } gfx::Rect NativeWindowMac::GetNormalBounds() { if (IsNormal()) { return GetBounds(); } NSRect frame = original_frame_; gfx::Rect bounds(frame.origin.x, 0, NSWidth(frame), NSHeight(frame)); NSScreen* screen = [[NSScreen screens] firstObject]; bounds.set_y(NSHeight([screen frame]) - NSMaxY(frame)); return bounds; // Works on OS_WIN ! // return widget()->GetRestoredBounds(); } void NativeWindowMac::SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints) { auto convertSize = [this](const gfx::Size& size) { // Our frameless window still has titlebar attached, so setting contentSize // will result in actual content size being larger. if (!has_frame()) { NSRect frame = NSMakeRect(0, 0, size.width(), size.height()); NSRect content = [window_ originalContentRectForFrameRect:frame]; return content.size; } else { return NSMakeSize(size.width(), size.height()); } }; NSView* content = [window_ contentView]; if (size_constraints.HasMinimumSize()) { NSSize min_size = convertSize(size_constraints.GetMinimumSize()); [window_ setContentMinSize:[content convertSize:min_size toView:nil]]; } if (size_constraints.HasMaximumSize()) { NSSize max_size = convertSize(size_constraints.GetMaximumSize()); [window_ setContentMaxSize:[content convertSize:max_size toView:nil]]; } NativeWindow::SetContentSizeConstraints(size_constraints); } bool NativeWindowMac::MoveAbove(const std::string& sourceId) { const content::DesktopMediaID id = content::DesktopMediaID::Parse(sourceId); if (id.type != content::DesktopMediaID::TYPE_WINDOW) return false; // Check if the window source is valid. const CGWindowID window_id = id.id; if (!webrtc::GetWindowOwnerPid(window_id)) return false; if (!parent()) { [window_ orderWindow:NSWindowAbove relativeTo:window_id]; } else { NSWindow* other_window = [NSApp windowWithWindowNumber:window_id]; ReorderChildWindowAbove(window_, other_window); } return true; } void NativeWindowMac::MoveTop() { if (!parent()) [window_ orderWindow:NSWindowAbove relativeTo:0]; else ReorderChildWindowAbove(window_, nullptr); } void NativeWindowMac::SetResizable(bool resizable) { ScopedDisableResize disable_resize; SetStyleMask(resizable, NSWindowStyleMaskResizable); // Right now, resizable and fullscreenable are decoupled in // documentation and on Windows/Linux. Chromium disables // fullscreenability if resizability is false on macOS as well // as disabling the maximize traffic light unless the window // is both resizable and maximizable. To work around this, we want // to match behavior on other platforms by disabiliting the maximize // button but keeping fullscreenability enabled. // TODO(codebytere): refactor this once we have a better solution. SetCanResize(resizable); if (!resizable) { SetFullScreenable(true); [[window_ standardWindowButton:NSWindowZoomButton] setEnabled:false]; } else { SetFullScreenable(true); [[window_ standardWindowButton:NSWindowZoomButton] setEnabled:IsFullScreenable()]; } } bool NativeWindowMac::IsResizable() { bool in_fs_transition = fullscreen_transition_state() != FullScreenTransitionState::kNone; bool has_rs_mask = HasStyleMask(NSWindowStyleMaskResizable); return has_rs_mask && !IsFullscreen() && !in_fs_transition; } void NativeWindowMac::SetMovable(bool movable) { [window_ setMovable:movable]; } bool NativeWindowMac::IsMovable() { return [window_ isMovable]; } void NativeWindowMac::SetMinimizable(bool minimizable) { SetStyleMask(minimizable, NSWindowStyleMaskMiniaturizable); } bool NativeWindowMac::IsMinimizable() { return HasStyleMask(NSWindowStyleMaskMiniaturizable); } void NativeWindowMac::SetMaximizable(bool maximizable) { maximizable_ = maximizable; [[window_ standardWindowButton:NSWindowZoomButton] setEnabled:maximizable]; } bool NativeWindowMac::IsMaximizable() { return [[window_ standardWindowButton:NSWindowZoomButton] isEnabled]; } void NativeWindowMac::SetFullScreenable(bool fullscreenable) { SetCollectionBehavior(fullscreenable, NSWindowCollectionBehaviorFullScreenPrimary); // On EL Capitan this flag is required to hide fullscreen button. SetCollectionBehavior(!fullscreenable, NSWindowCollectionBehaviorFullScreenAuxiliary); } bool NativeWindowMac::IsFullScreenable() { NSUInteger collectionBehavior = [window_ collectionBehavior]; return collectionBehavior & NSWindowCollectionBehaviorFullScreenPrimary; } void NativeWindowMac::SetClosable(bool closable) { SetStyleMask(closable, NSWindowStyleMaskClosable); } bool NativeWindowMac::IsClosable() { return HasStyleMask(NSWindowStyleMaskClosable); } void NativeWindowMac::SetAlwaysOnTop(ui::ZOrderLevel z_order, const std::string& level_name, int relative_level) { if (z_order == ui::ZOrderLevel::kNormal) { SetWindowLevel(NSNormalWindowLevel); return; } int level = NSNormalWindowLevel; if (level_name == "floating") { level = NSFloatingWindowLevel; } else if (level_name == "torn-off-menu") { level = NSTornOffMenuWindowLevel; } else if (level_name == "modal-panel") { level = NSModalPanelWindowLevel; } else if (level_name == "main-menu") { level = NSMainMenuWindowLevel; } else if (level_name == "status") { level = NSStatusWindowLevel; } else if (level_name == "pop-up-menu") { level = NSPopUpMenuWindowLevel; } else if (level_name == "screen-saver") { level = NSScreenSaverWindowLevel; } SetWindowLevel(level + relative_level); } std::string NativeWindowMac::GetAlwaysOnTopLevel() { std::string level_name = "normal"; int level = [window_ level]; if (level == NSFloatingWindowLevel) { level_name = "floating"; } else if (level == NSTornOffMenuWindowLevel) { level_name = "torn-off-menu"; } else if (level == NSModalPanelWindowLevel) { level_name = "modal-panel"; } else if (level == NSMainMenuWindowLevel) { level_name = "main-menu"; } else if (level == NSStatusWindowLevel) { level_name = "status"; } else if (level == NSPopUpMenuWindowLevel) { level_name = "pop-up-menu"; } else if (level == NSScreenSaverWindowLevel) { level_name = "screen-saver"; } return level_name; } void NativeWindowMac::SetWindowLevel(int unbounded_level) { int level = std::min( std::max(unbounded_level, CGWindowLevelForKey(kCGMinimumWindowLevelKey)), CGWindowLevelForKey(kCGMaximumWindowLevelKey)); ui::ZOrderLevel z_order_level = level == NSNormalWindowLevel ? ui::ZOrderLevel::kNormal : ui::ZOrderLevel::kFloatingWindow; bool did_z_order_level_change = z_order_level != GetZOrderLevel(); was_maximizable_ = IsMaximizable(); // We need to explicitly keep the NativeWidget up to date, since it stores the // window level in a local variable, rather than reading it from the NSWindow. // Unfortunately, it results in a second setLevel call. It's not ideal, but we // don't expect this to cause any user-visible jank. widget()->SetZOrderLevel(z_order_level); [window_ setLevel:level]; // Set level will make the zoom button revert to default, probably // a bug of Cocoa or macOS. SetMaximizable(was_maximizable_); // This must be notified at the very end or IsAlwaysOnTop // will not yet have been updated to reflect the new status if (did_z_order_level_change) NativeWindow::NotifyWindowAlwaysOnTopChanged(); } ui::ZOrderLevel NativeWindowMac::GetZOrderLevel() { return widget()->GetZOrderLevel(); } void NativeWindowMac::Center() { [window_ center]; } void NativeWindowMac::Invalidate() { [[window_ contentView] setNeedsDisplay:YES]; } void NativeWindowMac::SetTitle(const std::string& title) { [window_ setTitle:base::SysUTF8ToNSString(title)]; if (buttons_proxy_) [buttons_proxy_ redraw]; } std::string NativeWindowMac::GetTitle() { return base::SysNSStringToUTF8([window_ title]); } void NativeWindowMac::FlashFrame(bool flash) { if (flash) { attention_request_id_ = [NSApp requestUserAttention:NSInformationalRequest]; } else { [NSApp cancelUserAttentionRequest:attention_request_id_]; attention_request_id_ = 0; } } void NativeWindowMac::SetSkipTaskbar(bool skip) {} bool NativeWindowMac::IsExcludedFromShownWindowsMenu() { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); return [window isExcludedFromWindowsMenu]; } void NativeWindowMac::SetExcludedFromShownWindowsMenu(bool excluded) { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); [window setExcludedFromWindowsMenu:excluded]; } void NativeWindowMac::OnDisplayMetricsChanged(const display::Display& display, uint32_t changed_metrics) { // We only want to force screen recalibration if we're in simpleFullscreen // mode. if (!is_simple_fullscreen_) return; content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&NativeWindow::UpdateFrame, GetWeakPtr())); } void NativeWindowMac::SetSimpleFullScreen(bool simple_fullscreen) { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); if (simple_fullscreen && !is_simple_fullscreen_) { is_simple_fullscreen_ = true; // Take note of the current window size and level if (IsNormal()) { UpdateWindowOriginalFrame(); original_level_ = [window_ level]; } simple_fullscreen_options_ = [NSApp currentSystemPresentationOptions]; simple_fullscreen_mask_ = [window styleMask]; // We can simulate the pre-Lion fullscreen by auto-hiding the dock and menu // bar NSApplicationPresentationOptions options = NSApplicationPresentationAutoHideDock | NSApplicationPresentationAutoHideMenuBar; [NSApp setPresentationOptions:options]; was_maximizable_ = IsMaximizable(); was_movable_ = IsMovable(); NSRect fullscreenFrame = [window.screen frame]; // If our app has dock hidden, set the window level higher so another app's // menu bar doesn't appear on top of our fullscreen app. if ([[NSRunningApplication currentApplication] activationPolicy] != NSApplicationActivationPolicyRegular) { window.level = NSPopUpMenuWindowLevel; } // Always hide the titlebar in simple fullscreen mode. // // Note that we must remove the NSWindowStyleMaskTitled style instead of // using the [window_ setTitleVisibility:], as the latter would leave the // window with rounded corners. SetStyleMask(false, NSWindowStyleMaskTitled); if (!window_button_visibility_.has_value()) { // Lets keep previous behaviour - hide window controls in titled // fullscreen mode when not specified otherwise. InternalSetWindowButtonVisibility(false); } [window setFrame:fullscreenFrame display:YES animate:YES]; // Fullscreen windows can't be resized, minimized, maximized, or moved SetMinimizable(false); SetResizable(false); SetMaximizable(false); SetMovable(false); } else if (!simple_fullscreen && is_simple_fullscreen_) { is_simple_fullscreen_ = false; [window setFrame:original_frame_ display:YES animate:YES]; window.level = original_level_; [NSApp setPresentationOptions:simple_fullscreen_options_]; // Restore original style mask ScopedDisableResize disable_resize; [window_ setStyleMask:simple_fullscreen_mask_]; // Restore window manipulation abilities SetMaximizable(was_maximizable_); SetMovable(was_movable_); // Restore default window controls visibility state. if (!window_button_visibility_.has_value()) { bool visibility; if (has_frame()) visibility = true; else visibility = title_bar_style_ != TitleBarStyle::kNormal; InternalSetWindowButtonVisibility(visibility); } if (buttons_proxy_) [buttons_proxy_ redraw]; } } bool NativeWindowMac::IsSimpleFullScreen() { return is_simple_fullscreen_; } void NativeWindowMac::SetKiosk(bool kiosk) { if (kiosk && !is_kiosk_) { kiosk_options_ = [NSApp currentSystemPresentationOptions]; NSApplicationPresentationOptions options = NSApplicationPresentationHideDock | NSApplicationPresentationHideMenuBar | NSApplicationPresentationDisableAppleMenu | NSApplicationPresentationDisableProcessSwitching | NSApplicationPresentationDisableForceQuit | NSApplicationPresentationDisableSessionTermination | NSApplicationPresentationDisableHideApplication; [NSApp setPresentationOptions:options]; is_kiosk_ = true; fullscreen_before_kiosk_ = IsFullscreen(); if (!fullscreen_before_kiosk_) SetFullScreen(true); } else if (!kiosk && is_kiosk_) { is_kiosk_ = false; if (!fullscreen_before_kiosk_) SetFullScreen(false); // Set presentation options *after* asynchronously exiting // fullscreen to ensure they take effect. [NSApp setPresentationOptions:kiosk_options_]; } } bool NativeWindowMac::IsKiosk() { return is_kiosk_; } void NativeWindowMac::SetBackgroundColor(SkColor color) { base::ScopedCFTypeRef<CGColorRef> cgcolor( skia::CGColorCreateFromSkColor(color)); [[[window_ contentView] layer] setBackgroundColor:cgcolor]; } SkColor NativeWindowMac::GetBackgroundColor() { CGColorRef color = [[[window_ contentView] layer] backgroundColor]; if (!color) return SK_ColorTRANSPARENT; return skia::CGColorRefToSkColor(color); } void NativeWindowMac::SetHasShadow(bool has_shadow) { [window_ setHasShadow:has_shadow]; } bool NativeWindowMac::HasShadow() { return [window_ hasShadow]; } void NativeWindowMac::InvalidateShadow() { [window_ invalidateShadow]; } void NativeWindowMac::SetOpacity(const double opacity) { const double boundedOpacity = std::clamp(opacity, 0.0, 1.0); [window_ setAlphaValue:boundedOpacity]; } double NativeWindowMac::GetOpacity() { return [window_ alphaValue]; } void NativeWindowMac::SetRepresentedFilename(const std::string& filename) { [window_ setRepresentedFilename:base::SysUTF8ToNSString(filename)]; if (buttons_proxy_) [buttons_proxy_ redraw]; } std::string NativeWindowMac::GetRepresentedFilename() { return base::SysNSStringToUTF8([window_ representedFilename]); } void NativeWindowMac::SetDocumentEdited(bool edited) { [window_ setDocumentEdited:edited]; if (buttons_proxy_) [buttons_proxy_ redraw]; } bool NativeWindowMac::IsDocumentEdited() { return [window_ isDocumentEdited]; } bool NativeWindowMac::IsHiddenInMissionControl() { NSUInteger collectionBehavior = [window_ collectionBehavior]; return collectionBehavior & NSWindowCollectionBehaviorTransient; } void NativeWindowMac::SetHiddenInMissionControl(bool hidden) { SetCollectionBehavior(hidden, NSWindowCollectionBehaviorTransient); } void NativeWindowMac::SetIgnoreMouseEvents(bool ignore, bool forward) { [window_ setIgnoresMouseEvents:ignore]; if (!ignore) { SetForwardMouseMessages(NO); } else { SetForwardMouseMessages(forward); } } void NativeWindowMac::SetContentProtection(bool enable) { [window_ setSharingType:enable ? NSWindowSharingNone : NSWindowSharingReadOnly]; } void NativeWindowMac::SetFocusable(bool focusable) { // No known way to unfocus the window if it had the focus. Here we do not // want to call Focus(false) because it moves the window to the back, i.e. // at the bottom in term of z-order. [window_ setDisableKeyOrMainWindow:!focusable]; } bool NativeWindowMac::IsFocusable() { return ![window_ disableKeyOrMainWindow]; } void NativeWindowMac::AddBrowserView(NativeBrowserView* view) { [CATransaction begin]; [CATransaction setDisableActions:YES]; if (!view) { [CATransaction commit]; return; } add_browser_view(view); if (view->GetInspectableWebContentsView()) { auto* native_view = view->GetInspectableWebContentsView() ->GetNativeView() .GetNativeNSView(); [[window_ contentView] addSubview:native_view positioned:NSWindowAbove relativeTo:nil]; native_view.hidden = NO; } [CATransaction commit]; } void NativeWindowMac::RemoveBrowserView(NativeBrowserView* view) { [CATransaction begin]; [CATransaction setDisableActions:YES]; if (!view) { [CATransaction commit]; return; } if (view->GetInspectableWebContentsView()) [view->GetInspectableWebContentsView()->GetNativeView().GetNativeNSView() removeFromSuperview]; remove_browser_view(view); [CATransaction commit]; } void NativeWindowMac::SetTopBrowserView(NativeBrowserView* view) { [CATransaction begin]; [CATransaction setDisableActions:YES]; if (!view) { [CATransaction commit]; return; } remove_browser_view(view); add_browser_view(view); if (view->GetInspectableWebContentsView()) { auto* native_view = view->GetInspectableWebContentsView() ->GetNativeView() .GetNativeNSView(); [[window_ contentView] addSubview:native_view positioned:NSWindowAbove relativeTo:nil]; native_view.hidden = NO; } [CATransaction commit]; } void NativeWindowMac::SetParentWindow(NativeWindow* parent) { InternalSetParentWindow(parent, IsVisible()); } gfx::NativeView NativeWindowMac::GetNativeView() const { return [window_ contentView]; } gfx::NativeWindow NativeWindowMac::GetNativeWindow() const { return window_; } gfx::AcceleratedWidget NativeWindowMac::GetAcceleratedWidget() const { return [window_ windowNumber]; } content::DesktopMediaID NativeWindowMac::GetDesktopMediaID() const { auto desktop_media_id = content::DesktopMediaID( content::DesktopMediaID::TYPE_WINDOW, GetAcceleratedWidget()); // c.f. // https://source.chromium.org/chromium/chromium/src/+/main:chrome/browser/media/webrtc/native_desktop_media_list.cc;l=775-780;drc=79502ab47f61bff351426f57f576daef02b1a8dc // Refs https://github.com/electron/electron/pull/30507 // TODO(deepak1556): Match upstream for `kWindowCaptureMacV2` #if 0 if (remote_cocoa::ScopedCGWindowID::Get(desktop_media_id.id)) { desktop_media_id.window_id = desktop_media_id.id; } #endif return desktop_media_id; } NativeWindowHandle NativeWindowMac::GetNativeWindowHandle() const { return [window_ contentView]; } void NativeWindowMac::SetProgressBar(double progress, const NativeWindow::ProgressState state) { NSDockTile* dock_tile = [NSApp dockTile]; // Sometimes macOS would install a default contentView for dock, we must // verify whether NSProgressIndicator has been installed. bool first_time = !dock_tile.contentView || [[dock_tile.contentView subviews] count] == 0 || ![[[dock_tile.contentView subviews] lastObject] isKindOfClass:[NSProgressIndicator class]]; // For the first time API invoked, we need to create a ContentView in // DockTile. if (first_time) { NSImageView* image_view = [[NSImageView alloc] init]; [image_view setImage:[NSApp applicationIconImage]]; [dock_tile setContentView:image_view]; NSRect frame = NSMakeRect(0.0f, 0.0f, dock_tile.size.width, 15.0); NSProgressIndicator* progress_indicator = [[ElectronProgressBar alloc] initWithFrame:frame]; [progress_indicator setStyle:NSProgressIndicatorStyleBar]; [progress_indicator setIndeterminate:NO]; [progress_indicator setBezeled:YES]; [progress_indicator setMinValue:0]; [progress_indicator setMaxValue:1]; [progress_indicator setHidden:NO]; [dock_tile.contentView addSubview:progress_indicator]; } NSProgressIndicator* progress_indicator = static_cast<NSProgressIndicator*>( [[[dock_tile contentView] subviews] lastObject]); if (progress < 0) { [progress_indicator setHidden:YES]; } else if (progress > 1) { [progress_indicator setHidden:NO]; [progress_indicator setIndeterminate:YES]; [progress_indicator setDoubleValue:1]; } else { [progress_indicator setHidden:NO]; [progress_indicator setDoubleValue:progress]; } [dock_tile display]; } void NativeWindowMac::SetOverlayIcon(const gfx::Image& overlay, const std::string& description) {} void NativeWindowMac::SetVisibleOnAllWorkspaces(bool visible, bool visibleOnFullScreen, bool skipTransformProcessType) { // In order for NSWindows to be visible on fullscreen we need to invoke // app.dock.hide() since Apple changed the underlying functionality of // NSWindows starting with 10.14 to disallow NSWindows from floating on top of // fullscreen apps. if (!skipTransformProcessType) { if (visibleOnFullScreen) { Browser::Get()->DockHide(); } else { Browser::Get()->DockShow(JavascriptEnvironment::GetIsolate()); } } SetCollectionBehavior(visible, NSWindowCollectionBehaviorCanJoinAllSpaces); SetCollectionBehavior(visibleOnFullScreen, NSWindowCollectionBehaviorFullScreenAuxiliary); } bool NativeWindowMac::IsVisibleOnAllWorkspaces() { NSUInteger collectionBehavior = [window_ collectionBehavior]; return collectionBehavior & NSWindowCollectionBehaviorCanJoinAllSpaces; } void NativeWindowMac::SetAutoHideCursor(bool auto_hide) { [window_ setDisableAutoHideCursor:!auto_hide]; } void NativeWindowMac::UpdateVibrancyRadii(bool fullscreen) { NSVisualEffectView* vibrantView = [window_ vibrantView]; if (vibrantView != nil && !vibrancy_type_.empty()) { const bool no_rounded_corner = !HasStyleMask(NSWindowStyleMaskTitled); if (!has_frame() && !is_modal() && !no_rounded_corner) { CGFloat radius; if (fullscreen) { radius = 0.0f; } else if (@available(macOS 11.0, *)) { radius = 9.0f; } else { // Smaller corner radius on versions prior to Big Sur. radius = 5.0f; } CGFloat dimension = 2 * radius + 1; NSSize size = NSMakeSize(dimension, dimension); NSImage* maskImage = [NSImage imageWithSize:size flipped:NO drawingHandler:^BOOL(NSRect rect) { NSBezierPath* bezierPath = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [[NSColor blackColor] set]; [bezierPath fill]; return YES; }]; [maskImage setCapInsets:NSEdgeInsetsMake(radius, radius, radius, radius)]; [maskImage setResizingMode:NSImageResizingModeStretch]; [vibrantView setMaskImage:maskImage]; [window_ setCornerMask:maskImage]; } } } void NativeWindowMac::UpdateWindowOriginalFrame() { original_frame_ = [window_ frame]; } void NativeWindowMac::SetVibrancy(const std::string& type) { NSVisualEffectView* vibrantView = [window_ vibrantView]; if (type.empty()) { if (vibrantView == nil) return; [vibrantView removeFromSuperview]; [window_ setVibrantView:nil]; return; } NSVisualEffectMaterial vibrancyType{}; if (type == "titlebar") { vibrancyType = NSVisualEffectMaterialTitlebar; } else if (type == "selection") { vibrancyType = NSVisualEffectMaterialSelection; } else if (type == "menu") { vibrancyType = NSVisualEffectMaterialMenu; } else if (type == "popover") { vibrancyType = NSVisualEffectMaterialPopover; } else if (type == "sidebar") { vibrancyType = NSVisualEffectMaterialSidebar; } else if (type == "header") { vibrancyType = NSVisualEffectMaterialHeaderView; } else if (type == "sheet") { vibrancyType = NSVisualEffectMaterialSheet; } else if (type == "window") { vibrancyType = NSVisualEffectMaterialWindowBackground; } else if (type == "hud") { vibrancyType = NSVisualEffectMaterialHUDWindow; } else if (type == "fullscreen-ui") { vibrancyType = NSVisualEffectMaterialFullScreenUI; } else if (type == "tooltip") { vibrancyType = NSVisualEffectMaterialToolTip; } else if (type == "content") { vibrancyType = NSVisualEffectMaterialContentBackground; } else if (type == "under-window") { vibrancyType = NSVisualEffectMaterialUnderWindowBackground; } else if (type == "under-page") { vibrancyType = NSVisualEffectMaterialUnderPageBackground; } if (vibrancyType) { vibrancy_type_ = type; if (vibrantView == nil) { vibrantView = [[NSVisualEffectView alloc] initWithFrame:[[window_ contentView] bounds]]; [window_ setVibrantView:vibrantView]; [vibrantView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable]; [vibrantView setBlendingMode:NSVisualEffectBlendingModeBehindWindow]; if (visual_effect_state_ == VisualEffectState::kActive) { [vibrantView setState:NSVisualEffectStateActive]; } else if (visual_effect_state_ == VisualEffectState::kInactive) { [vibrantView setState:NSVisualEffectStateInactive]; } else { [vibrantView setState:NSVisualEffectStateFollowsWindowActiveState]; } [[window_ contentView] addSubview:vibrantView positioned:NSWindowBelow relativeTo:nil]; UpdateVibrancyRadii(IsFullscreen()); } [vibrantView setMaterial:vibrancyType]; } } void NativeWindowMac::SetWindowButtonVisibility(bool visible) { window_button_visibility_ = visible; if (buttons_proxy_) { if (visible) [buttons_proxy_ redraw]; [buttons_proxy_ setVisible:visible]; } if (title_bar_style_ != TitleBarStyle::kCustomButtonsOnHover) InternalSetWindowButtonVisibility(visible); NotifyLayoutWindowControlsOverlay(); } bool NativeWindowMac::GetWindowButtonVisibility() const { return ![window_ standardWindowButton:NSWindowZoomButton].hidden || ![window_ standardWindowButton:NSWindowMiniaturizeButton].hidden || ![window_ standardWindowButton:NSWindowCloseButton].hidden; } void NativeWindowMac::SetWindowButtonPosition( absl::optional<gfx::Point> position) { traffic_light_position_ = std::move(position); if (buttons_proxy_) { [buttons_proxy_ setMargin:traffic_light_position_]; NotifyLayoutWindowControlsOverlay(); } } absl::optional<gfx::Point> NativeWindowMac::GetWindowButtonPosition() const { return traffic_light_position_; } void NativeWindowMac::RedrawTrafficLights() { if (buttons_proxy_ && !IsFullscreen()) [buttons_proxy_ redraw]; } // In simpleFullScreen mode, update the frame for new bounds. void NativeWindowMac::UpdateFrame() { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); NSRect fullscreenFrame = [window.screen frame]; [window setFrame:fullscreenFrame display:YES animate:YES]; } void NativeWindowMac::SetTouchBar( std::vector<gin_helper::PersistentDictionary> items) { touch_bar_ = [[ElectronTouchBar alloc] initWithDelegate:window_delegate_ window:this settings:std::move(items)]; [window_ setTouchBar:nil]; } void NativeWindowMac::RefreshTouchBarItem(const std::string& item_id) { if (touch_bar_ && [window_ touchBar]) [touch_bar_ refreshTouchBarItem:[window_ touchBar] id:item_id]; } void NativeWindowMac::SetEscapeTouchBarItem( gin_helper::PersistentDictionary item) { if (touch_bar_ && [window_ touchBar]) [touch_bar_ setEscapeTouchBarItem:std::move(item) forTouchBar:[window_ touchBar]]; } void NativeWindowMac::SelectPreviousTab() { [window_ selectPreviousTab:nil]; } void NativeWindowMac::SelectNextTab() { [window_ selectNextTab:nil]; } void NativeWindowMac::ShowAllTabs() { [window_ toggleTabOverview:nil]; } void NativeWindowMac::MergeAllWindows() { [window_ mergeAllWindows:nil]; } void NativeWindowMac::MoveTabToNewWindow() { [window_ moveTabToNewWindow:nil]; } void NativeWindowMac::ToggleTabBar() { [window_ toggleTabBar:nil]; } bool NativeWindowMac::AddTabbedWindow(NativeWindow* window) { if (window_ == window->GetNativeWindow().GetNativeNSWindow()) { return false; } else { [window_ addTabbedWindow:window->GetNativeWindow().GetNativeNSWindow() ordered:NSWindowAbove]; } return true; } void NativeWindowMac::SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) { NativeWindow::SetAspectRatio(aspect_ratio, extra_size); // Reset the behaviour to default if aspect_ratio is set to 0 or less. if (aspect_ratio > 0.0) { NSSize aspect_ratio_size = NSMakeSize(aspect_ratio, 1.0); if (has_frame()) [window_ setContentAspectRatio:aspect_ratio_size]; else [window_ setAspectRatio:aspect_ratio_size]; } else { [window_ setResizeIncrements:NSMakeSize(1.0, 1.0)]; } } void NativeWindowMac::PreviewFile(const std::string& path, const std::string& display_name) { preview_item_ = [[ElectronPreviewItem alloc] initWithURL:[NSURL fileURLWithPath:base::SysUTF8ToNSString(path)] title:base::SysUTF8ToNSString(display_name)]; [[QLPreviewPanel sharedPreviewPanel] makeKeyAndOrderFront:nil]; } void NativeWindowMac::CloseFilePreview() { if ([QLPreviewPanel sharedPreviewPanelExists]) { [[QLPreviewPanel sharedPreviewPanel] close]; } } gfx::Rect NativeWindowMac::ContentBoundsToWindowBounds( const gfx::Rect& bounds) const { if (has_frame()) { gfx::Rect window_bounds( [window_ frameRectForContentRect:bounds.ToCGRect()]); int frame_height = window_bounds.height() - bounds.height(); window_bounds.set_y(window_bounds.y() - frame_height); return window_bounds; } else { return bounds; } } gfx::Rect NativeWindowMac::WindowBoundsToContentBounds( const gfx::Rect& bounds) const { if (has_frame()) { gfx::Rect content_bounds( [window_ contentRectForFrameRect:bounds.ToCGRect()]); int frame_height = bounds.height() - content_bounds.height(); content_bounds.set_y(content_bounds.y() + frame_height); return content_bounds; } else { return bounds; } } void NativeWindowMac::NotifyWindowEnterFullScreen() { NativeWindow::NotifyWindowEnterFullScreen(); // Restore the window title under fullscreen mode. if (buttons_proxy_) [window_ setTitleVisibility:NSWindowTitleVisible]; } void NativeWindowMac::NotifyWindowLeaveFullScreen() { NativeWindow::NotifyWindowLeaveFullScreen(); // Restore window buttons. if (buttons_proxy_ && window_button_visibility_.value_or(true)) { [buttons_proxy_ redraw]; [buttons_proxy_ setVisible:YES]; } } void NativeWindowMac::NotifyWindowWillEnterFullScreen() { UpdateVibrancyRadii(true); } void NativeWindowMac::NotifyWindowWillLeaveFullScreen() { if (buttons_proxy_) { // Hide window title when leaving fullscreen. [window_ setTitleVisibility:NSWindowTitleHidden]; // Hide the container otherwise traffic light buttons jump. [buttons_proxy_ setVisible:NO]; } UpdateVibrancyRadii(false); } void NativeWindowMac::SetActive(bool is_key) { is_active_ = is_key; } bool NativeWindowMac::IsActive() const { return is_active_; } void NativeWindowMac::Cleanup() { DCHECK(!IsClosed()); ui::NativeTheme::GetInstanceForNativeUi()->RemoveObserver(this); display::Screen::GetScreen()->RemoveObserver(this); } class NativeAppWindowFrameViewMac : public views::NativeFrameViewMac { public: NativeAppWindowFrameViewMac(views::Widget* frame, NativeWindowMac* window) : views::NativeFrameViewMac(frame), native_window_(window) {} NativeAppWindowFrameViewMac(const NativeAppWindowFrameViewMac&) = delete; NativeAppWindowFrameViewMac& operator=(const NativeAppWindowFrameViewMac&) = delete; ~NativeAppWindowFrameViewMac() override = default; // NonClientFrameView: int NonClientHitTest(const gfx::Point& point) override { if (!bounds().Contains(point)) return HTNOWHERE; if (GetWidget()->IsFullscreen()) return HTCLIENT; // Check for possible draggable region in the client area for the frameless // window. int contents_hit_test = native_window_->NonClientHitTest(point); if (contents_hit_test != HTNOWHERE) return contents_hit_test; return HTCLIENT; } private: // Weak. raw_ptr<NativeWindowMac> const native_window_; }; std::unique_ptr<views::NonClientFrameView> NativeWindowMac::CreateNonClientFrameView(views::Widget* widget) { return std::make_unique<NativeAppWindowFrameViewMac>(widget, this); } bool NativeWindowMac::HasStyleMask(NSUInteger flag) const { return [window_ styleMask] & flag; } void NativeWindowMac::SetStyleMask(bool on, NSUInteger flag) { // Changing the styleMask of a frameless windows causes it to change size so // we explicitly disable resizing while setting it. ScopedDisableResize disable_resize; if (on) [window_ setStyleMask:[window_ styleMask] | flag]; else [window_ setStyleMask:[window_ styleMask] & (~flag)]; // Change style mask will make the zoom button revert to default, probably // a bug of Cocoa or macOS. SetMaximizable(maximizable_); } void NativeWindowMac::SetCollectionBehavior(bool on, NSUInteger flag) { if (on) [window_ setCollectionBehavior:[window_ collectionBehavior] | flag]; else [window_ setCollectionBehavior:[window_ collectionBehavior] & (~flag)]; // Change collectionBehavior will make the zoom button revert to default, // probably a bug of Cocoa or macOS. SetMaximizable(maximizable_); } views::View* NativeWindowMac::GetContentsView() { return root_view_.get(); } bool NativeWindowMac::CanMaximize() const { return maximizable_; } void NativeWindowMac::OnNativeThemeUpdated(ui::NativeTheme* observed_theme) { content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&NativeWindow::RedrawTrafficLights, GetWeakPtr())); } void NativeWindowMac::AddContentViewLayers() { // Make sure the bottom corner is rounded for non-modal windows: // http://crbug.com/396264. if (!is_modal()) { // For normal window, we need to explicitly set layer for contentView to // make setBackgroundColor work correctly. // There is no need to do so for frameless window, and doing so would make // titleBarStyle stop working. if (has_frame()) { CALayer* background_layer = [[CALayer alloc] init]; [background_layer setAutoresizingMask:kCALayerWidthSizable | kCALayerHeightSizable]; [[window_ contentView] setLayer:background_layer]; } [[window_ contentView] setWantsLayer:YES]; } } void NativeWindowMac::InternalSetWindowButtonVisibility(bool visible) { [[window_ standardWindowButton:NSWindowCloseButton] setHidden:!visible]; [[window_ standardWindowButton:NSWindowMiniaturizeButton] setHidden:!visible]; [[window_ standardWindowButton:NSWindowZoomButton] setHidden:!visible]; } void NativeWindowMac::InternalSetParentWindow(NativeWindow* new_parent, bool attach) { if (is_modal()) return; // Do not remove/add if we are already properly attached. if (attach && new_parent && [window_ parentWindow] == new_parent->GetNativeWindow().GetNativeNSWindow()) return; // Remove current parent window. RemoveChildFromParentWindow(); // Set new parent window. if (new_parent) { new_parent->add_child_window(this); if (attach) new_parent->AttachChildren(); } NativeWindow::SetParentWindow(new_parent); } void NativeWindowMac::SetForwardMouseMessages(bool forward) { [window_ setAcceptsMouseMovedEvents:forward]; } gfx::Rect NativeWindowMac::GetWindowControlsOverlayRect() { if (titlebar_overlay_ && buttons_proxy_ && window_button_visibility_.value_or(true)) { NSRect buttons = [buttons_proxy_ getButtonsContainerBounds]; gfx::Rect overlay; overlay.set_width(GetContentSize().width() - NSWidth(buttons)); if ([buttons_proxy_ useCustomHeight]) { overlay.set_height(titlebar_overlay_height()); } else { overlay.set_height(NSHeight(buttons)); } if (!base::i18n::IsRTL()) overlay.set_x(NSMaxX(buttons)); return overlay; } return gfx::Rect(); } // static NativeWindow* NativeWindow::Create(const gin_helper::Dictionary& options, NativeWindow* parent) { return new NativeWindowMac(options, parent); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
39,413
[Bug]: App crashes with SIGTRAP while creating modal window on Mac
### 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 25.4.0 ### What operating system are you using? macOS ### Operating System Version 12.3 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version 25.1.1 ### Expected Behavior Not to crash:) ### Actual Behavior When I create new windows as modal to parent, I get crash with SIGTRAP Unfortunately, I couldn't reproduce this in small test project. Only fact I have, if I don't set new window as modal, app not crashes. ### Testcase Gist URL _No response_ ### Additional Information I can provide you part of stack trace and minidump <img width="872" alt="image" src="https://github.com/electron/electron/assets/25509934/ccfbba1b-13cd-4fee-a04c-1deff56d2dc3"> [2988dcae-9326-4b22-84d3-c0123f13e17f.dmp.zip](https://github.com/electron/electron/files/12292673/2988dcae-9326-4b22-84d3-c0123f13e17f.dmp.zip) There is very strange call for `ElectronPermissionMessageProvider::IsPrivilegeIncrease`. It seems like it never should be called. I also think it was affected here https://github.com/electron/electron/issues/38939
https://github.com/electron/electron/issues/39413
https://github.com/electron/electron/pull/39499
f7a7085019bf757700df3c2f8714e0de356203cd
1eb398b328d304f227deef0e89ca0be7b9e20755
2023-08-08T14:52:19Z
c++
2023-08-16T11:28:29Z
spec/api-browser-window-spec.ts
import { expect } from 'chai'; import * as childProcess from 'node:child_process'; import * as path from 'node:path'; import * as fs from 'node:fs'; import * as qs from 'node:querystring'; import * as http from 'node:http'; import * as os from 'node:os'; import { AddressInfo } from 'node:net'; import { app, BrowserWindow, BrowserView, dialog, ipcMain, OnBeforeSendHeadersListenerDetails, protocol, screen, webContents, webFrameMain, session, WebContents, WebFrameMain } from 'electron/main'; import { emittedUntil, emittedNTimes } from './lib/events-helpers'; import { ifit, ifdescribe, defer, listen } from './lib/spec-helpers'; import { closeWindow, closeAllWindows } from './lib/window-helpers'; import { areColorsSimilar, captureScreen, HexColors, getPixelColor } from './lib/screen-helpers'; import { once } from 'node:events'; import { setTimeout } from 'node:timers/promises'; const fixtures = path.resolve(__dirname, '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', () => { it('sets the correct class name on the prototype', () => { expect(BrowserWindow.prototype.constructor.name).to.equal('BrowserWindow'); }); 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(fixtures, 'apps', 'xwindow-icon'); const appProcess = childProcess.spawn(process.execPath, [appPath]); await once(appProcess, 'exit'); }); 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. const wr = new WeakRef(w); await setTimeout(); // 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 setTimeout(); expect(wr.deref()).to.not.be.undefined(); }); }); describe('BrowserWindow.close()', () => { let w: 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 = once(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 = once(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 allow access to id after destruction', async () => { const closed = once(w, 'closed'); w.destroy(); await closed; expect(w.id).to.be.a('number'); }); it('should emit unload handler', async () => { await w.loadFile(path.join(fixtures, 'api', 'unload.html')); const closed = once(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 once(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 = once(w, 'closed'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' }); w.close(); await closed; }); describe('when invoked synchronously inside navigation observer', () => { let server: http.Server; let url: string; before(async () => { 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}`); } }); url = (await listen(server)).url; }); 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 = once(w.webContents, 'destroyed'); w.webContents.loadURL(url + path); await destroyed; }); } }); }); describe('window.close()', () => { let w: 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 once(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 once(w.webContents, 'before-unload-fired'); }); }); describe('BrowserWindow.destroy()', () => { let w: 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: 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: http.Server; let url: string; let postData = null as any; before(async () => { 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(req.url && req.url.includes('slow') ? 200 : 0).then(respond); }); url = (await listen(server)).url; }); after(() => { server.close(); }); it('should emit did-start-loading event', async () => { const didStartLoading = once(w.webContents, 'did-start-loading'); w.loadURL('about:blank'); await didStartLoading; }); it('should emit ready-to-show event', async () => { const readyToShow = once(w, 'ready-to-show'); w.loadURL('about:blank'); await readyToShow; }); // DISABLED-FIXME(deepak1556): The error code now seems to be `ERR_FAILED`, verify what // changed and adjust the test. it('should emit did-fail-load event for files that do not exist', async () => { const didFailLoad = once(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 = once(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 not emit did-fail-load for a successfully loaded media file', async () => { w.webContents.on('did-fail-load', () => { expect.fail('did-fail-load should not emit on media file loads'); }); const mediaStarted = once(w.webContents, 'media-started-playing'); w.loadFile(path.join(fixtures, 'cat-spin.mp4')); await mediaStarted; }); it('should set `mainFrame = false` on did-fail-load events in iframes', async () => { const didFailLoad = once(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 = once(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: 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: http.Server; let url: string; before(async () => { server = http.createServer((req, res) => { if (req.url === '/navigate-top') { res.end('<a target=_top href="/">navigate _top</a>'); } else { res.end(''); } }); url = (await listen(server)).url; }); after(() => { server.close(); }); it('allows the window to be closed from the event listener', async () => { const event = once(w.webContents, 'will-navigate'); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); await event; w.close(); }); 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 () => { w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-top"></iframe>`); await emittedUntil(w.webContents, 'did-frame-finish-load', (e: any, isMainFrame: boolean) => !isMainFrame); let initiator: WebFrameMain | undefined; w.webContents.on('will-navigate', (e) => { initiator = e.initiator; }); const subframe = w.webContents.mainFrame.frames[0]; subframe.executeJavaScript('document.getElementsByTagName("a")[0].click()', true); await once(w.webContents, 'did-navigate'); expect(initiator).not.to.be.undefined(); expect(initiator).to.equal(subframe); }); }); describe('will-frame-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 if (req.url === '/navigate-iframe') { res.end('<a href="/test">navigate iframe</a>'); } else if (req.url === '/navigate-iframe?navigated') { res.end('Successfully navigated'); } else if (req.url === '/navigate-iframe-immediately') { res.end(` <script type="text/javascript" charset="utf-8"> location.href += '?navigated' </script> `); } else if (req.url === '/navigate-iframe-immediately?navigated') { res.end('Successfully navigated'); } 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-frame-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-frame-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('can be prevented when navigating subframe', (done) => { let willNavigate = false; w.webContents.on('did-frame-navigate', (_event, _url, _httpResponseCode, _httpStatusText, isMainFrame, frameProcessId, frameRoutingId) => { if (isMainFrame) return; w.webContents.once('will-frame-navigate', (e) => { willNavigate = true; e.preventDefault(); }); w.webContents.on('did-stop-loading', () => { const frame = webFrameMain.fromId(frameProcessId, frameRoutingId); expect(frame).to.not.be.undefined(); if (willNavigate) { // i.e. it shouldn't have had '?navigated' appended to it. try { expect(frame!.url.endsWith('/navigate-iframe-immediately')).to.be.true(); done(); } catch (e) { done(e); } } }); }); w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-iframe-immediately"></iframe>`); }); 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-frame-navigate', (e) => { e.preventDefault(); resolve(e.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-frame-navigate', (e) => { e.preventDefault(); resolve(e.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 setTimeout(1000); let willFrameNavigateEmitted = false; let isMainFrameValue; w.webContents.on('will-frame-navigate', (event) => { willFrameNavigateEmitted = true; isMainFrameValue = event.isMainFrame; }); const didNavigatePromise = once(w.webContents, 'did-navigate'); 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); await didNavigatePromise; expect(willFrameNavigateEmitted).to.be.true(); expect(isMainFrameValue).to.be.true(); }); it('is triggered when a cross-origin iframe navigates itself', async () => { await w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-iframe"></iframe>`); await setTimeout(1000); let willNavigateEmitted = false; let isMainFrameValue; w.webContents.on('will-frame-navigate', (event) => { willNavigateEmitted = true; isMainFrameValue = event.isMainFrame; }); const didNavigatePromise = once(w.webContents, 'did-frame-navigate'); 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); await didNavigatePromise; expect(willNavigateEmitted).to.be.true(); expect(isMainFrameValue).to.be.false(); }); it('can cancel when a cross-origin iframe navigates itself', async () => { }); }); describe('will-redirect event', () => { let server: http.Server; let url: string; before(async () => { 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(); } }); url = (await listen(server)).url; }); after(() => { server.close(); }); it('is emitted on redirects', async () => { const willRedirect = once(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 = once(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 = once(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', async () => { const event = once(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await event; w.close(); }); 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('ordering', () => { let server = null as unknown as http.Server; let url = null as unknown as string; const navigationEvents = [ 'did-start-navigation', 'did-navigate-in-page', 'will-frame-navigate', 'will-navigate', 'will-redirect', 'did-redirect-navigation', 'did-frame-navigate', 'did-navigate' ]; before((done) => { server = http.createServer((req, res) => { if (req.url === '/navigate') { res.end('<a href="/">navigate</a>'); } else if (req.url === '/redirect') { res.end('<a href="/redirect2">redirect</a>'); } else if (req.url === '/redirect2') { res.statusCode = 302; res.setHeader('location', url); res.end(); } else if (req.url === '/in-page') { res.end('<a href="#in-page">redirect</a><div id="in-page"></div>'); } else { res.end(''); } }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/`; done(); }); }); it('for initial navigation, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'did-frame-navigate', 'did-navigate' ]; const allEvents = Promise.all(navigationEvents.map(event => once(w.webContents, event).then(() => firedEvents.push(event)) )); const timeout = setTimeout(1000); w.loadURL(url); await Promise.race([allEvents, timeout]); expect(firedEvents).to.deep.equal(expectedEventOrder); }); it('for second navigation, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'will-frame-navigate', 'will-navigate', 'did-frame-navigate', 'did-navigate' ]; w.loadURL(`${url}navigate`); await once(w.webContents, 'did-navigate'); await setTimeout(2000); Promise.all(navigationEvents.map(event => once(w.webContents, event).then(() => firedEvents.push(event)) )); const navigationFinished = once(w.webContents, 'did-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: pageTarget.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); await navigationFinished; expect(firedEvents).to.deep.equal(expectedEventOrder); }); it('when navigating with redirection, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'will-frame-navigate', 'will-navigate', 'will-redirect', 'did-redirect-navigation', 'did-frame-navigate', 'did-navigate' ]; w.loadURL(`${url}redirect`); await once(w.webContents, 'did-navigate'); await setTimeout(2000); Promise.all(navigationEvents.map(event => once(w.webContents, event).then(() => firedEvents.push(event)) )); const navigationFinished = once(w.webContents, 'did-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: pageTarget.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); await navigationFinished; expect(firedEvents).to.deep.equal(expectedEventOrder); }); it('when navigating in-page, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'did-navigate-in-page' ]; w.loadURL(`${url}in-page`); await once(w.webContents, 'did-navigate'); await setTimeout(2000); Promise.all(navigationEvents.map(event => once(w.webContents, event).then(() => firedEvents.push(event)) )); const navigationFinished = once(w.webContents, 'did-navigate-in-page'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: pageTarget.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); await navigationFinished; expect(firedEvents).to.deep.equal(expectedEventOrder); }); }); }); } describe('focus and visibility', () => { let w: 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', async () => { const p = once(w, 'focus'); w.show(); await p; expect(w.isFocused()).to.equal(true); }); it('should make the window visible', async () => { const p = once(w, 'focus'); w.show(); await p; expect(w.isVisible()).to.equal(true); }); it('emits when window is shown', async () => { const show = once(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 = once(w, 'show'); w.show(); await shown; const hidden = once(w, 'hide'); w.hide(); await hidden; expect(w.isVisible()).to.equal(false); }); }); describe('BrowserWindow.minimize()', () => { // TODO(codebytere): Enable for Linux once maximize/minimize events work in CI. ifit(process.platform !== 'linux')('should not be visible when the window is minimized', async () => { const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMinimized()).to.equal(true); 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 = once(w, 'maximize'); const shown = once(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 setTimeout(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); }); ifit(process.platform !== 'win32')('focuses a blurred window', async () => { { const isBlurred = once(w, 'blur'); const isShown = once(w, 'show'); w.show(); w.blur(); await isShown; await isBlurred; } expect(w.isFocused()).to.equal(false); w.focus(); expect(w.isFocused()).to.equal(true); }); ifit(process.platform !== 'linux')('acquires focus status from the other windows', async () => { const w1 = new BrowserWindow({ show: false }); const w2 = new BrowserWindow({ show: false }); const w3 = new BrowserWindow({ show: false }); { const isFocused3 = once(w3, 'focus'); const isShown1 = once(w1, 'show'); const isShown2 = once(w2, 'show'); const isShown3 = once(w3, 'show'); w1.show(); w2.show(); w3.show(); await isShown1; await isShown2; await isShown3; await isFocused3; } // TODO(RaisinTen): Investigate why this assertion fails only on Linux. expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); w1.focus(); expect(w1.isFocused()).to.equal(true); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(false); w2.focus(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(true); expect(w3.isFocused()).to.equal(false); w3.focus(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); { const isClosed1 = once(w1, 'closed'); const isClosed2 = once(w2, 'closed'); const isClosed3 = once(w3, 'closed'); w1.destroy(); w2.destroy(); w3.destroy(); await isClosed1; await isClosed2; await isClosed3; } }); }); // TODO(RaisinTen): Make this work on Windows too. // Refs: https://github.com/electron/electron/issues/20464. ifdescribe(process.platform !== 'win32')('BrowserWindow.blur()', () => { it('removes focus from window', async () => { { const isFocused = once(w, 'focus'); const isShown = once(w, 'show'); w.show(); await isShown; await isFocused; } expect(w.isFocused()).to.equal(true); w.blur(); expect(w.isFocused()).to.equal(false); }); ifit(process.platform !== 'linux')('transfers focus status to the next window', async () => { const w1 = new BrowserWindow({ show: false }); const w2 = new BrowserWindow({ show: false }); const w3 = new BrowserWindow({ show: false }); { const isFocused3 = once(w3, 'focus'); const isShown1 = once(w1, 'show'); const isShown2 = once(w2, 'show'); const isShown3 = once(w3, 'show'); w1.show(); w2.show(); w3.show(); await isShown1; await isShown2; await isShown3; await isFocused3; } // TODO(RaisinTen): Investigate why this assertion fails only on Linux. expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); w3.blur(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(true); expect(w3.isFocused()).to.equal(false); w2.blur(); expect(w1.isFocused()).to.equal(true); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(false); w1.blur(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); { const isClosed1 = once(w1, 'closed'); const isClosed2 = once(w2, 'closed'); const isClosed3 = once(w3, 'closed'); w1.destroy(); w2.destroy(); w3.destroy(); await isClosed1; await isClosed2; await isClosed3; } }); }); describe('BrowserWindow.getFocusedWindow()', () => { it('returns the opener window when dev tools window is focused', async () => { const p = once(w, 'focus'); w.show(); await p; w.webContents.openDevTools({ mode: 'undocked' }); await once(w.webContents, 'devtools-focused'); expect(BrowserWindow.getFocusedWindow()).to.equal(w); }); }); describe('BrowserWindow.moveTop()', () => { it('should not steal focus', async () => { const posDelta = 50; const wShownInactive = once(w, 'show'); w.showInactive(); await wShownInactive; expect(w.isFocused()).to.equal(false); const otherWindow = new BrowserWindow({ show: false, title: 'otherWindow' }); const otherWindowShown = once(otherWindow, 'show'); const otherWindowFocused = once(otherWindow, 'focus'); otherWindow.show(); await otherWindowShown; await otherWindowFocused; expect(otherWindow.isFocused()).to.equal(true); w.moveTop(); const wPos = w.getPosition(); const wMoving = once(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 = once(w, 'focus'); const otherWindowBlurred = once(otherWindow, 'blur'); w.focus(); await wFocused; await otherWindowBlurred; expect(w.isFocused()).to.equal(true); otherWindow.moveTop(); const otherWindowPos = otherWindow.getPosition(); const otherWindowMoving = once(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); }); }); describe('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 = once(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 = once(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: 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 = { ...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(once(w, 'resized')).to.eventually.be.fulfilled(); }); }); }); describe('BrowserWindow.setSize(width, height)', () => { it('sets the window size', async () => { const size = [300, 400]; const resized = once(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(once(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 = once(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 = once(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 = once(w, 'resize'); w.setContentBounds(bounds); await resize; await setTimeout(); 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 = once(w, 'resize'); w.setContentBounds(bounds); await resize; await setTimeout(); 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); }); it('returns correct color with multiple passed formats', () => { w.destroy(); w = new BrowserWindow({}); w.setBackgroundColor('#AABBFF'); expect(w.getBackgroundColor()).to.equal('#AABBFF'); w.setBackgroundColor('blueviolet'); expect(w.getBackgroundColor()).to.equal('#8A2BE2'); w.setBackgroundColor('rgb(255, 0, 185)'); expect(w.getBackgroundColor()).to.equal('#FF00B9'); w.setBackgroundColor('rgba(245, 40, 145, 0.8)'); expect(w.getBackgroundColor()).to.equal('#F52891'); w.setBackgroundColor('hsl(155, 100%, 50%)'); expect(w.getBackgroundColor()).to.equal('#00FF95'); }); }); describe('BrowserWindow.getNormalBounds()', () => { describe('Normal state', () => { it('checks normal bounds after resize', async () => { const size = [300, 400]; const resize = once(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 = once(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 = once(w, 'maximize'); w.show(); w.maximize(); await maximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after resize and maximize', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('updates normal bounds after move and maximize', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('checks normal bounds when unmaximized', async () => { const bounds = w.getBounds(); w.once('maximize', () => { w.unmaximize(); }); const unmaximize = once(w, 'unmaximize'); w.show(); w.maximize(); await unmaximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('correctly reports maximized state after maximizing then minimizing', async () => { w.destroy(); w = new BrowserWindow({ show: false }); w.show(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMaximized()).to.equal(false); expect(w.isMinimized()).to.equal(true); }); it('correctly reports maximized state after maximizing then fullscreening', async () => { w.destroy(); w = new BrowserWindow({ show: false }); w.show(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; expect(w.isMaximized()).to.equal(false); expect(w.isFullScreen()).to.equal(true); }); it('checks normal bounds for maximized transparent window', async () => { w.destroy(); w = new BrowserWindow({ transparent: true, show: false }); w.show(); const bounds = w.getNormalBounds(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; 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 = once(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 = once(w, 'maximize'); w.show(); w.maximize(); await maximize; expect(w.isMaximized()).to.equal(true); const unmaximize = once(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 = once(w, 'maximize'); 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 = once(w, 'minimize'); w.show(); w.minimize(); await minimize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after move and minimize', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const minimize = once(w, 'minimize'); w.minimize(); await minimize; const normal = w.getNormalBounds(); expect(original).to.deep.equal(normal); expectBoundsEqual(normal, w.getBounds()); }); it('updates normal bounds after resize and minimize', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const minimize = once(w, 'minimize'); w.minimize(); await minimize; const normal = w.getNormalBounds(); expect(original).to.deep.equal(normal); expectBoundsEqual(normal, w.getBounds()); }); it('checks normal bounds when restored', async () => { const bounds = w.getBounds(); w.once('minimize', () => { w.restore(); }); const restore = once(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 = once(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('does not go fullscreen if roundedCorners are enabled', async () => { w = new BrowserWindow({ frame: false, roundedCorners: false, fullscreen: true }); expect(w.fullScreen).to.be.false(); }); 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 = once(w, 'enter-full-screen'); w.show(); w.fullScreen = true; await enterFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after resize and fullscreen', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.fullScreen = true; await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('updates normal bounds after move and fullscreen', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.fullScreen = true; await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('checks normal bounds when unfullscreen\'ed', async () => { const bounds = w.getBounds(); w.once('enter-full-screen', () => { w.fullScreen = false; }); const leaveFullScreen = once(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 = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after resize and fullscreen', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.setFullScreen(true); await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('updates normal bounds after move and fullscreen', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.setFullScreen(true); await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('checks normal bounds when unfullscreen\'ed', async () => { const bounds = w.getBounds(); w.show(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); }); }); }); ifdescribe(process.platform === 'darwin')('tabbed windows', () => { let w: 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.showAllTabs()', () => { it('does not throw', () => { expect(() => { w.showAllTabs(); }).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); }); ifit(process.platform === 'darwin')('honors the stayHidden argument', async () => { const w = new BrowserWindow({ webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.hide(); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } await w.capturePage({ x: 0, y: 0, width: 0, height: 0 }, { stayHidden: true }); const visible = await w.webContents.executeJavaScript('document.visibilityState'); expect(visible).to.equal('hidden'); }); it('resolves after the window is hidden', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixtures, 'pages', 'a.html')); await once(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('resolves after the window is hidden and capturer count is non-zero', async () => { const w = new BrowserWindow({ show: false }); w.webContents.setBackgroundThrottling(false); w.loadFile(path.join(fixtures, 'pages', 'a.html')); await once(w, 'ready-to-show'); const image = await w.capturePage(); expect(image.isEmpty()).to.equal(false); }); it('preserves transparency', async () => { const w = new BrowserWindow({ show: false, transparent: true }); w.loadFile(path.join(fixtures, 'pages', 'theme-color.html')); await once(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: 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: 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', async () => { expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); const minimized = once(w, 'minimize'); w.minimize(); await minimized; expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); const restored = once(w, 'restore'); w.restore(); await restored; 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 = once(w, 'always-on-top-changed') as Promise<[any, boolean]>; 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: BrowserWindow; let server: http.Server; let url: 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++; }); url = (await listen(server)).url; }); 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 = once(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: 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); }); it('correctly updates when entering/exiting fullscreen for hidden style', async () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hidden' }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; const leaveFS = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFS; w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); it('correctly updates when entering/exiting fullscreen for hiddenInset style', async () => { 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); const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; const leaveFS = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFS; w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setVibrancy(type)', () => { afterEach(closeAllWindows); it('allows setting, changing, and removing the vibrancy', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setVibrancy('titlebar'); w.setVibrancy('selection'); w.setVibrancy(null); w.setVibrancy('menu'); 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(); }); }); ifdescribe(process.platform === 'darwin')('trafficLightPosition', () => { const pos = { x: 10, y: 10 }; afterEach(closeAllWindows); describe('BrowserWindow.getWindowButtonPosition(pos)', () => { it('returns null when there is no custom position', () => { const w = new BrowserWindow({ show: false }); expect(w.getWindowButtonPosition()).to.be.null('getWindowButtonPosition'); }); it('gets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); expect(w.getWindowButtonPosition()).to.deep.equal(pos); }); it('gets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); expect(w.getWindowButtonPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setWindowButtonPosition(pos)', () => { it('resets the position when null is passed', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); w.setWindowButtonPosition(null); expect(w.getWindowButtonPosition()).to.be.null('setWindowButtonPosition'); }); it('sets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setWindowButtonPosition(newPos); expect(w.getWindowButtonPosition()).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.setWindowButtonPosition(newPos); expect(w.getWindowButtonPosition()).to.deep.equal(newPos); }); }); // The set/getTrafficLightPosition APIs are deprecated. describe('BrowserWindow.getTrafficLightPosition(pos)', () => { it('returns { x: 0, y: 0 } when there is no custom position', () => { const w = new BrowserWindow({ show: false }); expect(w.getTrafficLightPosition()).to.deep.equal({ x: 0, y: 0 }); }); 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('resets the position when { x: 0, y: 0 } is passed', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); w.setTrafficLightPosition({ x: 0, y: 0 }); expect(w.getTrafficLightPosition()).to.deep.equal({ x: 0, y: 0 }); }); 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('Opening a BrowserWindow from a link', () => { let appProcess: childProcess.ChildProcessWithoutNullStreams | undefined; afterEach(() => { if (appProcess && !appProcess.killed) { appProcess.kill(); appProcess = undefined; } }); it('can properly open and load a new window from a link', async () => { const appPath = path.join(__dirname, 'fixtures', 'apps', 'open-new-window-from-link'); appProcess = childProcess.spawn(process.execPath, [appPath]); const [code] = await once(appProcess, 'exit'); expect(code).to.equal(0); }); }); 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 typeof ElectronInternal.WebContents).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.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 = once(w.webContents, 'did-attach-webview'); const [, webviewContents] = await once(app, 'web-contents-created') as [any, WebContents]; expect(BrowserWindow.fromWebContents(webviewContents)!.id).to.equal(w.id); await p; }); it('is usable immediately on browser-window-created', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.executeJavaScript('window.open(""); null'); const [win, winFromWebContents] = await new Promise<any>((resolve) => { app.once('browser-window-created', (e, win) => { resolve([win, BrowserWindow.fromWebContents(win.webContents)]); }); }); expect(winFromWebContents).to.equal(win); }); }); 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.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.destroy(); bv2.webContents.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.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(['win32', 'darwin'].includes(process.platform))('"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 = once(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 = once(ipcMain, 'geometrychange'); w.setBounds({ width: 800 }); const [, newOverlayRect] = await geometryChange; expect(newOverlayRect.width).to.equal(overlayRect.width + 400); }; afterEach(async () => { await closeAllWindows(); 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')('when an invalid titleBarStyle is initially set', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { color: '#0000f0', symbolColor: '#ffffff' }, titleBarStyle: 'hiddenInset' }); }); afterEach(async () => { await closeAllWindows(); }); it('does not crash changing minimizability ', () => { expect(() => { w.setMinimizable(false); }).to.not.throw(); }); it('does not crash changing maximizability', () => { expect(() => { w.setMaximizable(false); }).to.not.throw(); }); }); }); ifdescribe(['win32', 'darwin'].includes(process.platform))('"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 = once(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()'); if (!w.isMaximized()) { const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; } expect(w.isMaximized()).to.be.true('not maximized'); 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(async () => { await closeAllWindows(); ipcMain.removeAllListeners('geometrychange'); }); it('sets Window Control Overlay with title bar height of 40', async () => { await testWindowsOverlayHeight(40); }); }); ifdescribe(process.platform === 'win32')('BrowserWindow.setTitlebarOverlay', () => { afterEach(async () => { await closeAllWindows(); ipcMain.removeAllListeners('geometrychange'); }); it('does not crash when an invalid titleBarStyle was initially set', () => { const win = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { color: '#0000f0', symbolColor: '#ffffff' }, titleBarStyle: 'hiddenInset' }); expect(() => { win.setTitleBarOverlay({ color: '#000000' }); }).to.not.throw(); }); it('correctly updates the height of the overlay', async () => { const testOverlay = async (w: BrowserWindow, size: Number, firstRun: boolean) => { const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); const overlayReady = once(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); if (firstRun) { await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const { height: preMaxHeight } = await w.webContents.executeJavaScript('getJSOverlayProperties()'); if (!w.isMaximized()) { const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; } expect(w.isMaximized()).to.be.true('not maximized'); const { x, y, width, height } = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(x).to.equal(0); expect(y).to.equal(0); expect(width).to.be.greaterThan(0); expect(height).to.equal(size); expect(preMaxHeight).to.equal(size); }; const INITIAL_SIZE = 40; const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden', webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { height: INITIAL_SIZE } }); await testOverlay(w, INITIAL_SIZE, true); w.setTitleBarOverlay({ height: INITIAL_SIZE + 10 }); await testOverlay(w, INITIAL_SIZE + 10, false); }); }); 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-next-line no-new */ new BrowserWindow({ tabbingIdentifier: 'group1' }); /* eslint-disable-next-line no-new */ new BrowserWindow({ tabbingIdentifier: 'group2', frame: false }); }).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 once(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 once(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 once(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-isolated 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 once(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 once(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 once(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 once(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 once(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 once(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; let serverUrl: string; before(async () => { 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}`); } }); serverUrl = (await listen(server)).url; }); 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 once(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 once(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 once(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 once(ipcMain, 'answer'); const expectedUrl = process.platform === 'win32' ? 'file:///' + htmlPath.replace(/\\/g, '/') : pageUrl; expect(url).to.equal(expectedUrl); }); it('exposes full EventEmitter object to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload: path.join(fixtures, 'module', 'preload-eventemitter.js') } }); w.loadURL('about:blank'); const [, rendererEventEmitterProperties] = await once(ipcMain, 'answer'); const { EventEmitter } = require('node:events'); const emitter = new EventEmitter(); const browserEventEmitterProperties = []; let currentObj = emitter; do { browserEventEmitterProperties.push(...Object.getOwnPropertyNames(currentObj)); } while ((currentObj = Object.getPrototypeOf(currentObj))); expect(rendererEventEmitterProperties).to.deep.equal(browserEventEmitterProperties); }); 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 = once(ipcMain, 'answer'); w.loadURL(pageUrl); const [, { url, frameName, options }] = await once(w.webContents, 'did-create-window') as [BrowserWindow, Electron.DidCreateWindowDetails]; 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 once(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 once(app, 'browser-window-created') as [any, BrowserWindow]; // Ask the popup window for details. const detailsAnswer = once(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 = once(ipcMain, 'answer'); w.webContents.send('touch-the-popup'); const [, popupAccessMessage] = await touchPopupResult; // Ask the popup to access the opener. const touchOpenerResult = once(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 once(ipcMain, 'answer'); expect(argv).to.include('--enable-sandbox'); }); it('should open windows with the options configured via setWindowOpenHandler handlers', 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([ once(app, 'web-contents-created') as Promise<[any, WebContents]>, once(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 => once(ipcMain, name))); w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'verify-ipc-sender' }); await done; }); describe('event handling', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); }); it('works for window events', async () => { const pageTitleUpdated = once(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 => once(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 => once(w.webContents, name))); w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'webcontents-events' }); await done; }); }); 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 once(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'); expect(test.nodeEvents).to.equal(true); expect(test.nodeTimers).to.equal(true); expect(test.nodeUrl).to.equal(true); 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 = once(w.webContents, 'did-attach-webview') as Promise<[any, WebContents]>; const webviewDomReady = once(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; 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 = once(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 = once(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 = once(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 = once(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 once(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 once(ipcMain, 'answer'); expect(content).to.equal('function'); } w.reload(); { const [, content] = await once(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, preload } } })); const webviewLoaded = once(ipcMain, 'webview-loaded'); w.loadFile(path.join(fixtures, 'api', 'new-window-webview.html')); await webviewLoaded; }); it('should open windows with the options configured via setWindowOpenHandler handlers', 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([ once(app, 'web-contents-created') as Promise<[any, WebContents]>, once(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 once(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 once(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 = once(w.webContents, 'enter-html-full-screen'); w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true); await enterHtmlFullScreen; expect(w.getSize()).to.deep.equal(size); }); }); describe('"defaultFontFamily" option', () => { it('can change the standard font family', async () => { const w = new BrowserWindow({ show: false, webPreferences: { defaultFontFamily: { standard: 'Impact' } } }); await w.loadFile(path.join(fixtures, 'pages', 'content.html')); const fontFamily = await w.webContents.executeJavaScript("window.getComputedStyle(document.getElementsByTagName('p')[0])['font-family']", true); expect(fontFamily).to.equal('Impact'); }); }); }); describe('beforeunload handler', function () { let w: 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 = once(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 once(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 once(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 once(w.webContents, 'console-message'); w.close(); await once(w.webContents, 'before-unload-fired'); w.close(); await once(w.webContents, 'before-unload-fired'); w.webContents.removeListener('destroyed', destroyListener); const wait = once(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 once(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 once(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 once(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'); }); }); // TODO(codebytere): figure out how to make these pass in CI on Windows. ifdescribe(process.platform !== 'win32')('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 once(ipcMain, 'pong'); expect(readyToShow).to.be.false('ready to show'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); }); it('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 once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.hide(); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } }); it('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 once(w, 'show'); } w.hide(); w.show(); const [, visibilityState] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); }); it('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 once(w, 'show'); } w.hide(); w.showInactive(); const [, visibilityState] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); }); 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 once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.minimize(); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } }); it('visibilityState remains visible if backgroundThrottling is disabled', async () => { const w = new BrowserWindow({ show: false, width: 100, height: 100, webPreferences: { backgroundThrottling: false, nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await once(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 = once(w, 'show'); w.show(); await shown1; const hidden = once(w, 'hide'); w.hide(); await hidden; const shown2 = once(w, 'show'); w.show(); await shown2; } finally { ipcMain.removeAllListeners('pong'); } }); }); 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 = once(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 = once(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 = once(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 = once(w, 'maximize'); const unmaximize = once(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 = once(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 }); let called = false; w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); w.webContents.on('dom-ready', () => { w.webContents.beginFrameSubscription(function () { // This callback might be called twice. if (called) return; called = true; // Pending endFrameSubscription to next tick can reliably reproduce // a crash which happens when nothing is returned in the callback. setTimeout().then(() => { 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 () => { /* Use temp directory for saving MHTML file since the write handle * gets passed to untrusted process and chromium will deny exec access to * the path. To perform this task, chromium requires that the path is one * of the browser controlled paths, refs https://chromium-review.googlesource.com/c/chromium/src/+/3774416 */ const tmpDir = await fs.promises.mkdtemp(path.resolve(os.tmpdir(), 'electron-mhtml-save-')); const savePageMHTMLPath = path.join(tmpDir, 'save_page.html'); const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageMHTMLPath, 'MHTML'); expect(fs.existsSync(savePageMHTMLPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.false('js path'); expect(fs.existsSync(savePageCssPath)).to.be.false('css path'); try { await fs.promises.unlink(savePageMHTMLPath); await fs.promises.rmdir(tmpDir); } catch {} }); 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(); }); // TODO(zcbenz): // This test does not run on Linux CI. See: // https://github.com/electron/electron/issues/28699 ifit(process.platform === 'linux' && !process.env.CI)('should bring a minimized maximized window back to maximized state', async () => { const w = new BrowserWindow({}); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMaximized()).to.equal(false); const restore = once(w, 'restore'); w.restore(); await restore; expect(w.isMaximized()).to.equal(true); }); }); // TODO(dsanders11): Enable once maximize event works on Linux again on CI ifdescribe(process.platform !== 'linux')('BrowserWindow.maximize()', () => { afterEach(closeAllWindows); it('should show the window if it is not currently shown', async () => { const w = new BrowserWindow({ show: false }); const hidden = once(w, 'hide'); let shown = once(w, 'show'); const maximize = once(w, 'maximize'); expect(w.isVisible()).to.be.false('visible'); w.maximize(); await maximize; await shown; expect(w.isMaximized()).to.be.true('maximized'); expect(w.isVisible()).to.be.true('visible'); // Even if the window is already maximized w.hide(); await hidden; expect(w.isVisible()).to.be.false('visible'); shown = once(w, 'show'); w.maximize(); await shown; expect(w.isVisible()).to.be.true('visible'); }); }); 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 = once(w, 'minimize'); w.minimize(); await minimize; w.unmaximize(); await setTimeout(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 setTimeout(1000); expectBoundsEqual(w.getSize(), initialSize); expectBoundsEqual(w.getPosition(), initialPosition); }); ifit(process.platform === 'darwin')('should not change size or position of a window which is functionally maximized', async () => { const { workArea } = screen.getPrimaryDisplay(); const bounds = { x: workArea.x, y: workArea.y, width: workArea.width, height: workArea.height }; const w = new BrowserWindow(bounds); w.unmaximize(); await setTimeout(1000); expectBoundsEqual(w.getBounds(), bounds); }); }); 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 = once(w, 'show'); // start fullscreen and hidden w.setFullScreen(true); w.show(); await shown; const leftFullScreen = once(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 = once(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 once(w, 'enter-full-screen'); // Wait a tick for the full-screen state to 'stick' await setTimeout(); w.setFullScreen(false); await once(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 = once(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 = once(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 = once(c, 'closed'); c.close(); await closed; // The child window list is not immediately cleared, so wait a tick until it's ready. await setTimeout(); expect(w.getChildWindows().length).to.equal(0); }); it('can handle child window close and reparent multiple times', async () => { const w = new BrowserWindow({ show: false }); let c: BrowserWindow | null; for (let i = 0; i < 5; i++) { c = new BrowserWindow({ show: false, parent: w }); const closed = once(c, 'closed'); c.close(); await closed; } await setTimeout(); expect(w.getChildWindows().length).to.equal(0); }); ifit(process.platform === 'darwin')('child window matches visibility when visibility changes', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); const wShow = once(w, 'show'); const cShow = once(c, 'show'); w.show(); c.show(); await Promise.all([wShow, cShow]); const minimized = once(w, 'minimize'); w.minimize(); await minimized; expect(w.isVisible()).to.be.false('parent is visible'); expect(c.isVisible()).to.be.false('child is visible'); const restored = once(w, 'restore'); w.restore(); await restored; expect(w.isVisible()).to.be.true('parent is visible'); expect(c.isVisible()).to.be.true('child is visible'); }); ifit(process.platform === 'darwin')('matches child window visibility when visibility changes', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); const wShow = once(w, 'show'); const cShow = once(c, 'show'); w.show(); c.show(); await Promise.all([wShow, cShow]); const minimized = once(c, 'minimize'); c.minimize(); await minimized; expect(c.isVisible()).to.be.false('child is visible'); const restored = once(c, 'restore'); c.restore(); await restored; expect(w.isVisible()).to.be.true('parent is visible'); expect(c.isVisible()).to.be.true('child is visible'); }); it('closes a grandchild window when a middle child window is destroyed', (done) => { const w = new BrowserWindow(); w.loadFile(path.join(fixtures, 'pages', 'base-page.html')); w.webContents.executeJavaScript('window.open("")'); w.webContents.on('did-create-window', async (window) => { const childWindow = new BrowserWindow({ parent: window }); await setTimeout(); window.close(); childWindow.on('closed', () => { expect(() => { BrowserWindow.getFocusedWindow(); }).to.not.throw(); done(); }); }); }); 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 = once(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 setTimeout(); expect(w.getChildWindows().length).to.equal(0); }); ifit(process.platform === 'darwin')('can reparent when the first parent is destroyed', async () => { const w1 = new BrowserWindow({ show: false }); const w2 = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); c.setParentWindow(w1); expect(w1.getChildWindows().length).to.equal(1); const closed = once(w1, 'closed'); w1.destroy(); await closed; c.setParentWindow(w2); await setTimeout(); const children = w2.getChildWindows(); expect(children[0]).to.equal(c); }); }); 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 = once(two, 'show'); two.show(); await twoShown; setTimeout(500).then(() => two.close()); await once(two, 'closed'); }; const one = new BrowserWindow({ width: 600, height: 400, parent: parentWindow, modal: true, show: false }); const oneShown = once(one, 'show'); one.show(); await oneShown; setTimeout(500).then(() => one.destroy()); await once(one, 'closed'); await createTwo(); }); ifit(process.platform !== 'darwin')('can disable and enable a window', () => { const w = new BrowserWindow({ show: false }); w.setEnabled(false); expect(w.isEnabled()).to.be.false('w.isEnabled()'); w.setEnabled(true); expect(w.isEnabled()).to.be.true('!w.isEnabled()'); }); 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 = once(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 = once(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; let serverUrl: string; before(async () => { server = http.createServer((request, response) => { response.end(); }); serverUrl = (await listen(server)).url; }); after(() => { server.close(); }); it('is true when the main frame is loading', async () => { const w = new BrowserWindow({ show: false }); const didStartLoading = once(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 = once(w.webContents, 'did-stop-loading'); w.webContents.loadURL(serverUrl); await didStopLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); const didStartLoading = once(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 = once(w.webContents, 'did-stop-loading'); w.webContents.loadURL(serverUrl); await didStopLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); const didStartLoading = once(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')('when fullscreen state is changed', () => { it('correctly remembers state prior to fullscreen change', async () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); w.setMenuBarVisibility(false); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; expect(w.fullScreen).to.be.true('not fullscreen'); const exitFS = once(w, 'leave-full-screen'); w.setFullScreen(false); await exitFS; expect(w.fullScreen).to.be.false('not fullscreen'); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); }); it('correctly remembers state prior to fullscreen change with autoHide', async () => { const w = new BrowserWindow({ show: false }); expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); w.autoHideMenuBar = true; expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); w.setMenuBarVisibility(false); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; expect(w.fullScreen).to.be.true('not fullscreen'); const exitFS = once(w, 'leave-full-screen'); w.setFullScreen(false); await exitFS; expect(w.fullScreen).to.be.false('not fullscreen'); expect(w.isMenuBarVisible()).to.be.false('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'); }); }); }); ifdescribe(process.platform === 'darwin')('isHiddenInMissionControl state', () => { it('with functions', () => { it('can be set with ignoreMissionControl constructor option', () => { const w = new BrowserWindow({ show: false, hiddenInMissionControl: true }); expect(w.isHiddenInMissionControl()).to.be.true('isHiddenInMissionControl'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isHiddenInMissionControl()).to.be.false('isHiddenInMissionControl'); w.setHiddenInMissionControl(true); expect(w.isHiddenInMissionControl()).to.be.true('isHiddenInMissionControl'); w.setHiddenInMissionControl(false); expect(w.isHiddenInMissionControl()).to.be.false('isHiddenInMissionControl'); }); }); }); // 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 = once(w, 'enter-full-screen'); w.kiosk = true; expect(w.isKiosk()).to.be.true('isKiosk'); await enterFullScreen; await setTimeout(); const leaveFullScreen = once(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 = once(w, 'enter-full-screen'); w.setKiosk(true); expect(w.isKiosk()).to.be.true('isKiosk'); await enterFullScreen; await setTimeout(); const leaveFullScreen = once(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 false and restored', async () => { const w = new BrowserWindow({ resizable: false }); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.resizable).to.be.false('resizable'); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.resizable).to.be.false('resizable'); }); it('default resizable flag should be restored after entering/exiting fullscreen', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.resizable).to.be.false('resizable'); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.resizable).to.be.true('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 = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; }); it('should be able to load a URL while transitioning to fullscreen', async () => { const w = new BrowserWindow({ fullscreen: true }); w.loadFile(path.join(fixtures, 'pages', 'c.html')); const load = once(w.webContents, 'did-finish-load'); const enterFS = once(w, 'enter-full-screen'); await Promise.all([enterFS, load]); expect(w.fullScreen).to.be.true(); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; }); it('can be changed with setFullScreen method', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await setTimeout(); const leaveFullScreen = once(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 setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); }); it('handles several HTML fullscreen transitions', async () => { const w = new BrowserWindow(); await w.loadFile(path.join(fixtures, 'pages', 'a.html')); expect(w.isFullScreen()).to.be.false('is fullscreen'); const enterFullScreen = once(w, 'enter-full-screen'); const leaveFullScreen = once(w, 'leave-full-screen'); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await enterFullScreen; await w.webContents.executeJavaScript('document.exitFullscreen()', true); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); await setTimeout(); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await enterFullScreen; await w.webContents.executeJavaScript('document.exitFullscreen()', true); 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'); const enterFS = emittedNTimes(w, 'enter-full-screen', 2); const leaveFS = emittedNTimes(w, 'leave-full-screen', 2); w.setFullScreen(true); w.setFullScreen(false); w.setFullScreen(true); w.setFullScreen(false); await Promise.all([enterFS, leaveFS]); expect(w.isFullScreen()).to.be.false('not fullscreen'); }); it('handles several chromium-initiated transitions in close proximity', async () => { const w = new BrowserWindow(); await w.loadFile(path.join(fixtures, 'pages', 'a.html')); expect(w.isFullScreen()).to.be.false('is fullscreen'); let enterCount = 0; let exitCount = 0; const done = new Promise<void>(resolve => { const checkDone = () => { if (enterCount === 2 && exitCount === 2) resolve(); }; w.webContents.on('enter-html-full-screen', () => { enterCount++; checkDone(); }); w.webContents.on('leave-html-full-screen', () => { exitCount++; checkDone(); }); }); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await done; }); it('handles HTML fullscreen transitions when fullscreenable is false', async () => { const w = new BrowserWindow({ fullscreenable: false }); await w.loadFile(path.join(fixtures, 'pages', 'a.html')); expect(w.isFullScreen()).to.be.false('is fullscreen'); let enterCount = 0; let exitCount = 0; const done = new Promise<void>((resolve, reject) => { const checkDone = () => { if (enterCount === 2 && exitCount === 2) resolve(); }; w.webContents.on('enter-html-full-screen', async () => { enterCount++; if (w.isFullScreen()) reject(new Error('w.isFullScreen should be false')); const isFS = await w.webContents.executeJavaScript('!!document.fullscreenElement'); if (!isFS) reject(new Error('Document should have fullscreen element')); checkDone(); }); w.webContents.on('leave-html-full-screen', () => { exitCount++; if (w.isFullScreen()) reject(new Error('w.isFullScreen should be false')); checkDone(); }); }); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await expect(done).to.eventually.be.fulfilled(); }); it('does not crash when exiting simpleFullScreen (properties)', async () => { const w = new BrowserWindow(); w.setSimpleFullScreen(true); await setTimeout(1000); w.setFullScreen(!w.isFullScreen()); }); it('does not crash when exiting simpleFullScreen (functions)', async () => { const w = new BrowserWindow(); w.simpleFullScreen = true; await setTimeout(1000); w.setFullScreen(!w.isFullScreen()); }); it('should not be changed by setKiosk method', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setKiosk(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); const leaveFullScreen = once(w, 'leave-full-screen'); w.setKiosk(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('isFullScreen'); }); it('should stay fullscreen if fullscreen before kiosk', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); w.setKiosk(true); w.setKiosk(false); // Wait enough time for a fullscreen change to take effect. await setTimeout(2000); expect(w.isFullScreen()).to.be.true('isFullScreen'); }); it('multiple windows inherit correct fullscreen state', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await setTimeout(1000); const w2 = new BrowserWindow({ show: false }); const enterFullScreen2 = once(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 = once(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(); }); it('should not call BrowserWindow show event', async () => { const w = new BrowserWindow({ show: false }); const shown = once(w, 'show'); w.show(); await shown; let showCalled = false; w.on('show', () => { showCalled = true; }); w.previewFile(__filename); await setTimeout(500); expect(showCalled).to.equal(false, 'should not have called show twice'); }); }); // TODO (jkleinsc) renable these tests on mas arm64 ifdescribe(!process.mas || process.arch !== 'arm64')('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 = once(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 = once(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 = once(app, 'browser-window-created') as Promise<[any, BrowserWindow]>; 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 = once(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 = once(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 = once(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 = once(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 = once(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 = once(w1, 'focus'); w1.webContents.focus(); await w1Focused; expect(w1.webContents.isFocused()).to.be.true('focuses window'); }); }); describe('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 = once(w.webContents, 'paint') as Promise<[any, Electron.Rectangle, Electron.NativeImage]>; 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 = once(w.webContents, 'paint') as Promise<[any, Electron.Rectangle, Electron.NativeImage]>; 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 = once(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 = once(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.stopPainting(); w.webContents.startPainting(); await once(w.webContents, 'paint') as [any, Electron.Rectangle, Electron.NativeImage]; 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 once(w.webContents, 'paint') as [any, Electron.Rectangle, Electron.NativeImage]; expect(w.webContents.getFrameRate()).to.equal(60); }); it('has default frame rate (property)', async () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await once(w.webContents, 'paint') as [any, Electron.Rectangle, Electron.NativeImage]; expect(w.webContents.frameRate).to.equal(60); }); it('sets custom frame rate (function)', async () => { const domReady = once(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.setFrameRate(30); await once(w.webContents, 'paint') as [any, Electron.Rectangle, Electron.NativeImage]; expect(w.webContents.getFrameRate()).to.equal(30); }); it('sets custom frame rate (property)', async () => { const domReady = once(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.frameRate = 30; await once(w.webContents, 'paint') as [any, Electron.Rectangle, Electron.NativeImage]; expect(w.webContents.frameRate).to.equal(30); }); }); }); describe('"transparent" option', () => { afterEach(closeAllWindows); ifit(process.platform !== 'linux')('correctly returns isMaximized() when the window is maximized then minimized', async () => { const w = new BrowserWindow({ frame: false, transparent: true }); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMaximized()).to.be.false(); expect(w.isMinimized()).to.be.true(); }); // 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 once(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 === 'darwin' && process.arch === 'x64')('should not display a visible background', async () => { const display = screen.getPrimaryDisplay(); const backgroundWindow = new BrowserWindow({ ...display.bounds, frame: false, backgroundColor: HexColors.GREEN, hasShadow: false }); await backgroundWindow.loadURL('about:blank'); const foregroundWindow = new BrowserWindow({ ...display.bounds, show: true, transparent: true, frame: false, hasShadow: false }); const colorFile = path.join(__dirname, 'fixtures', 'pages', 'half-background-color.html'); await foregroundWindow.loadFile(colorFile); await setTimeout(1000); 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, HexColors.GREEN)).to.be.true(); expect(areColorsSimilar(rightHalfColor, HexColors.RED)).to.be.true(); }); ifit(process.platform === 'darwin')('Allows setting a transparent window via CSS', async () => { const display = screen.getPrimaryDisplay(); const backgroundWindow = new BrowserWindow({ ...display.bounds, frame: false, backgroundColor: HexColors.PURPLE, hasShadow: false }); await backgroundWindow.loadURL('about:blank'); const foregroundWindow = new BrowserWindow({ ...display.bounds, frame: false, transparent: true, hasShadow: false, webPreferences: { contextIsolation: false, nodeIntegration: true } }); foregroundWindow.loadFile(path.join(__dirname, 'fixtures', 'pages', 'css-transparent.html')); await once(ipcMain, 'set-transparent'); await setTimeout(); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); expect(areColorsSimilar(centerColor, HexColors.PURPLE)).to.be.true(); }); // Linux and arm64 platforms (WOA and macOS) do not return any capture sources ifit(process.platform === 'darwin' && process.arch === 'x64')('should not make background transparent if falsy', async () => { const display = screen.getPrimaryDisplay(); for (const transparent of [false, undefined]) { const window = new BrowserWindow({ ...display.bounds, transparent }); await once(window, 'show'); await window.webContents.loadURL('data:text/html,<head><meta name="color-scheme" content="dark"></head>'); await setTimeout(500); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); window.close(); // color-scheme is set to dark so background should not be white expect(areColorsSimilar(centerColor, HexColors.WHITE)).to.be.false(); } }); }); describe('"backgroundColor" option', () => { afterEach(closeAllWindows); // Linux/WOA doesn't return any capture sources. ifit(process.platform === 'darwin')('should display the set color', async () => { const display = screen.getPrimaryDisplay(); const w = new BrowserWindow({ ...display.bounds, show: true, backgroundColor: HexColors.BLUE }); w.loadURL('about:blank'); await once(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, HexColors.BLUE)).to.be.true(); }); }); });
closed
electron/electron
https://github.com/electron/electron
39,445
[Bug]: `BrowserWindow`'s top offset (`y` value) is set to 25 when trying to set it explicitly below 25 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 25.4.0 ### What operating system are you using? macOS ### Operating System Version macOS Monterey 12.6 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior BrowserWindow's top offset from screen (`y` value) should be respected when explicitly specified to be below 25 ### Actual Behavior BrowserWindow's top offset from screen (`y` value) is always set to 25 when explicitly specified to be below 25 ### Testcase Gist URL https://gist.github.com/7bd49c0498a46da629adf1327fc03160 ### Additional Information Both when creating a new `BrowserWindow` like so: ```js const win = new BrowserWindow({ x: 15, y: 16, }) console.log(win.getBounds()); // logs { x: 15, y: 25, width: 800, height: 600 } ``` or when setting the `BrowserWindow` position after creation like so: ```js const win = new BrowserWindow(); win.setPosition(15,16); console.log(win.getBounds()); // logs { x: 15, y: 25, width: 800, height: 600 } ``` When the y-value above is set to anything below 25, it always goes to 25 and never below. However, setting the y-value above 25 works correctly and returns position that was specified. This issue doesn't seem to exist on Windows and Linux and seems to isolated to MacOS. I did find a possibly related issue filed [here](https://github.com/electron/electron/issues/39257)
https://github.com/electron/electron/issues/39445
https://github.com/electron/electron/pull/39512
dd8df3b0c47102fe5686f516c80e698ab555a6f9
31dfde7fa63c19a299e18b2dcef7cdf922d2a400
2023-08-09T18:17:51Z
c++
2023-08-17T09:02:03Z
docs/api/browser-window.md
# BrowserWindow > Create and control browser windows. Process: [Main](../glossary.md#main-process) This module cannot be used until the `ready` event of the `app` module is emitted. ```javascript // In the main process. const { BrowserWindow } = require('electron') const win = new BrowserWindow({ width: 800, height: 600 }) // Load a remote URL win.loadURL('https://github.com') // Or load a local HTML file win.loadFile('index.html') ``` ## Window customization The `BrowserWindow` class exposes various ways to modify the look and behavior of your app's windows. For more details, see the [Window Customization](../tutorial/window-customization.md) tutorial. ## Showing the window gracefully When loading a page in the window directly, users may see the page load incrementally, which is not a good experience for a native app. To make the window display without a visual flash, there are two solutions for different situations. ### Using the `ready-to-show` event While loading the page, the `ready-to-show` event will be emitted when the renderer process has rendered the page for the first time if the window has not been shown yet. Showing the window after this event will have no visual flash: ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow({ show: false }) win.once('ready-to-show', () => { win.show() }) ``` This event is usually emitted after the `did-finish-load` event, but for pages with many remote resources, it may be emitted before the `did-finish-load` event. Please note that using this event implies that the renderer will be considered "visible" and paint even though `show` is false. This event will never fire if you use `paintWhenInitiallyHidden: false` ### Setting the `backgroundColor` property For a complex app, the `ready-to-show` event could be emitted too late, making the app feel slow. In this case, it is recommended to show the window immediately, and use a `backgroundColor` close to your app's background: ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow({ backgroundColor: '#2e2c29' }) win.loadURL('https://github.com') ``` Note that even for apps that use `ready-to-show` event, it is still recommended to set `backgroundColor` to make the app feel more native. Some examples of valid `backgroundColor` values include: ```js const win = new BrowserWindow() win.setBackgroundColor('hsl(230, 100%, 50%)') win.setBackgroundColor('rgb(255, 145, 145)') win.setBackgroundColor('#ff00a3') win.setBackgroundColor('blueviolet') ``` For more information about these color types see valid options in [win.setBackgroundColor](browser-window.md#winsetbackgroundcolorbackgroundcolor). ## Parent and child windows By using `parent` option, you can create child windows: ```javascript const { BrowserWindow } = require('electron') const top = new BrowserWindow() const child = new BrowserWindow({ parent: top }) child.show() top.show() ``` The `child` window will always show on top of the `top` window. ## Modal windows A modal window is a child window that disables parent window, to create a modal window, you have to set both `parent` and `modal` options: ```javascript const { BrowserWindow } = require('electron') const top = new BrowserWindow() const child = new BrowserWindow({ parent: top, modal: true, show: false }) child.loadURL('https://github.com') child.once('ready-to-show', () => { child.show() }) ``` ## Page visibility The [Page Visibility API][page-visibility-api] works as follows: * On all platforms, the visibility state tracks whether the window is hidden/minimized or not. * Additionally, on macOS, the visibility state also tracks the window occlusion state. If the window is occluded (i.e. fully covered) by another window, the visibility state will be `hidden`. On other platforms, the visibility state will be `hidden` only when the window is minimized or explicitly hidden with `win.hide()`. * If a `BrowserWindow` is created with `show: false`, the initial visibility state will be `visible` despite the window actually being hidden. * If `backgroundThrottling` is disabled, the visibility state will remain `visible` even if the window is minimized, occluded, or hidden. It is recommended that you pause expensive operations when the visibility state is `hidden` in order to minimize power consumption. ## Platform notices * On macOS modal windows will be displayed as sheets attached to the parent window. * On macOS the child windows will keep the relative position to parent window when parent window moves, while on Windows and Linux child windows will not move. * On Linux the type of modal windows will be changed to `dialog`. * On Linux many desktop environments do not support hiding a modal window. ## Class: BrowserWindow > Create and control browser windows. Process: [Main](../glossary.md#main-process) `BrowserWindow` is an [EventEmitter][event-emitter]. It creates a new `BrowserWindow` with native properties as set by the `options`. ### `new BrowserWindow([options])` * `options` [BrowserWindowConstructorOptions](structures/browser-window-options.md?inline) (optional) ### Instance Events Objects created with `new BrowserWindow` emit the following events: **Note:** Some events are only available on specific operating systems and are labeled as such. #### Event: 'page-title-updated' Returns: * `event` Event * `title` string * `explicitSet` boolean Emitted when the document changed its title, calling `event.preventDefault()` will prevent the native window's title from changing. `explicitSet` is false when title is synthesized from file URL. #### Event: 'close' Returns: * `event` Event Emitted when the window is going to be closed. It's emitted before the `beforeunload` and `unload` event of the DOM. Calling `event.preventDefault()` will cancel the close. Usually you would want to use the `beforeunload` handler to decide whether the window should be closed, which will also be called when the window is reloaded. In Electron, returning any value other than `undefined` would cancel the close. For example: ```javascript window.onbeforeunload = (e) => { console.log('I do not want to be closed') // Unlike usual browsers that a message box will be prompted to users, returning // a non-void value will silently cancel the close. // It is recommended to use the dialog API to let the user confirm closing the // application. e.returnValue = false } ``` _**Note**: There is a subtle difference between the behaviors of `window.onbeforeunload = handler` and `window.addEventListener('beforeunload', handler)`. It is recommended to always set the `event.returnValue` explicitly, instead of only returning a value, as the former works more consistently within Electron._ #### Event: 'closed' Emitted when the window is closed. After you have received this event you should remove the reference to the window and avoid using it any more. #### Event: 'session-end' _Windows_ Emitted when window session is going to end due to force shutdown or machine restart or session log off. #### Event: 'unresponsive' Emitted when the web page becomes unresponsive. #### Event: 'responsive' Emitted when the unresponsive web page becomes responsive again. #### Event: 'blur' Emitted when the window loses focus. #### Event: 'focus' Emitted when the window gains focus. #### Event: 'show' Emitted when the window is shown. #### Event: 'hide' Emitted when the window is hidden. #### Event: 'ready-to-show' Emitted when the web page has been rendered (while not being shown) and window can be displayed without a visual flash. Please note that using this event implies that the renderer will be considered "visible" and paint even though `show` is false. This event will never fire if you use `paintWhenInitiallyHidden: false` #### Event: 'maximize' Emitted when window is maximized. #### Event: 'unmaximize' Emitted when the window exits from a maximized state. #### Event: 'minimize' Emitted when the window is minimized. #### Event: 'restore' Emitted when the window is restored from a minimized state. #### Event: 'will-resize' _macOS_ _Windows_ Returns: * `event` Event * `newBounds` [Rectangle](structures/rectangle.md) - Size the window is being resized to. * `details` Object * `edge` (string) - The edge of the window being dragged for resizing. Can be `bottom`, `left`, `right`, `top-left`, `top-right`, `bottom-left` or `bottom-right`. Emitted before the window is resized. Calling `event.preventDefault()` will prevent the window from being resized. Note that this is only emitted when the window is being resized manually. Resizing the window with `setBounds`/`setSize` will not emit this event. The possible values and behaviors of the `edge` option are platform dependent. Possible values are: * On Windows, possible values are `bottom`, `top`, `left`, `right`, `top-left`, `top-right`, `bottom-left`, `bottom-right`. * On macOS, possible values are `bottom` and `right`. * The value `bottom` is used to denote vertical resizing. * The value `right` is used to denote horizontal resizing. #### Event: 'resize' Emitted after the window has been resized. #### Event: 'resized' _macOS_ _Windows_ Emitted once when the window has finished being resized. This is usually emitted when the window has been resized manually. On macOS, resizing the window with `setBounds`/`setSize` and setting the `animate` parameter to `true` will also emit this event once resizing has finished. #### Event: 'will-move' _macOS_ _Windows_ Returns: * `event` Event * `newBounds` [Rectangle](structures/rectangle.md) - Location the window is being moved to. Emitted before the window is moved. On Windows, calling `event.preventDefault()` will prevent the window from being moved. Note that this is only emitted when the window is being moved manually. Moving the window with `setPosition`/`setBounds`/`center` will not emit this event. #### Event: 'move' Emitted when the window is being moved to a new position. #### Event: 'moved' _macOS_ _Windows_ Emitted once when the window is moved to a new position. **Note**: On macOS this event is an alias of `move`. #### Event: 'enter-full-screen' Emitted when the window enters a full-screen state. #### Event: 'leave-full-screen' Emitted when the window leaves a full-screen state. #### 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: 'always-on-top-changed' Returns: * `event` Event * `isAlwaysOnTop` boolean Emitted when the window is set or unset to show always on top of other windows. #### Event: 'app-command' _Windows_ _Linux_ Returns: * `event` Event * `command` string Emitted when an [App Command](https://learn.microsoft.com/en-us/windows/win32/inputdev/wm-appcommand) is invoked. These are typically related to keyboard media keys or browser commands, as well as the "Back" button built into some mice on Windows. Commands are lowercased, underscores are replaced with hyphens, and the `APPCOMMAND_` prefix is stripped off. e.g. `APPCOMMAND_BROWSER_BACKWARD` is emitted as `browser-backward`. ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow() win.on('app-command', (e, cmd) => { // Navigate the window back when the user hits their mouse back button if (cmd === 'browser-backward' && win.webContents.canGoBack()) { win.webContents.goBack() } }) ``` The following app commands are explicitly supported on Linux: * `browser-backward` * `browser-forward` #### Event: 'scroll-touch-begin' _macOS_ _Deprecated_ Emitted when scroll wheel event phase has begun. > **Note** > This event is deprecated beginning in Electron 22.0.0. See [Breaking > Changes](../breaking-changes.md#deprecated-browserwindow-scroll-touch--events) > for details of how to migrate to using the [WebContents > `input-event`](./web-contents.md#event-input-event) event. #### Event: 'scroll-touch-end' _macOS_ _Deprecated_ Emitted when scroll wheel event phase has ended. > **Note** > This event is deprecated beginning in Electron 22.0.0. See [Breaking > Changes](../breaking-changes.md#deprecated-browserwindow-scroll-touch--events) > for details of how to migrate to using the [WebContents > `input-event`](./web-contents.md#event-input-event) event. #### Event: 'scroll-touch-edge' _macOS_ _Deprecated_ Emitted when scroll wheel event phase filed upon reaching the edge of element. > **Note** > This event is deprecated beginning in Electron 22.0.0. See [Breaking > Changes](../breaking-changes.md#deprecated-browserwindow-scroll-touch--events) > for details of how to migrate to using the [WebContents > `input-event`](./web-contents.md#event-input-event) event. #### Event: 'swipe' _macOS_ Returns: * `event` Event * `direction` string Emitted on 3-finger swipe. Possible directions are `up`, `right`, `down`, `left`. The method underlying this event is built to handle older macOS-style trackpad swiping, where the content on the screen doesn't move with the swipe. Most macOS trackpads are not configured to allow this kind of swiping anymore, so in order for it to emit properly the 'Swipe between pages' preference in `System Preferences > Trackpad > More Gestures` must be set to 'Swipe with two or three fingers'. #### Event: 'rotate-gesture' _macOS_ Returns: * `event` Event * `rotation` Float Emitted on trackpad rotation gesture. Continually emitted until rotation gesture is ended. The `rotation` value on each emission is the angle in degrees rotated since the last emission. The last emitted event upon a rotation gesture will always be of value `0`. Counter-clockwise rotation values are positive, while clockwise ones are negative. #### Event: 'sheet-begin' _macOS_ Emitted when the window opens a sheet. #### Event: 'sheet-end' _macOS_ Emitted when the window has closed a sheet. #### Event: 'new-window-for-tab' _macOS_ Emitted when the native new tab button is clicked. #### Event: 'system-context-menu' _Windows_ Returns: * `event` Event * `point` [Point](structures/point.md) - The screen coordinates the context menu was triggered at Emitted when the system context menu is triggered on the window, this is normally only triggered when the user right clicks on the non-client area of your window. This is the window titlebar or any area you have declared as `-webkit-app-region: drag` in a frameless window. Calling `event.preventDefault()` will prevent the menu from being displayed. ### Static Methods The `BrowserWindow` class has the following static methods: #### `BrowserWindow.getAllWindows()` Returns `BrowserWindow[]` - An array of all opened browser windows. #### `BrowserWindow.getFocusedWindow()` Returns `BrowserWindow | null` - The window that is focused in this application, otherwise returns `null`. #### `BrowserWindow.fromWebContents(webContents)` * `webContents` [WebContents](web-contents.md) Returns `BrowserWindow | null` - The window that owns the given `webContents` or `null` if the contents are not owned by a window. #### `BrowserWindow.fromBrowserView(browserView)` * `browserView` [BrowserView](browser-view.md) Returns `BrowserWindow | null` - The window that owns the given `browserView`. If the given view is not attached to any window, returns `null`. #### `BrowserWindow.fromId(id)` * `id` Integer Returns `BrowserWindow | null` - The window with the given `id`. ### Instance Properties Objects created with `new BrowserWindow` have the following properties: ```javascript const { BrowserWindow } = require('electron') // In this example `win` is our instance const win = new BrowserWindow({ width: 800, height: 600 }) win.loadURL('https://github.com') ``` #### `win.webContents` _Readonly_ A `WebContents` object this window owns. All web page related events and operations will be done via it. See the [`webContents` documentation](web-contents.md) for its methods and events. #### `win.id` _Readonly_ A `Integer` property representing the unique ID of the window. Each ID is unique among all `BrowserWindow` instances of the entire Electron application. #### `win.autoHideMenuBar` A `boolean` property that determines whether the window menu bar should hide itself automatically. Once set, the menu bar will only show when users press the single `Alt` key. If the menu bar is already visible, setting this property to `true` won't hide it immediately. #### `win.simpleFullScreen` A `boolean` property that determines whether the window is in simple (pre-Lion) fullscreen mode. #### `win.fullScreen` A `boolean` property that determines whether the window is in fullscreen mode. #### `win.focusable` _Windows_ _macOS_ A `boolean` property that determines whether the window is focusable. #### `win.visibleOnAllWorkspaces` _macOS_ _Linux_ A `boolean` property that determines whether the window is visible on all workspaces. **Note:** Always returns false on Windows. #### `win.shadow` A `boolean` property that determines whether the window has a shadow. #### `win.menuBarVisible` _Windows_ _Linux_ A `boolean` property that determines whether the menu bar should be visible. **Note:** If the menu bar is auto-hide, users can still bring up the menu bar by pressing the single `Alt` key. #### `win.kiosk` A `boolean` property that determines whether the window is in kiosk mode. #### `win.documentEdited` _macOS_ A `boolean` property that specifies whether the window’s document has been edited. The icon in title bar will become gray when set to `true`. #### `win.representedFilename` _macOS_ A `string` property that determines the pathname of the file the window represents, and the icon of the file will show in window's title bar. #### `win.title` A `string` property that determines the title of the native window. **Note:** The title of the web page can be different from the title of the native window. #### `win.minimizable` _macOS_ _Windows_ A `boolean` property that determines whether the window can be manually minimized by user. On Linux the setter is a no-op, although the getter returns `true`. #### `win.maximizable` _macOS_ _Windows_ A `boolean` property that determines whether the window can be manually maximized by user. On Linux the setter is a no-op, although the getter returns `true`. #### `win.fullScreenable` A `boolean` property that determines whether the maximize/zoom window button toggles fullscreen mode or maximizes the window. #### `win.resizable` A `boolean` property that determines whether the window can be manually resized by user. #### `win.closable` _macOS_ _Windows_ A `boolean` property that determines whether the window can be manually closed by user. On Linux the setter is a no-op, although the getter returns `true`. #### `win.movable` _macOS_ _Windows_ A `boolean` property that determines Whether the window can be moved by user. On Linux the setter is a no-op, although the getter returns `true`. #### `win.excludedFromShownWindowsMenu` _macOS_ A `boolean` property that determines whether the window is excluded from the application’s Windows menu. `false` by default. ```js @ts-expect-error=[11] const win = new BrowserWindow({ height: 600, width: 600 }) const template = [ { role: 'windowmenu' } ] win.excludedFromShownWindowsMenu = true const menu = Menu.buildFromTemplate(template) Menu.setApplicationMenu(menu) ``` #### `win.accessibleTitle` A `string` property that defines an alternative title provided only to accessibility tools such as screen readers. This string is not directly visible to users. ### Instance Methods Objects created with `new BrowserWindow` have the following instance methods: **Note:** Some methods are only available on specific operating systems and are labeled as such. #### `win.destroy()` Force closing the window, the `unload` and `beforeunload` event won't be emitted for the web page, and `close` event will also not be emitted for this window, but it guarantees the `closed` event will be emitted. #### `win.close()` Try to close the window. This has the same effect as a user manually clicking the close button of the window. The web page may cancel the close though. See the [close event](#event-close). #### `win.focus()` Focuses on the window. #### `win.blur()` Removes focus from the window. #### `win.isFocused()` Returns `boolean` - Whether the window is focused. #### `win.isDestroyed()` Returns `boolean` - Whether the window is destroyed. #### `win.show()` Shows and gives focus to the window. #### `win.showInactive()` Shows the window but doesn't focus on it. #### `win.hide()` Hides the window. #### `win.isVisible()` Returns `boolean` - Whether the window is visible to the user in the foreground of the app. #### `win.isModal()` Returns `boolean` - Whether current window is a modal window. #### `win.maximize()` Maximizes the window. This will also show (but not focus) the window if it isn't being displayed already. #### `win.unmaximize()` Unmaximizes the window. #### `win.isMaximized()` Returns `boolean` - Whether the window is maximized. #### `win.minimize()` Minimizes the window. On some platforms the minimized window will be shown in the Dock. #### `win.restore()` Restores the window from minimized state to its previous state. #### `win.isMinimized()` Returns `boolean` - Whether the window is minimized. #### `win.setFullScreen(flag)` * `flag` boolean Sets whether the window should be in fullscreen mode. **Note:** On macOS, fullscreen transitions take place asynchronously. If further actions depend on the fullscreen state, use the ['enter-full-screen'](browser-window.md#event-enter-full-screen) or ['leave-full-screen'](browser-window.md#event-leave-full-screen) events. #### `win.isFullScreen()` Returns `boolean` - Whether the window is in fullscreen mode. #### `win.setSimpleFullScreen(flag)` _macOS_ * `flag` boolean Enters or leaves simple fullscreen mode. Simple fullscreen mode emulates the native fullscreen behavior found in versions of macOS prior to Lion (10.7). #### `win.isSimpleFullScreen()` _macOS_ Returns `boolean` - Whether the window is in simple (pre-Lion) fullscreen mode. #### `win.isNormal()` Returns `boolean` - Whether the window is in normal state (not maximized, not minimized, not in fullscreen mode). #### `win.setAspectRatio(aspectRatio[, extraSize])` * `aspectRatio` Float - The aspect ratio to maintain for some portion of the content view. * `extraSize` [Size](structures/size.md) (optional) _macOS_ - The extra size not to be included while maintaining the aspect ratio. This will make a window maintain an aspect ratio. The extra size allows a developer to have space, specified in pixels, not included within the aspect ratio calculations. This API already takes into account the difference between a window's size and its content size. Consider a normal window with an HD video player and associated controls. Perhaps there are 15 pixels of controls on the left edge, 25 pixels of controls on the right edge and 50 pixels of controls below the player. In order to maintain a 16:9 aspect ratio (standard aspect ratio for HD @1920x1080) within the player itself we would call this function with arguments of 16/9 and { width: 40, height: 50 }. The second argument doesn't care where the extra width and height are within the content view--only that they exist. Sum any extra width and height areas you have within the overall content view. The aspect ratio is not respected when window is resized programmatically with APIs like `win.setSize`. To reset an aspect ratio, pass 0 as the `aspectRatio` value: `win.setAspectRatio(0)`. #### `win.setBackgroundColor(backgroundColor)` * `backgroundColor` string - Color in Hex, RGB, RGBA, HSL, HSLA or named CSS color format. The alpha channel is optional for the hex type. Examples of valid `backgroundColor` values: * Hex * #fff (shorthand RGB) * #ffff (shorthand ARGB) * #ffffff (RGB) * #ffffffff (ARGB) * RGB * rgb\((\[\d]+),\s*(\[\d]+),\s*(\[\d]+)\) * e.g. rgb(255, 255, 255) * RGBA * rgba\((\[\d]+),\s*(\[\d]+),\s*(\[\d]+),\s*(\[\d.]+)\) * e.g. rgba(255, 255, 255, 1.0) * HSL * hsl\((-?\[\d.]+),\s*(\[\d.]+)%,\s*(\[\d.]+)%\) * e.g. hsl(200, 20%, 50%) * HSLA * hsla\((-?\[\d.]+),\s*(\[\d.]+)%,\s*(\[\d.]+)%,\s*(\[\d.]+)\) * e.g. hsla(200, 20%, 50%, 0.5) * Color name * Options are listed in [SkParseColor.cpp](https://source.chromium.org/chromium/chromium/src/+/main:third_party/skia/src/utils/SkParseColor.cpp;l=11-152;drc=eea4bf52cb0d55e2a39c828b017c80a5ee054148) * Similar to CSS Color Module Level 3 keywords, but case-sensitive. * e.g. `blueviolet` or `red` Sets the background color of the window. See [Setting `backgroundColor`](#setting-the-backgroundcolor-property). #### `win.previewFile(path[, displayName])` _macOS_ * `path` string - The absolute path to the file to preview with QuickLook. This is important as Quick Look uses the file name and file extension on the path to determine the content type of the file to open. * `displayName` string (optional) - The name of the file to display on the Quick Look modal view. This is purely visual and does not affect the content type of the file. Defaults to `path`. Uses [Quick Look][quick-look] to preview a file at a given path. #### `win.closeFilePreview()` _macOS_ Closes the currently open [Quick Look][quick-look] panel. #### `win.setBounds(bounds[, animate])` * `bounds` Partial<[Rectangle](structures/rectangle.md)> * `animate` boolean (optional) _macOS_ Resizes and moves the window to the supplied bounds. Any properties that are not supplied will default to their current values. ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow() // set all bounds properties win.setBounds({ x: 440, y: 225, width: 800, height: 600 }) // set a single bounds property win.setBounds({ width: 100 }) // { x: 440, y: 225, width: 100, height: 600 } console.log(win.getBounds()) ``` #### `win.getBounds()` Returns [`Rectangle`](structures/rectangle.md) - The `bounds` of the window as `Object`. #### `win.getBackgroundColor()` Returns `string` - Gets the background color of the window in Hex (`#RRGGBB`) format. See [Setting `backgroundColor`](#setting-the-backgroundcolor-property). **Note:** The alpha value is _not_ returned alongside the red, green, and blue values. #### `win.setContentBounds(bounds[, animate])` * `bounds` [Rectangle](structures/rectangle.md) * `animate` boolean (optional) _macOS_ Resizes and moves the window's client area (e.g. the web page) to the supplied bounds. #### `win.getContentBounds()` Returns [`Rectangle`](structures/rectangle.md) - The `bounds` of the window's client area as `Object`. #### `win.getNormalBounds()` Returns [`Rectangle`](structures/rectangle.md) - Contains the window bounds of the normal state **Note:** whatever the current state of the window : maximized, minimized or in fullscreen, this function always returns the position and size of the window in normal state. In normal state, getBounds and getNormalBounds returns the same [`Rectangle`](structures/rectangle.md). #### `win.setEnabled(enable)` * `enable` boolean Disable or enable the window. #### `win.isEnabled()` Returns `boolean` - whether the window is enabled. #### `win.setSize(width, height[, animate])` * `width` Integer * `height` Integer * `animate` boolean (optional) _macOS_ Resizes the window to `width` and `height`. If `width` or `height` are below any set minimum size constraints the window will snap to its minimum size. #### `win.getSize()` Returns `Integer[]` - Contains the window's width and height. #### `win.setContentSize(width, height[, animate])` * `width` Integer * `height` Integer * `animate` boolean (optional) _macOS_ Resizes the window's client area (e.g. the web page) to `width` and `height`. #### `win.getContentSize()` Returns `Integer[]` - Contains the window's client area's width and height. #### `win.setMinimumSize(width, height)` * `width` Integer * `height` Integer Sets the minimum size of window to `width` and `height`. #### `win.getMinimumSize()` Returns `Integer[]` - Contains the window's minimum width and height. #### `win.setMaximumSize(width, height)` * `width` Integer * `height` Integer Sets the maximum size of window to `width` and `height`. #### `win.getMaximumSize()` Returns `Integer[]` - Contains the window's maximum width and height. #### `win.setResizable(resizable)` * `resizable` boolean Sets whether the window can be manually resized by the user. #### `win.isResizable()` Returns `boolean` - Whether the window can be manually resized by the user. #### `win.setMovable(movable)` _macOS_ _Windows_ * `movable` boolean Sets whether the window can be moved by user. On Linux does nothing. #### `win.isMovable()` _macOS_ _Windows_ Returns `boolean` - Whether the window can be moved by user. On Linux always returns `true`. #### `win.setMinimizable(minimizable)` _macOS_ _Windows_ * `minimizable` boolean Sets whether the window can be manually minimized by user. On Linux does nothing. #### `win.isMinimizable()` _macOS_ _Windows_ Returns `boolean` - Whether the window can be manually minimized by the user. On Linux always returns `true`. #### `win.setMaximizable(maximizable)` _macOS_ _Windows_ * `maximizable` boolean Sets whether the window can be manually maximized by user. On Linux does nothing. #### `win.isMaximizable()` _macOS_ _Windows_ Returns `boolean` - Whether the window can be manually maximized by user. On Linux always returns `true`. #### `win.setFullScreenable(fullscreenable)` * `fullscreenable` boolean Sets whether the maximize/zoom window button toggles fullscreen mode or maximizes the window. #### `win.isFullScreenable()` Returns `boolean` - Whether the maximize/zoom window button toggles fullscreen mode or maximizes the window. #### `win.setClosable(closable)` _macOS_ _Windows_ * `closable` boolean Sets whether the window can be manually closed by user. On Linux does nothing. #### `win.isClosable()` _macOS_ _Windows_ Returns `boolean` - Whether the window can be manually closed by user. On Linux always returns `true`. #### `win.setHiddenInMissionControl(hidden)` _macOS_ * `hidden` boolean Sets whether the window will be hidden when the user toggles into mission control. #### `win.isHiddenInMissionControl()` _macOS_ Returns `boolean` - Whether the window will be hidden when the user toggles into mission control. #### `win.setAlwaysOnTop(flag[, level][, relativeLevel])` * `flag` boolean * `level` string (optional) _macOS_ _Windows_ - Values include `normal`, `floating`, `torn-off-menu`, `modal-panel`, `main-menu`, `status`, `pop-up-menu`, `screen-saver`, and ~~`dock`~~ (Deprecated). The default is `floating` when `flag` is true. The `level` is reset to `normal` when the flag is false. Note that from `floating` to `status` included, the window is placed below the Dock on macOS and below the taskbar on Windows. From `pop-up-menu` to a higher it is shown above the Dock on macOS and above the taskbar on Windows. See the [macOS docs][window-levels] for more details. * `relativeLevel` Integer (optional) _macOS_ - The number of layers higher to set this window relative to the given `level`. The default is `0`. Note that Apple discourages setting levels higher than 1 above `screen-saver`. Sets whether the window should show always on top of other windows. After setting this, the window is still a normal window, not a toolbox window which can not be focused on. #### `win.isAlwaysOnTop()` Returns `boolean` - Whether the window is always on top of other windows. #### `win.moveAbove(mediaSourceId)` * `mediaSourceId` string - Window id in the format of DesktopCapturerSource's id. For example "window:1869:0". Moves window above the source window in the sense of z-order. If the `mediaSourceId` is not of type window or if the window does not exist then this method throws an error. #### `win.moveTop()` Moves window to top(z-order) regardless of focus #### `win.center()` Moves window to the center of the screen. #### `win.setPosition(x, y[, animate])` * `x` Integer * `y` Integer * `animate` boolean (optional) _macOS_ Moves window to `x` and `y`. #### `win.getPosition()` Returns `Integer[]` - Contains the window's current position. #### `win.setTitle(title)` * `title` string Changes the title of native window to `title`. #### `win.getTitle()` Returns `string` - The title of the native window. **Note:** The title of the web page can be different from the title of the native window. #### `win.setSheetOffset(offsetY[, offsetX])` _macOS_ * `offsetY` Float * `offsetX` Float (optional) Changes the attachment point for sheets on macOS. By default, sheets are attached just below the window frame, but you may want to display them beneath a HTML-rendered toolbar. For example: ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow() const toolbarRect = document.getElementById('toolbar').getBoundingClientRect() win.setSheetOffset(toolbarRect.height) ``` #### `win.flashFrame(flag)` * `flag` boolean Starts or stops flashing the window to attract user's attention. #### `win.setSkipTaskbar(skip)` _macOS_ _Windows_ * `skip` boolean Makes the window not show in the taskbar. #### `win.setKiosk(flag)` * `flag` boolean Enters or leaves kiosk mode. #### `win.isKiosk()` Returns `boolean` - Whether the window is in kiosk mode. #### `win.isTabletMode()` _Windows_ Returns `boolean` - Whether the window is in Windows 10 tablet mode. Since Windows 10 users can [use their PC as tablet](https://support.microsoft.com/en-us/help/17210/windows-10-use-your-pc-like-a-tablet), under this mode apps can choose to optimize their UI for tablets, such as enlarging the titlebar and hiding titlebar buttons. This API returns whether the window is in tablet mode, and the `resize` event can be be used to listen to changes to tablet mode. #### `win.getMediaSourceId()` Returns `string` - Window id in the format of DesktopCapturerSource's id. For example "window:1324:0". More precisely the format is `window:id:other_id` where `id` is `HWND` on Windows, `CGWindowID` (`uint64_t`) on macOS and `Window` (`unsigned long`) on Linux. `other_id` is used to identify web contents (tabs) so within the same top level window. #### `win.getNativeWindowHandle()` Returns `Buffer` - The platform-specific handle of the window. The native type of the handle is `HWND` on Windows, `NSView*` on macOS, and `Window` (`unsigned long`) on Linux. #### `win.hookWindowMessage(message, callback)` _Windows_ * `message` Integer * `callback` Function * `wParam` Buffer - The `wParam` provided to the WndProc * `lParam` Buffer - The `lParam` provided to the WndProc Hooks a windows message. The `callback` is called when the message is received in the WndProc. #### `win.isWindowMessageHooked(message)` _Windows_ * `message` Integer Returns `boolean` - `true` or `false` depending on whether the message is hooked. #### `win.unhookWindowMessage(message)` _Windows_ * `message` Integer Unhook the window message. #### `win.unhookAllWindowMessages()` _Windows_ Unhooks all of the window messages. #### `win.setRepresentedFilename(filename)` _macOS_ * `filename` string Sets the pathname of the file the window represents, and the icon of the file will show in window's title bar. #### `win.getRepresentedFilename()` _macOS_ Returns `string` - The pathname of the file the window represents. #### `win.setDocumentEdited(edited)` _macOS_ * `edited` boolean Specifies whether the window’s document has been edited, and the icon in title bar will become gray when set to `true`. #### `win.isDocumentEdited()` _macOS_ Returns `boolean` - Whether the window's document has been edited. #### `win.focusOnWebView()` #### `win.blurWebView()` #### `win.capturePage([rect, opts])` * `rect` [Rectangle](structures/rectangle.md) (optional) - The bounds to capture * `opts` Object (optional) * `stayHidden` boolean (optional) - Keep the page hidden instead of visible. Default is `false`. * `stayAwake` boolean (optional) - Keep the system awake instead of allowing it to sleep. Default is `false`. 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. If the page is not visible, `rect` may be empty. 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. #### `win.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)). Same as [`webContents.loadURL(url[, options])`](web-contents.md#contentsloadurlurl-options). The `url` can be a remote address (e.g. `http://`) or a path to a local HTML file using the `file://` protocol. To ensure that file URLs are properly formatted, it is recommended to use Node's [`url.format`](https://nodejs.org/api/url.html#url_url_format_urlobject) method: ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow() const url = require('url').format({ protocol: 'file', slashes: true, pathname: require('path').join(__dirname, 'index.html') }) win.loadURL(url) ``` You can load a URL using a `POST` request with URL-encoded data by doing the following: ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow() win.loadURL('http://localhost:8000/post', { postData: [{ type: 'rawData', bytes: Buffer.from('hello=world') }], extraHeaders: 'Content-Type: application/x-www-form-urlencoded' }) ``` #### `win.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)). Same as `webContents.loadFile`, `filePath` should be a path to an HTML file relative to the root of your application. See the `webContents` docs for more information. #### `win.reload()` Same as `webContents.reload`. #### `win.setMenu(menu)` _Linux_ _Windows_ * `menu` Menu | null Sets the `menu` as the window's menu bar. #### `win.removeMenu()` _Linux_ _Windows_ Remove the window's menu bar. #### `win.setProgressBar(progress[, options])` * `progress` Double * `options` Object (optional) * `mode` string _Windows_ - Mode for the progress bar. Can be `none`, `normal`, `indeterminate`, `error` or `paused`. Sets progress value in progress bar. Valid range is \[0, 1.0]. Remove progress bar when progress < 0; Change to indeterminate mode when progress > 1. On Linux platform, only supports Unity desktop environment, you need to specify the `*.desktop` file name to `desktopName` field in `package.json`. By default, it will assume `{app.name}.desktop`. On Windows, a mode can be passed. Accepted values are `none`, `normal`, `indeterminate`, `error`, and `paused`. If you call `setProgressBar` without a mode set (but with a value within the valid range), `normal` will be assumed. #### `win.setOverlayIcon(overlay, description)` _Windows_ * `overlay` [NativeImage](native-image.md) | null - the icon to display on the bottom right corner of the taskbar icon. If this parameter is `null`, the overlay is cleared * `description` string - a description that will be provided to Accessibility screen readers Sets a 16 x 16 pixel overlay onto the current taskbar icon, usually used to convey some sort of application status or to passively notify the user. #### `win.invalidateShadow()` _macOS_ Invalidates the window shadow so that it is recomputed based on the current window shape. `BrowserWindows` that are transparent can sometimes leave behind visual artifacts on macOS. This method can be used to clear these artifacts when, for example, performing an animation. #### `win.setHasShadow(hasShadow)` * `hasShadow` boolean Sets whether the window should have a shadow. #### `win.hasShadow()` Returns `boolean` - Whether the window has a shadow. #### `win.setOpacity(opacity)` _Windows_ _macOS_ * `opacity` number - between 0.0 (fully transparent) and 1.0 (fully opaque) Sets the opacity of the window. On Linux, does nothing. Out of bound number values are clamped to the \[0, 1] range. #### `win.getOpacity()` Returns `number` - between 0.0 (fully transparent) and 1.0 (fully opaque). On Linux, always returns 1. #### `win.setShape(rects)` _Windows_ _Linux_ _Experimental_ * `rects` [Rectangle[]](structures/rectangle.md) - Sets a shape on the window. Passing an empty list reverts the window to being rectangular. Setting a window shape determines the area within the window where the system permits drawing and user interaction. Outside of the given region, no pixels will be drawn and no mouse events will be registered. Mouse events outside of the region will not be received by that window, but will fall through to whatever is behind the window. #### `win.setThumbarButtons(buttons)` _Windows_ * `buttons` [ThumbarButton[]](structures/thumbar-button.md) Returns `boolean` - Whether the buttons were added successfully Add a thumbnail toolbar with a specified set of buttons to the thumbnail image of a window in a taskbar button layout. Returns a `boolean` object indicates whether the thumbnail has been added successfully. The number of buttons in thumbnail toolbar should be no greater than 7 due to the limited room. Once you setup the thumbnail toolbar, the toolbar cannot be removed due to the platform's limitation. But you can call the API with an empty array to clean the buttons. The `buttons` is an array of `Button` objects: * `Button` Object * `icon` [NativeImage](native-image.md) - The icon showing in thumbnail toolbar. * `click` Function * `tooltip` string (optional) - The text of the button's tooltip. * `flags` string[] (optional) - Control specific states and behaviors of the button. By default, it is `['enabled']`. The `flags` is an array that can include following `string`s: * `enabled` - The button is active and available to the user. * `disabled` - The button is disabled. It is present, but has a visual state indicating it will not respond to user action. * `dismissonclick` - When the button is clicked, the thumbnail window closes immediately. * `nobackground` - Do not draw a button border, use only the image. * `hidden` - The button is not shown to the user. * `noninteractive` - The button is enabled but not interactive; no pressed button state is drawn. This value is intended for instances where the button is used in a notification. #### `win.setThumbnailClip(region)` _Windows_ * `region` [Rectangle](structures/rectangle.md) - Region of the window Sets the region of the window to show as the thumbnail image displayed when hovering over the window in the taskbar. You can reset the thumbnail to be the entire window by specifying an empty region: `{ x: 0, y: 0, width: 0, height: 0 }`. #### `win.setThumbnailToolTip(toolTip)` _Windows_ * `toolTip` string Sets the toolTip that is displayed when hovering over the window thumbnail in the taskbar. #### `win.setAppDetails(options)` _Windows_ * `options` Object * `appId` string (optional) - Window's [App User Model ID](https://learn.microsoft.com/en-us/windows/win32/shell/appids). It has to be set, otherwise the other options will have no effect. * `appIconPath` string (optional) - Window's [Relaunch Icon](https://learn.microsoft.com/en-us/windows/win32/properties/props-system-appusermodel-relaunchiconresource). * `appIconIndex` Integer (optional) - Index of the icon in `appIconPath`. Ignored when `appIconPath` is not set. Default is `0`. * `relaunchCommand` string (optional) - Window's [Relaunch Command](https://learn.microsoft.com/en-us/windows/win32/properties/props-system-appusermodel-relaunchcommand). * `relaunchDisplayName` string (optional) - Window's [Relaunch Display Name](https://learn.microsoft.com/en-us/windows/win32/properties/props-system-appusermodel-relaunchdisplaynameresource). Sets the properties for the window's taskbar button. **Note:** `relaunchCommand` and `relaunchDisplayName` must always be set together. If one of those properties is not set, then neither will be used. #### `win.showDefinitionForSelection()` _macOS_ Same as `webContents.showDefinitionForSelection()`. #### `win.setIcon(icon)` _Windows_ _Linux_ * `icon` [NativeImage](native-image.md) | string Changes window icon. #### `win.setWindowButtonVisibility(visible)` _macOS_ * `visible` boolean Sets whether the window traffic light buttons should be visible. #### `win.setAutoHideMenuBar(hide)` _Windows_ _Linux_ * `hide` boolean Sets whether the window menu bar should hide itself automatically. Once set the menu bar will only show when users press the single `Alt` key. If the menu bar is already visible, calling `setAutoHideMenuBar(true)` won't hide it immediately. #### `win.isMenuBarAutoHide()` _Windows_ _Linux_ Returns `boolean` - Whether menu bar automatically hides itself. #### `win.setMenuBarVisibility(visible)` _Windows_ _Linux_ * `visible` boolean Sets whether the menu bar should be visible. If the menu bar is auto-hide, users can still bring up the menu bar by pressing the single `Alt` key. #### `win.isMenuBarVisible()` _Windows_ _Linux_ Returns `boolean` - Whether the menu bar is visible. #### `win.setVisibleOnAllWorkspaces(visible[, options])` _macOS_ _Linux_ * `visible` boolean * `options` Object (optional) * `visibleOnFullScreen` boolean (optional) _macOS_ - Sets whether the window should be visible above fullscreen windows. * `skipTransformProcessType` boolean (optional) _macOS_ - Calling setVisibleOnAllWorkspaces will by default transform the process type between UIElementApplication and ForegroundApplication to ensure the correct behavior. However, this will hide the window and dock for a short time every time it is called. If your window is already of type UIElementApplication, you can bypass this transformation by passing true to skipTransformProcessType. Sets whether the window should be visible on all workspaces. **Note:** This API does nothing on Windows. #### `win.isVisibleOnAllWorkspaces()` _macOS_ _Linux_ Returns `boolean` - Whether the window is visible on all workspaces. **Note:** This API always returns false on Windows. #### `win.setIgnoreMouseEvents(ignore[, options])` * `ignore` boolean * `options` Object (optional) * `forward` boolean (optional) _macOS_ _Windows_ - If true, forwards mouse move messages to Chromium, enabling mouse related events such as `mouseleave`. Only used when `ignore` is true. If `ignore` is false, forwarding is always disabled regardless of this value. Makes the window ignore all mouse events. All mouse events happened in this window will be passed to the window below this window, but if this window has focus, it will still receive keyboard events. #### `win.setContentProtection(enable)` _macOS_ _Windows_ * `enable` boolean Prevents the window contents from being captured by other apps. On macOS it sets the NSWindow's sharingType to NSWindowSharingNone. On Windows it calls SetWindowDisplayAffinity with `WDA_EXCLUDEFROMCAPTURE`. For Windows 10 version 2004 and up the window will be removed from capture entirely, older Windows versions behave as if `WDA_MONITOR` is applied capturing a black window. #### `win.setFocusable(focusable)` _macOS_ _Windows_ * `focusable` boolean Changes whether the window can be focused. On macOS it does not remove the focus from the window. #### `win.isFocusable()` _macOS_ _Windows_ Returns `boolean` - Whether the window can be focused. #### `win.setParentWindow(parent)` * `parent` BrowserWindow | null Sets `parent` as current window's parent window, passing `null` will turn current window into a top-level window. #### `win.getParentWindow()` Returns `BrowserWindow | null` - The parent window or `null` if there is no parent. #### `win.getChildWindows()` Returns `BrowserWindow[]` - All child windows. #### `win.setAutoHideCursor(autoHide)` _macOS_ * `autoHide` boolean Controls whether to hide cursor when typing. #### `win.selectPreviousTab()` _macOS_ Selects the previous tab when native tabs are enabled and there are other tabs in the window. #### `win.selectNextTab()` _macOS_ Selects the next tab when native tabs are enabled and there are other tabs in the window. #### `win.showAllTabs()` _macOS_ Shows or hides the tab overview when native tabs are enabled. #### `win.mergeAllWindows()` _macOS_ Merges all windows into one window with multiple tabs when native tabs are enabled and there is more than one open window. #### `win.moveTabToNewWindow()` _macOS_ Moves the current tab into a new window if native tabs are enabled and there is more than one tab in the current window. #### `win.toggleTabBar()` _macOS_ Toggles the visibility of the tab bar if native tabs are enabled and there is only one tab in the current window. #### `win.addTabbedWindow(browserWindow)` _macOS_ * `browserWindow` BrowserWindow Adds a window as a tab on this window, after the tab for the window instance. #### `win.setVibrancy(type)` _macOS_ * `type` string | null - Can be `titlebar`, `selection`, `menu`, `popover`, `sidebar`, `header`, `sheet`, `window`, `hud`, `fullscreen-ui`, `tooltip`, `content`, `under-window`, or `under-page`. See the [macOS documentation][vibrancy-docs] for more details. Adds a vibrancy effect to the browser window. Passing `null` or an empty string will remove the vibrancy effect on the window. #### `win.setBackgroundMaterial(material)` _Windows_ * `material` string * `auto` - Let the Desktop Window Manager (DWM) automatically decide the system-drawn backdrop material for this window. This is the default. * `none` - Don't draw any system backdrop. * `mica` - Draw the backdrop material effect corresponding to a long-lived window. * `acrylic` - Draw the backdrop material effect corresponding to a transient window. * `tabbed` - Draw the backdrop material effect corresponding to a window with a tabbed title bar. This method sets the browser window's system-drawn background material, including behind the non-client area. See the [Windows documentation](https://learn.microsoft.com/en-us/windows/win32/api/dwmapi/ne-dwmapi-dwm_systembackdrop_type) for more details. **Note:** This method is only supported on Windows 11 22H2 and up. #### `win.setWindowButtonPosition(position)` _macOS_ * `position` [Point](structures/point.md) | null Set a custom position for the traffic light buttons in frameless window. Passing `null` will reset the position to default. #### `win.getWindowButtonPosition()` _macOS_ Returns `Point | null` - The custom position for the traffic light buttons in frameless window, `null` will be returned when there is no custom position. #### `win.setTrafficLightPosition(position)` _macOS_ _Deprecated_ * `position` [Point](structures/point.md) Set a custom position for the traffic light buttons in frameless window. Passing `{ x: 0, y: 0 }` will reset the position to default. > **Note** > This function is deprecated. Use [setWindowButtonPosition](#winsetwindowbuttonpositionposition-macos) instead. #### `win.getTrafficLightPosition()` _macOS_ _Deprecated_ Returns `Point` - The custom position for the traffic light buttons in frameless window, `{ x: 0, y: 0 }` will be returned when there is no custom position. > **Note** > This function is deprecated. Use [getWindowButtonPosition](#wingetwindowbuttonposition-macos) instead. #### `win.setTouchBar(touchBar)` _macOS_ * `touchBar` TouchBar | null Sets the touchBar layout for the current window. Specifying `null` or `undefined` clears the touch bar. This method only has an effect if the machine has a touch bar. **Note:** The TouchBar API is currently experimental and may change or be removed in future Electron releases. #### `win.setBrowserView(browserView)` _Experimental_ * `browserView` [BrowserView](browser-view.md) | null - Attach `browserView` to `win`. If there are other `BrowserView`s attached, they will be removed from this window. #### `win.getBrowserView()` _Experimental_ Returns `BrowserView | null` - The `BrowserView` attached to `win`. Returns `null` if one is not attached. Throws an error if multiple `BrowserView`s are attached. #### `win.addBrowserView(browserView)` _Experimental_ * `browserView` [BrowserView](browser-view.md) Replacement API for setBrowserView supporting work with multi browser views. #### `win.removeBrowserView(browserView)` _Experimental_ * `browserView` [BrowserView](browser-view.md) #### `win.setTopBrowserView(browserView)` _Experimental_ * `browserView` [BrowserView](browser-view.md) Raises `browserView` above other `BrowserView`s attached to `win`. Throws an error if `browserView` is not attached to `win`. #### `win.getBrowserViews()` _Experimental_ Returns `BrowserView[]` - a sorted by z-index array of all BrowserViews that have been attached with `addBrowserView` or `setBrowserView`. The top-most BrowserView is the last element of the array. **Note:** The BrowserView API is currently experimental and may change or be removed in future Electron releases. #### `win.setTitleBarOverlay(options)` _Windows_ * `options` Object * `color` String (optional) _Windows_ - The CSS color of the Window Controls Overlay when enabled. * `symbolColor` String (optional) _Windows_ - The CSS color of the symbols on the Window Controls Overlay when enabled. * `height` Integer (optional) _Windows_ - The height of the title bar and Window Controls Overlay in pixels. On a Window with Window Controls Overlay already enabled, this method updates the style of the title bar overlay. [page-visibility-api]: https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API [quick-look]: https://en.wikipedia.org/wiki/Quick_Look [vibrancy-docs]: https://developer.apple.com/documentation/appkit/nsvisualeffectview?preferredLanguage=objc [window-levels]: https://developer.apple.com/documentation/appkit/nswindow/level [event-emitter]: https://nodejs.org/api/events.html#events_class_eventemitter
closed
electron/electron
https://github.com/electron/electron
39,445
[Bug]: `BrowserWindow`'s top offset (`y` value) is set to 25 when trying to set it explicitly below 25 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 25.4.0 ### What operating system are you using? macOS ### Operating System Version macOS Monterey 12.6 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior BrowserWindow's top offset from screen (`y` value) should be respected when explicitly specified to be below 25 ### Actual Behavior BrowserWindow's top offset from screen (`y` value) is always set to 25 when explicitly specified to be below 25 ### Testcase Gist URL https://gist.github.com/7bd49c0498a46da629adf1327fc03160 ### Additional Information Both when creating a new `BrowserWindow` like so: ```js const win = new BrowserWindow({ x: 15, y: 16, }) console.log(win.getBounds()); // logs { x: 15, y: 25, width: 800, height: 600 } ``` or when setting the `BrowserWindow` position after creation like so: ```js const win = new BrowserWindow(); win.setPosition(15,16); console.log(win.getBounds()); // logs { x: 15, y: 25, width: 800, height: 600 } ``` When the y-value above is set to anything below 25, it always goes to 25 and never below. However, setting the y-value above 25 works correctly and returns position that was specified. This issue doesn't seem to exist on Windows and Linux and seems to isolated to MacOS. I did find a possibly related issue filed [here](https://github.com/electron/electron/issues/39257)
https://github.com/electron/electron/issues/39445
https://github.com/electron/electron/pull/39512
dd8df3b0c47102fe5686f516c80e698ab555a6f9
31dfde7fa63c19a299e18b2dcef7cdf922d2a400
2023-08-09T18:17:51Z
c++
2023-08-17T09:02:03Z
docs/api/browser-window.md
# BrowserWindow > Create and control browser windows. Process: [Main](../glossary.md#main-process) This module cannot be used until the `ready` event of the `app` module is emitted. ```javascript // In the main process. const { BrowserWindow } = require('electron') const win = new BrowserWindow({ width: 800, height: 600 }) // Load a remote URL win.loadURL('https://github.com') // Or load a local HTML file win.loadFile('index.html') ``` ## Window customization The `BrowserWindow` class exposes various ways to modify the look and behavior of your app's windows. For more details, see the [Window Customization](../tutorial/window-customization.md) tutorial. ## Showing the window gracefully When loading a page in the window directly, users may see the page load incrementally, which is not a good experience for a native app. To make the window display without a visual flash, there are two solutions for different situations. ### Using the `ready-to-show` event While loading the page, the `ready-to-show` event will be emitted when the renderer process has rendered the page for the first time if the window has not been shown yet. Showing the window after this event will have no visual flash: ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow({ show: false }) win.once('ready-to-show', () => { win.show() }) ``` This event is usually emitted after the `did-finish-load` event, but for pages with many remote resources, it may be emitted before the `did-finish-load` event. Please note that using this event implies that the renderer will be considered "visible" and paint even though `show` is false. This event will never fire if you use `paintWhenInitiallyHidden: false` ### Setting the `backgroundColor` property For a complex app, the `ready-to-show` event could be emitted too late, making the app feel slow. In this case, it is recommended to show the window immediately, and use a `backgroundColor` close to your app's background: ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow({ backgroundColor: '#2e2c29' }) win.loadURL('https://github.com') ``` Note that even for apps that use `ready-to-show` event, it is still recommended to set `backgroundColor` to make the app feel more native. Some examples of valid `backgroundColor` values include: ```js const win = new BrowserWindow() win.setBackgroundColor('hsl(230, 100%, 50%)') win.setBackgroundColor('rgb(255, 145, 145)') win.setBackgroundColor('#ff00a3') win.setBackgroundColor('blueviolet') ``` For more information about these color types see valid options in [win.setBackgroundColor](browser-window.md#winsetbackgroundcolorbackgroundcolor). ## Parent and child windows By using `parent` option, you can create child windows: ```javascript const { BrowserWindow } = require('electron') const top = new BrowserWindow() const child = new BrowserWindow({ parent: top }) child.show() top.show() ``` The `child` window will always show on top of the `top` window. ## Modal windows A modal window is a child window that disables parent window, to create a modal window, you have to set both `parent` and `modal` options: ```javascript const { BrowserWindow } = require('electron') const top = new BrowserWindow() const child = new BrowserWindow({ parent: top, modal: true, show: false }) child.loadURL('https://github.com') child.once('ready-to-show', () => { child.show() }) ``` ## Page visibility The [Page Visibility API][page-visibility-api] works as follows: * On all platforms, the visibility state tracks whether the window is hidden/minimized or not. * Additionally, on macOS, the visibility state also tracks the window occlusion state. If the window is occluded (i.e. fully covered) by another window, the visibility state will be `hidden`. On other platforms, the visibility state will be `hidden` only when the window is minimized or explicitly hidden with `win.hide()`. * If a `BrowserWindow` is created with `show: false`, the initial visibility state will be `visible` despite the window actually being hidden. * If `backgroundThrottling` is disabled, the visibility state will remain `visible` even if the window is minimized, occluded, or hidden. It is recommended that you pause expensive operations when the visibility state is `hidden` in order to minimize power consumption. ## Platform notices * On macOS modal windows will be displayed as sheets attached to the parent window. * On macOS the child windows will keep the relative position to parent window when parent window moves, while on Windows and Linux child windows will not move. * On Linux the type of modal windows will be changed to `dialog`. * On Linux many desktop environments do not support hiding a modal window. ## Class: BrowserWindow > Create and control browser windows. Process: [Main](../glossary.md#main-process) `BrowserWindow` is an [EventEmitter][event-emitter]. It creates a new `BrowserWindow` with native properties as set by the `options`. ### `new BrowserWindow([options])` * `options` [BrowserWindowConstructorOptions](structures/browser-window-options.md?inline) (optional) ### Instance Events Objects created with `new BrowserWindow` emit the following events: **Note:** Some events are only available on specific operating systems and are labeled as such. #### Event: 'page-title-updated' Returns: * `event` Event * `title` string * `explicitSet` boolean Emitted when the document changed its title, calling `event.preventDefault()` will prevent the native window's title from changing. `explicitSet` is false when title is synthesized from file URL. #### Event: 'close' Returns: * `event` Event Emitted when the window is going to be closed. It's emitted before the `beforeunload` and `unload` event of the DOM. Calling `event.preventDefault()` will cancel the close. Usually you would want to use the `beforeunload` handler to decide whether the window should be closed, which will also be called when the window is reloaded. In Electron, returning any value other than `undefined` would cancel the close. For example: ```javascript window.onbeforeunload = (e) => { console.log('I do not want to be closed') // Unlike usual browsers that a message box will be prompted to users, returning // a non-void value will silently cancel the close. // It is recommended to use the dialog API to let the user confirm closing the // application. e.returnValue = false } ``` _**Note**: There is a subtle difference between the behaviors of `window.onbeforeunload = handler` and `window.addEventListener('beforeunload', handler)`. It is recommended to always set the `event.returnValue` explicitly, instead of only returning a value, as the former works more consistently within Electron._ #### Event: 'closed' Emitted when the window is closed. After you have received this event you should remove the reference to the window and avoid using it any more. #### Event: 'session-end' _Windows_ Emitted when window session is going to end due to force shutdown or machine restart or session log off. #### Event: 'unresponsive' Emitted when the web page becomes unresponsive. #### Event: 'responsive' Emitted when the unresponsive web page becomes responsive again. #### Event: 'blur' Emitted when the window loses focus. #### Event: 'focus' Emitted when the window gains focus. #### Event: 'show' Emitted when the window is shown. #### Event: 'hide' Emitted when the window is hidden. #### Event: 'ready-to-show' Emitted when the web page has been rendered (while not being shown) and window can be displayed without a visual flash. Please note that using this event implies that the renderer will be considered "visible" and paint even though `show` is false. This event will never fire if you use `paintWhenInitiallyHidden: false` #### Event: 'maximize' Emitted when window is maximized. #### Event: 'unmaximize' Emitted when the window exits from a maximized state. #### Event: 'minimize' Emitted when the window is minimized. #### Event: 'restore' Emitted when the window is restored from a minimized state. #### Event: 'will-resize' _macOS_ _Windows_ Returns: * `event` Event * `newBounds` [Rectangle](structures/rectangle.md) - Size the window is being resized to. * `details` Object * `edge` (string) - The edge of the window being dragged for resizing. Can be `bottom`, `left`, `right`, `top-left`, `top-right`, `bottom-left` or `bottom-right`. Emitted before the window is resized. Calling `event.preventDefault()` will prevent the window from being resized. Note that this is only emitted when the window is being resized manually. Resizing the window with `setBounds`/`setSize` will not emit this event. The possible values and behaviors of the `edge` option are platform dependent. Possible values are: * On Windows, possible values are `bottom`, `top`, `left`, `right`, `top-left`, `top-right`, `bottom-left`, `bottom-right`. * On macOS, possible values are `bottom` and `right`. * The value `bottom` is used to denote vertical resizing. * The value `right` is used to denote horizontal resizing. #### Event: 'resize' Emitted after the window has been resized. #### Event: 'resized' _macOS_ _Windows_ Emitted once when the window has finished being resized. This is usually emitted when the window has been resized manually. On macOS, resizing the window with `setBounds`/`setSize` and setting the `animate` parameter to `true` will also emit this event once resizing has finished. #### Event: 'will-move' _macOS_ _Windows_ Returns: * `event` Event * `newBounds` [Rectangle](structures/rectangle.md) - Location the window is being moved to. Emitted before the window is moved. On Windows, calling `event.preventDefault()` will prevent the window from being moved. Note that this is only emitted when the window is being moved manually. Moving the window with `setPosition`/`setBounds`/`center` will not emit this event. #### Event: 'move' Emitted when the window is being moved to a new position. #### Event: 'moved' _macOS_ _Windows_ Emitted once when the window is moved to a new position. **Note**: On macOS this event is an alias of `move`. #### Event: 'enter-full-screen' Emitted when the window enters a full-screen state. #### Event: 'leave-full-screen' Emitted when the window leaves a full-screen state. #### 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: 'always-on-top-changed' Returns: * `event` Event * `isAlwaysOnTop` boolean Emitted when the window is set or unset to show always on top of other windows. #### Event: 'app-command' _Windows_ _Linux_ Returns: * `event` Event * `command` string Emitted when an [App Command](https://learn.microsoft.com/en-us/windows/win32/inputdev/wm-appcommand) is invoked. These are typically related to keyboard media keys or browser commands, as well as the "Back" button built into some mice on Windows. Commands are lowercased, underscores are replaced with hyphens, and the `APPCOMMAND_` prefix is stripped off. e.g. `APPCOMMAND_BROWSER_BACKWARD` is emitted as `browser-backward`. ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow() win.on('app-command', (e, cmd) => { // Navigate the window back when the user hits their mouse back button if (cmd === 'browser-backward' && win.webContents.canGoBack()) { win.webContents.goBack() } }) ``` The following app commands are explicitly supported on Linux: * `browser-backward` * `browser-forward` #### Event: 'scroll-touch-begin' _macOS_ _Deprecated_ Emitted when scroll wheel event phase has begun. > **Note** > This event is deprecated beginning in Electron 22.0.0. See [Breaking > Changes](../breaking-changes.md#deprecated-browserwindow-scroll-touch--events) > for details of how to migrate to using the [WebContents > `input-event`](./web-contents.md#event-input-event) event. #### Event: 'scroll-touch-end' _macOS_ _Deprecated_ Emitted when scroll wheel event phase has ended. > **Note** > This event is deprecated beginning in Electron 22.0.0. See [Breaking > Changes](../breaking-changes.md#deprecated-browserwindow-scroll-touch--events) > for details of how to migrate to using the [WebContents > `input-event`](./web-contents.md#event-input-event) event. #### Event: 'scroll-touch-edge' _macOS_ _Deprecated_ Emitted when scroll wheel event phase filed upon reaching the edge of element. > **Note** > This event is deprecated beginning in Electron 22.0.0. See [Breaking > Changes](../breaking-changes.md#deprecated-browserwindow-scroll-touch--events) > for details of how to migrate to using the [WebContents > `input-event`](./web-contents.md#event-input-event) event. #### Event: 'swipe' _macOS_ Returns: * `event` Event * `direction` string Emitted on 3-finger swipe. Possible directions are `up`, `right`, `down`, `left`. The method underlying this event is built to handle older macOS-style trackpad swiping, where the content on the screen doesn't move with the swipe. Most macOS trackpads are not configured to allow this kind of swiping anymore, so in order for it to emit properly the 'Swipe between pages' preference in `System Preferences > Trackpad > More Gestures` must be set to 'Swipe with two or three fingers'. #### Event: 'rotate-gesture' _macOS_ Returns: * `event` Event * `rotation` Float Emitted on trackpad rotation gesture. Continually emitted until rotation gesture is ended. The `rotation` value on each emission is the angle in degrees rotated since the last emission. The last emitted event upon a rotation gesture will always be of value `0`. Counter-clockwise rotation values are positive, while clockwise ones are negative. #### Event: 'sheet-begin' _macOS_ Emitted when the window opens a sheet. #### Event: 'sheet-end' _macOS_ Emitted when the window has closed a sheet. #### Event: 'new-window-for-tab' _macOS_ Emitted when the native new tab button is clicked. #### Event: 'system-context-menu' _Windows_ Returns: * `event` Event * `point` [Point](structures/point.md) - The screen coordinates the context menu was triggered at Emitted when the system context menu is triggered on the window, this is normally only triggered when the user right clicks on the non-client area of your window. This is the window titlebar or any area you have declared as `-webkit-app-region: drag` in a frameless window. Calling `event.preventDefault()` will prevent the menu from being displayed. ### Static Methods The `BrowserWindow` class has the following static methods: #### `BrowserWindow.getAllWindows()` Returns `BrowserWindow[]` - An array of all opened browser windows. #### `BrowserWindow.getFocusedWindow()` Returns `BrowserWindow | null` - The window that is focused in this application, otherwise returns `null`. #### `BrowserWindow.fromWebContents(webContents)` * `webContents` [WebContents](web-contents.md) Returns `BrowserWindow | null` - The window that owns the given `webContents` or `null` if the contents are not owned by a window. #### `BrowserWindow.fromBrowserView(browserView)` * `browserView` [BrowserView](browser-view.md) Returns `BrowserWindow | null` - The window that owns the given `browserView`. If the given view is not attached to any window, returns `null`. #### `BrowserWindow.fromId(id)` * `id` Integer Returns `BrowserWindow | null` - The window with the given `id`. ### Instance Properties Objects created with `new BrowserWindow` have the following properties: ```javascript const { BrowserWindow } = require('electron') // In this example `win` is our instance const win = new BrowserWindow({ width: 800, height: 600 }) win.loadURL('https://github.com') ``` #### `win.webContents` _Readonly_ A `WebContents` object this window owns. All web page related events and operations will be done via it. See the [`webContents` documentation](web-contents.md) for its methods and events. #### `win.id` _Readonly_ A `Integer` property representing the unique ID of the window. Each ID is unique among all `BrowserWindow` instances of the entire Electron application. #### `win.autoHideMenuBar` A `boolean` property that determines whether the window menu bar should hide itself automatically. Once set, the menu bar will only show when users press the single `Alt` key. If the menu bar is already visible, setting this property to `true` won't hide it immediately. #### `win.simpleFullScreen` A `boolean` property that determines whether the window is in simple (pre-Lion) fullscreen mode. #### `win.fullScreen` A `boolean` property that determines whether the window is in fullscreen mode. #### `win.focusable` _Windows_ _macOS_ A `boolean` property that determines whether the window is focusable. #### `win.visibleOnAllWorkspaces` _macOS_ _Linux_ A `boolean` property that determines whether the window is visible on all workspaces. **Note:** Always returns false on Windows. #### `win.shadow` A `boolean` property that determines whether the window has a shadow. #### `win.menuBarVisible` _Windows_ _Linux_ A `boolean` property that determines whether the menu bar should be visible. **Note:** If the menu bar is auto-hide, users can still bring up the menu bar by pressing the single `Alt` key. #### `win.kiosk` A `boolean` property that determines whether the window is in kiosk mode. #### `win.documentEdited` _macOS_ A `boolean` property that specifies whether the window’s document has been edited. The icon in title bar will become gray when set to `true`. #### `win.representedFilename` _macOS_ A `string` property that determines the pathname of the file the window represents, and the icon of the file will show in window's title bar. #### `win.title` A `string` property that determines the title of the native window. **Note:** The title of the web page can be different from the title of the native window. #### `win.minimizable` _macOS_ _Windows_ A `boolean` property that determines whether the window can be manually minimized by user. On Linux the setter is a no-op, although the getter returns `true`. #### `win.maximizable` _macOS_ _Windows_ A `boolean` property that determines whether the window can be manually maximized by user. On Linux the setter is a no-op, although the getter returns `true`. #### `win.fullScreenable` A `boolean` property that determines whether the maximize/zoom window button toggles fullscreen mode or maximizes the window. #### `win.resizable` A `boolean` property that determines whether the window can be manually resized by user. #### `win.closable` _macOS_ _Windows_ A `boolean` property that determines whether the window can be manually closed by user. On Linux the setter is a no-op, although the getter returns `true`. #### `win.movable` _macOS_ _Windows_ A `boolean` property that determines Whether the window can be moved by user. On Linux the setter is a no-op, although the getter returns `true`. #### `win.excludedFromShownWindowsMenu` _macOS_ A `boolean` property that determines whether the window is excluded from the application’s Windows menu. `false` by default. ```js @ts-expect-error=[11] const win = new BrowserWindow({ height: 600, width: 600 }) const template = [ { role: 'windowmenu' } ] win.excludedFromShownWindowsMenu = true const menu = Menu.buildFromTemplate(template) Menu.setApplicationMenu(menu) ``` #### `win.accessibleTitle` A `string` property that defines an alternative title provided only to accessibility tools such as screen readers. This string is not directly visible to users. ### Instance Methods Objects created with `new BrowserWindow` have the following instance methods: **Note:** Some methods are only available on specific operating systems and are labeled as such. #### `win.destroy()` Force closing the window, the `unload` and `beforeunload` event won't be emitted for the web page, and `close` event will also not be emitted for this window, but it guarantees the `closed` event will be emitted. #### `win.close()` Try to close the window. This has the same effect as a user manually clicking the close button of the window. The web page may cancel the close though. See the [close event](#event-close). #### `win.focus()` Focuses on the window. #### `win.blur()` Removes focus from the window. #### `win.isFocused()` Returns `boolean` - Whether the window is focused. #### `win.isDestroyed()` Returns `boolean` - Whether the window is destroyed. #### `win.show()` Shows and gives focus to the window. #### `win.showInactive()` Shows the window but doesn't focus on it. #### `win.hide()` Hides the window. #### `win.isVisible()` Returns `boolean` - Whether the window is visible to the user in the foreground of the app. #### `win.isModal()` Returns `boolean` - Whether current window is a modal window. #### `win.maximize()` Maximizes the window. This will also show (but not focus) the window if it isn't being displayed already. #### `win.unmaximize()` Unmaximizes the window. #### `win.isMaximized()` Returns `boolean` - Whether the window is maximized. #### `win.minimize()` Minimizes the window. On some platforms the minimized window will be shown in the Dock. #### `win.restore()` Restores the window from minimized state to its previous state. #### `win.isMinimized()` Returns `boolean` - Whether the window is minimized. #### `win.setFullScreen(flag)` * `flag` boolean Sets whether the window should be in fullscreen mode. **Note:** On macOS, fullscreen transitions take place asynchronously. If further actions depend on the fullscreen state, use the ['enter-full-screen'](browser-window.md#event-enter-full-screen) or ['leave-full-screen'](browser-window.md#event-leave-full-screen) events. #### `win.isFullScreen()` Returns `boolean` - Whether the window is in fullscreen mode. #### `win.setSimpleFullScreen(flag)` _macOS_ * `flag` boolean Enters or leaves simple fullscreen mode. Simple fullscreen mode emulates the native fullscreen behavior found in versions of macOS prior to Lion (10.7). #### `win.isSimpleFullScreen()` _macOS_ Returns `boolean` - Whether the window is in simple (pre-Lion) fullscreen mode. #### `win.isNormal()` Returns `boolean` - Whether the window is in normal state (not maximized, not minimized, not in fullscreen mode). #### `win.setAspectRatio(aspectRatio[, extraSize])` * `aspectRatio` Float - The aspect ratio to maintain for some portion of the content view. * `extraSize` [Size](structures/size.md) (optional) _macOS_ - The extra size not to be included while maintaining the aspect ratio. This will make a window maintain an aspect ratio. The extra size allows a developer to have space, specified in pixels, not included within the aspect ratio calculations. This API already takes into account the difference between a window's size and its content size. Consider a normal window with an HD video player and associated controls. Perhaps there are 15 pixels of controls on the left edge, 25 pixels of controls on the right edge and 50 pixels of controls below the player. In order to maintain a 16:9 aspect ratio (standard aspect ratio for HD @1920x1080) within the player itself we would call this function with arguments of 16/9 and { width: 40, height: 50 }. The second argument doesn't care where the extra width and height are within the content view--only that they exist. Sum any extra width and height areas you have within the overall content view. The aspect ratio is not respected when window is resized programmatically with APIs like `win.setSize`. To reset an aspect ratio, pass 0 as the `aspectRatio` value: `win.setAspectRatio(0)`. #### `win.setBackgroundColor(backgroundColor)` * `backgroundColor` string - Color in Hex, RGB, RGBA, HSL, HSLA or named CSS color format. The alpha channel is optional for the hex type. Examples of valid `backgroundColor` values: * Hex * #fff (shorthand RGB) * #ffff (shorthand ARGB) * #ffffff (RGB) * #ffffffff (ARGB) * RGB * rgb\((\[\d]+),\s*(\[\d]+),\s*(\[\d]+)\) * e.g. rgb(255, 255, 255) * RGBA * rgba\((\[\d]+),\s*(\[\d]+),\s*(\[\d]+),\s*(\[\d.]+)\) * e.g. rgba(255, 255, 255, 1.0) * HSL * hsl\((-?\[\d.]+),\s*(\[\d.]+)%,\s*(\[\d.]+)%\) * e.g. hsl(200, 20%, 50%) * HSLA * hsla\((-?\[\d.]+),\s*(\[\d.]+)%,\s*(\[\d.]+)%,\s*(\[\d.]+)\) * e.g. hsla(200, 20%, 50%, 0.5) * Color name * Options are listed in [SkParseColor.cpp](https://source.chromium.org/chromium/chromium/src/+/main:third_party/skia/src/utils/SkParseColor.cpp;l=11-152;drc=eea4bf52cb0d55e2a39c828b017c80a5ee054148) * Similar to CSS Color Module Level 3 keywords, but case-sensitive. * e.g. `blueviolet` or `red` Sets the background color of the window. See [Setting `backgroundColor`](#setting-the-backgroundcolor-property). #### `win.previewFile(path[, displayName])` _macOS_ * `path` string - The absolute path to the file to preview with QuickLook. This is important as Quick Look uses the file name and file extension on the path to determine the content type of the file to open. * `displayName` string (optional) - The name of the file to display on the Quick Look modal view. This is purely visual and does not affect the content type of the file. Defaults to `path`. Uses [Quick Look][quick-look] to preview a file at a given path. #### `win.closeFilePreview()` _macOS_ Closes the currently open [Quick Look][quick-look] panel. #### `win.setBounds(bounds[, animate])` * `bounds` Partial<[Rectangle](structures/rectangle.md)> * `animate` boolean (optional) _macOS_ Resizes and moves the window to the supplied bounds. Any properties that are not supplied will default to their current values. ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow() // set all bounds properties win.setBounds({ x: 440, y: 225, width: 800, height: 600 }) // set a single bounds property win.setBounds({ width: 100 }) // { x: 440, y: 225, width: 100, height: 600 } console.log(win.getBounds()) ``` #### `win.getBounds()` Returns [`Rectangle`](structures/rectangle.md) - The `bounds` of the window as `Object`. #### `win.getBackgroundColor()` Returns `string` - Gets the background color of the window in Hex (`#RRGGBB`) format. See [Setting `backgroundColor`](#setting-the-backgroundcolor-property). **Note:** The alpha value is _not_ returned alongside the red, green, and blue values. #### `win.setContentBounds(bounds[, animate])` * `bounds` [Rectangle](structures/rectangle.md) * `animate` boolean (optional) _macOS_ Resizes and moves the window's client area (e.g. the web page) to the supplied bounds. #### `win.getContentBounds()` Returns [`Rectangle`](structures/rectangle.md) - The `bounds` of the window's client area as `Object`. #### `win.getNormalBounds()` Returns [`Rectangle`](structures/rectangle.md) - Contains the window bounds of the normal state **Note:** whatever the current state of the window : maximized, minimized or in fullscreen, this function always returns the position and size of the window in normal state. In normal state, getBounds and getNormalBounds returns the same [`Rectangle`](structures/rectangle.md). #### `win.setEnabled(enable)` * `enable` boolean Disable or enable the window. #### `win.isEnabled()` Returns `boolean` - whether the window is enabled. #### `win.setSize(width, height[, animate])` * `width` Integer * `height` Integer * `animate` boolean (optional) _macOS_ Resizes the window to `width` and `height`. If `width` or `height` are below any set minimum size constraints the window will snap to its minimum size. #### `win.getSize()` Returns `Integer[]` - Contains the window's width and height. #### `win.setContentSize(width, height[, animate])` * `width` Integer * `height` Integer * `animate` boolean (optional) _macOS_ Resizes the window's client area (e.g. the web page) to `width` and `height`. #### `win.getContentSize()` Returns `Integer[]` - Contains the window's client area's width and height. #### `win.setMinimumSize(width, height)` * `width` Integer * `height` Integer Sets the minimum size of window to `width` and `height`. #### `win.getMinimumSize()` Returns `Integer[]` - Contains the window's minimum width and height. #### `win.setMaximumSize(width, height)` * `width` Integer * `height` Integer Sets the maximum size of window to `width` and `height`. #### `win.getMaximumSize()` Returns `Integer[]` - Contains the window's maximum width and height. #### `win.setResizable(resizable)` * `resizable` boolean Sets whether the window can be manually resized by the user. #### `win.isResizable()` Returns `boolean` - Whether the window can be manually resized by the user. #### `win.setMovable(movable)` _macOS_ _Windows_ * `movable` boolean Sets whether the window can be moved by user. On Linux does nothing. #### `win.isMovable()` _macOS_ _Windows_ Returns `boolean` - Whether the window can be moved by user. On Linux always returns `true`. #### `win.setMinimizable(minimizable)` _macOS_ _Windows_ * `minimizable` boolean Sets whether the window can be manually minimized by user. On Linux does nothing. #### `win.isMinimizable()` _macOS_ _Windows_ Returns `boolean` - Whether the window can be manually minimized by the user. On Linux always returns `true`. #### `win.setMaximizable(maximizable)` _macOS_ _Windows_ * `maximizable` boolean Sets whether the window can be manually maximized by user. On Linux does nothing. #### `win.isMaximizable()` _macOS_ _Windows_ Returns `boolean` - Whether the window can be manually maximized by user. On Linux always returns `true`. #### `win.setFullScreenable(fullscreenable)` * `fullscreenable` boolean Sets whether the maximize/zoom window button toggles fullscreen mode or maximizes the window. #### `win.isFullScreenable()` Returns `boolean` - Whether the maximize/zoom window button toggles fullscreen mode or maximizes the window. #### `win.setClosable(closable)` _macOS_ _Windows_ * `closable` boolean Sets whether the window can be manually closed by user. On Linux does nothing. #### `win.isClosable()` _macOS_ _Windows_ Returns `boolean` - Whether the window can be manually closed by user. On Linux always returns `true`. #### `win.setHiddenInMissionControl(hidden)` _macOS_ * `hidden` boolean Sets whether the window will be hidden when the user toggles into mission control. #### `win.isHiddenInMissionControl()` _macOS_ Returns `boolean` - Whether the window will be hidden when the user toggles into mission control. #### `win.setAlwaysOnTop(flag[, level][, relativeLevel])` * `flag` boolean * `level` string (optional) _macOS_ _Windows_ - Values include `normal`, `floating`, `torn-off-menu`, `modal-panel`, `main-menu`, `status`, `pop-up-menu`, `screen-saver`, and ~~`dock`~~ (Deprecated). The default is `floating` when `flag` is true. The `level` is reset to `normal` when the flag is false. Note that from `floating` to `status` included, the window is placed below the Dock on macOS and below the taskbar on Windows. From `pop-up-menu` to a higher it is shown above the Dock on macOS and above the taskbar on Windows. See the [macOS docs][window-levels] for more details. * `relativeLevel` Integer (optional) _macOS_ - The number of layers higher to set this window relative to the given `level`. The default is `0`. Note that Apple discourages setting levels higher than 1 above `screen-saver`. Sets whether the window should show always on top of other windows. After setting this, the window is still a normal window, not a toolbox window which can not be focused on. #### `win.isAlwaysOnTop()` Returns `boolean` - Whether the window is always on top of other windows. #### `win.moveAbove(mediaSourceId)` * `mediaSourceId` string - Window id in the format of DesktopCapturerSource's id. For example "window:1869:0". Moves window above the source window in the sense of z-order. If the `mediaSourceId` is not of type window or if the window does not exist then this method throws an error. #### `win.moveTop()` Moves window to top(z-order) regardless of focus #### `win.center()` Moves window to the center of the screen. #### `win.setPosition(x, y[, animate])` * `x` Integer * `y` Integer * `animate` boolean (optional) _macOS_ Moves window to `x` and `y`. #### `win.getPosition()` Returns `Integer[]` - Contains the window's current position. #### `win.setTitle(title)` * `title` string Changes the title of native window to `title`. #### `win.getTitle()` Returns `string` - The title of the native window. **Note:** The title of the web page can be different from the title of the native window. #### `win.setSheetOffset(offsetY[, offsetX])` _macOS_ * `offsetY` Float * `offsetX` Float (optional) Changes the attachment point for sheets on macOS. By default, sheets are attached just below the window frame, but you may want to display them beneath a HTML-rendered toolbar. For example: ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow() const toolbarRect = document.getElementById('toolbar').getBoundingClientRect() win.setSheetOffset(toolbarRect.height) ``` #### `win.flashFrame(flag)` * `flag` boolean Starts or stops flashing the window to attract user's attention. #### `win.setSkipTaskbar(skip)` _macOS_ _Windows_ * `skip` boolean Makes the window not show in the taskbar. #### `win.setKiosk(flag)` * `flag` boolean Enters or leaves kiosk mode. #### `win.isKiosk()` Returns `boolean` - Whether the window is in kiosk mode. #### `win.isTabletMode()` _Windows_ Returns `boolean` - Whether the window is in Windows 10 tablet mode. Since Windows 10 users can [use their PC as tablet](https://support.microsoft.com/en-us/help/17210/windows-10-use-your-pc-like-a-tablet), under this mode apps can choose to optimize their UI for tablets, such as enlarging the titlebar and hiding titlebar buttons. This API returns whether the window is in tablet mode, and the `resize` event can be be used to listen to changes to tablet mode. #### `win.getMediaSourceId()` Returns `string` - Window id in the format of DesktopCapturerSource's id. For example "window:1324:0". More precisely the format is `window:id:other_id` where `id` is `HWND` on Windows, `CGWindowID` (`uint64_t`) on macOS and `Window` (`unsigned long`) on Linux. `other_id` is used to identify web contents (tabs) so within the same top level window. #### `win.getNativeWindowHandle()` Returns `Buffer` - The platform-specific handle of the window. The native type of the handle is `HWND` on Windows, `NSView*` on macOS, and `Window` (`unsigned long`) on Linux. #### `win.hookWindowMessage(message, callback)` _Windows_ * `message` Integer * `callback` Function * `wParam` Buffer - The `wParam` provided to the WndProc * `lParam` Buffer - The `lParam` provided to the WndProc Hooks a windows message. The `callback` is called when the message is received in the WndProc. #### `win.isWindowMessageHooked(message)` _Windows_ * `message` Integer Returns `boolean` - `true` or `false` depending on whether the message is hooked. #### `win.unhookWindowMessage(message)` _Windows_ * `message` Integer Unhook the window message. #### `win.unhookAllWindowMessages()` _Windows_ Unhooks all of the window messages. #### `win.setRepresentedFilename(filename)` _macOS_ * `filename` string Sets the pathname of the file the window represents, and the icon of the file will show in window's title bar. #### `win.getRepresentedFilename()` _macOS_ Returns `string` - The pathname of the file the window represents. #### `win.setDocumentEdited(edited)` _macOS_ * `edited` boolean Specifies whether the window’s document has been edited, and the icon in title bar will become gray when set to `true`. #### `win.isDocumentEdited()` _macOS_ Returns `boolean` - Whether the window's document has been edited. #### `win.focusOnWebView()` #### `win.blurWebView()` #### `win.capturePage([rect, opts])` * `rect` [Rectangle](structures/rectangle.md) (optional) - The bounds to capture * `opts` Object (optional) * `stayHidden` boolean (optional) - Keep the page hidden instead of visible. Default is `false`. * `stayAwake` boolean (optional) - Keep the system awake instead of allowing it to sleep. Default is `false`. 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. If the page is not visible, `rect` may be empty. 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. #### `win.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)). Same as [`webContents.loadURL(url[, options])`](web-contents.md#contentsloadurlurl-options). The `url` can be a remote address (e.g. `http://`) or a path to a local HTML file using the `file://` protocol. To ensure that file URLs are properly formatted, it is recommended to use Node's [`url.format`](https://nodejs.org/api/url.html#url_url_format_urlobject) method: ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow() const url = require('url').format({ protocol: 'file', slashes: true, pathname: require('path').join(__dirname, 'index.html') }) win.loadURL(url) ``` You can load a URL using a `POST` request with URL-encoded data by doing the following: ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow() win.loadURL('http://localhost:8000/post', { postData: [{ type: 'rawData', bytes: Buffer.from('hello=world') }], extraHeaders: 'Content-Type: application/x-www-form-urlencoded' }) ``` #### `win.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)). Same as `webContents.loadFile`, `filePath` should be a path to an HTML file relative to the root of your application. See the `webContents` docs for more information. #### `win.reload()` Same as `webContents.reload`. #### `win.setMenu(menu)` _Linux_ _Windows_ * `menu` Menu | null Sets the `menu` as the window's menu bar. #### `win.removeMenu()` _Linux_ _Windows_ Remove the window's menu bar. #### `win.setProgressBar(progress[, options])` * `progress` Double * `options` Object (optional) * `mode` string _Windows_ - Mode for the progress bar. Can be `none`, `normal`, `indeterminate`, `error` or `paused`. Sets progress value in progress bar. Valid range is \[0, 1.0]. Remove progress bar when progress < 0; Change to indeterminate mode when progress > 1. On Linux platform, only supports Unity desktop environment, you need to specify the `*.desktop` file name to `desktopName` field in `package.json`. By default, it will assume `{app.name}.desktop`. On Windows, a mode can be passed. Accepted values are `none`, `normal`, `indeterminate`, `error`, and `paused`. If you call `setProgressBar` without a mode set (but with a value within the valid range), `normal` will be assumed. #### `win.setOverlayIcon(overlay, description)` _Windows_ * `overlay` [NativeImage](native-image.md) | null - the icon to display on the bottom right corner of the taskbar icon. If this parameter is `null`, the overlay is cleared * `description` string - a description that will be provided to Accessibility screen readers Sets a 16 x 16 pixel overlay onto the current taskbar icon, usually used to convey some sort of application status or to passively notify the user. #### `win.invalidateShadow()` _macOS_ Invalidates the window shadow so that it is recomputed based on the current window shape. `BrowserWindows` that are transparent can sometimes leave behind visual artifacts on macOS. This method can be used to clear these artifacts when, for example, performing an animation. #### `win.setHasShadow(hasShadow)` * `hasShadow` boolean Sets whether the window should have a shadow. #### `win.hasShadow()` Returns `boolean` - Whether the window has a shadow. #### `win.setOpacity(opacity)` _Windows_ _macOS_ * `opacity` number - between 0.0 (fully transparent) and 1.0 (fully opaque) Sets the opacity of the window. On Linux, does nothing. Out of bound number values are clamped to the \[0, 1] range. #### `win.getOpacity()` Returns `number` - between 0.0 (fully transparent) and 1.0 (fully opaque). On Linux, always returns 1. #### `win.setShape(rects)` _Windows_ _Linux_ _Experimental_ * `rects` [Rectangle[]](structures/rectangle.md) - Sets a shape on the window. Passing an empty list reverts the window to being rectangular. Setting a window shape determines the area within the window where the system permits drawing and user interaction. Outside of the given region, no pixels will be drawn and no mouse events will be registered. Mouse events outside of the region will not be received by that window, but will fall through to whatever is behind the window. #### `win.setThumbarButtons(buttons)` _Windows_ * `buttons` [ThumbarButton[]](structures/thumbar-button.md) Returns `boolean` - Whether the buttons were added successfully Add a thumbnail toolbar with a specified set of buttons to the thumbnail image of a window in a taskbar button layout. Returns a `boolean` object indicates whether the thumbnail has been added successfully. The number of buttons in thumbnail toolbar should be no greater than 7 due to the limited room. Once you setup the thumbnail toolbar, the toolbar cannot be removed due to the platform's limitation. But you can call the API with an empty array to clean the buttons. The `buttons` is an array of `Button` objects: * `Button` Object * `icon` [NativeImage](native-image.md) - The icon showing in thumbnail toolbar. * `click` Function * `tooltip` string (optional) - The text of the button's tooltip. * `flags` string[] (optional) - Control specific states and behaviors of the button. By default, it is `['enabled']`. The `flags` is an array that can include following `string`s: * `enabled` - The button is active and available to the user. * `disabled` - The button is disabled. It is present, but has a visual state indicating it will not respond to user action. * `dismissonclick` - When the button is clicked, the thumbnail window closes immediately. * `nobackground` - Do not draw a button border, use only the image. * `hidden` - The button is not shown to the user. * `noninteractive` - The button is enabled but not interactive; no pressed button state is drawn. This value is intended for instances where the button is used in a notification. #### `win.setThumbnailClip(region)` _Windows_ * `region` [Rectangle](structures/rectangle.md) - Region of the window Sets the region of the window to show as the thumbnail image displayed when hovering over the window in the taskbar. You can reset the thumbnail to be the entire window by specifying an empty region: `{ x: 0, y: 0, width: 0, height: 0 }`. #### `win.setThumbnailToolTip(toolTip)` _Windows_ * `toolTip` string Sets the toolTip that is displayed when hovering over the window thumbnail in the taskbar. #### `win.setAppDetails(options)` _Windows_ * `options` Object * `appId` string (optional) - Window's [App User Model ID](https://learn.microsoft.com/en-us/windows/win32/shell/appids). It has to be set, otherwise the other options will have no effect. * `appIconPath` string (optional) - Window's [Relaunch Icon](https://learn.microsoft.com/en-us/windows/win32/properties/props-system-appusermodel-relaunchiconresource). * `appIconIndex` Integer (optional) - Index of the icon in `appIconPath`. Ignored when `appIconPath` is not set. Default is `0`. * `relaunchCommand` string (optional) - Window's [Relaunch Command](https://learn.microsoft.com/en-us/windows/win32/properties/props-system-appusermodel-relaunchcommand). * `relaunchDisplayName` string (optional) - Window's [Relaunch Display Name](https://learn.microsoft.com/en-us/windows/win32/properties/props-system-appusermodel-relaunchdisplaynameresource). Sets the properties for the window's taskbar button. **Note:** `relaunchCommand` and `relaunchDisplayName` must always be set together. If one of those properties is not set, then neither will be used. #### `win.showDefinitionForSelection()` _macOS_ Same as `webContents.showDefinitionForSelection()`. #### `win.setIcon(icon)` _Windows_ _Linux_ * `icon` [NativeImage](native-image.md) | string Changes window icon. #### `win.setWindowButtonVisibility(visible)` _macOS_ * `visible` boolean Sets whether the window traffic light buttons should be visible. #### `win.setAutoHideMenuBar(hide)` _Windows_ _Linux_ * `hide` boolean Sets whether the window menu bar should hide itself automatically. Once set the menu bar will only show when users press the single `Alt` key. If the menu bar is already visible, calling `setAutoHideMenuBar(true)` won't hide it immediately. #### `win.isMenuBarAutoHide()` _Windows_ _Linux_ Returns `boolean` - Whether menu bar automatically hides itself. #### `win.setMenuBarVisibility(visible)` _Windows_ _Linux_ * `visible` boolean Sets whether the menu bar should be visible. If the menu bar is auto-hide, users can still bring up the menu bar by pressing the single `Alt` key. #### `win.isMenuBarVisible()` _Windows_ _Linux_ Returns `boolean` - Whether the menu bar is visible. #### `win.setVisibleOnAllWorkspaces(visible[, options])` _macOS_ _Linux_ * `visible` boolean * `options` Object (optional) * `visibleOnFullScreen` boolean (optional) _macOS_ - Sets whether the window should be visible above fullscreen windows. * `skipTransformProcessType` boolean (optional) _macOS_ - Calling setVisibleOnAllWorkspaces will by default transform the process type between UIElementApplication and ForegroundApplication to ensure the correct behavior. However, this will hide the window and dock for a short time every time it is called. If your window is already of type UIElementApplication, you can bypass this transformation by passing true to skipTransformProcessType. Sets whether the window should be visible on all workspaces. **Note:** This API does nothing on Windows. #### `win.isVisibleOnAllWorkspaces()` _macOS_ _Linux_ Returns `boolean` - Whether the window is visible on all workspaces. **Note:** This API always returns false on Windows. #### `win.setIgnoreMouseEvents(ignore[, options])` * `ignore` boolean * `options` Object (optional) * `forward` boolean (optional) _macOS_ _Windows_ - If true, forwards mouse move messages to Chromium, enabling mouse related events such as `mouseleave`. Only used when `ignore` is true. If `ignore` is false, forwarding is always disabled regardless of this value. Makes the window ignore all mouse events. All mouse events happened in this window will be passed to the window below this window, but if this window has focus, it will still receive keyboard events. #### `win.setContentProtection(enable)` _macOS_ _Windows_ * `enable` boolean Prevents the window contents from being captured by other apps. On macOS it sets the NSWindow's sharingType to NSWindowSharingNone. On Windows it calls SetWindowDisplayAffinity with `WDA_EXCLUDEFROMCAPTURE`. For Windows 10 version 2004 and up the window will be removed from capture entirely, older Windows versions behave as if `WDA_MONITOR` is applied capturing a black window. #### `win.setFocusable(focusable)` _macOS_ _Windows_ * `focusable` boolean Changes whether the window can be focused. On macOS it does not remove the focus from the window. #### `win.isFocusable()` _macOS_ _Windows_ Returns `boolean` - Whether the window can be focused. #### `win.setParentWindow(parent)` * `parent` BrowserWindow | null Sets `parent` as current window's parent window, passing `null` will turn current window into a top-level window. #### `win.getParentWindow()` Returns `BrowserWindow | null` - The parent window or `null` if there is no parent. #### `win.getChildWindows()` Returns `BrowserWindow[]` - All child windows. #### `win.setAutoHideCursor(autoHide)` _macOS_ * `autoHide` boolean Controls whether to hide cursor when typing. #### `win.selectPreviousTab()` _macOS_ Selects the previous tab when native tabs are enabled and there are other tabs in the window. #### `win.selectNextTab()` _macOS_ Selects the next tab when native tabs are enabled and there are other tabs in the window. #### `win.showAllTabs()` _macOS_ Shows or hides the tab overview when native tabs are enabled. #### `win.mergeAllWindows()` _macOS_ Merges all windows into one window with multiple tabs when native tabs are enabled and there is more than one open window. #### `win.moveTabToNewWindow()` _macOS_ Moves the current tab into a new window if native tabs are enabled and there is more than one tab in the current window. #### `win.toggleTabBar()` _macOS_ Toggles the visibility of the tab bar if native tabs are enabled and there is only one tab in the current window. #### `win.addTabbedWindow(browserWindow)` _macOS_ * `browserWindow` BrowserWindow Adds a window as a tab on this window, after the tab for the window instance. #### `win.setVibrancy(type)` _macOS_ * `type` string | null - Can be `titlebar`, `selection`, `menu`, `popover`, `sidebar`, `header`, `sheet`, `window`, `hud`, `fullscreen-ui`, `tooltip`, `content`, `under-window`, or `under-page`. See the [macOS documentation][vibrancy-docs] for more details. Adds a vibrancy effect to the browser window. Passing `null` or an empty string will remove the vibrancy effect on the window. #### `win.setBackgroundMaterial(material)` _Windows_ * `material` string * `auto` - Let the Desktop Window Manager (DWM) automatically decide the system-drawn backdrop material for this window. This is the default. * `none` - Don't draw any system backdrop. * `mica` - Draw the backdrop material effect corresponding to a long-lived window. * `acrylic` - Draw the backdrop material effect corresponding to a transient window. * `tabbed` - Draw the backdrop material effect corresponding to a window with a tabbed title bar. This method sets the browser window's system-drawn background material, including behind the non-client area. See the [Windows documentation](https://learn.microsoft.com/en-us/windows/win32/api/dwmapi/ne-dwmapi-dwm_systembackdrop_type) for more details. **Note:** This method is only supported on Windows 11 22H2 and up. #### `win.setWindowButtonPosition(position)` _macOS_ * `position` [Point](structures/point.md) | null Set a custom position for the traffic light buttons in frameless window. Passing `null` will reset the position to default. #### `win.getWindowButtonPosition()` _macOS_ Returns `Point | null` - The custom position for the traffic light buttons in frameless window, `null` will be returned when there is no custom position. #### `win.setTrafficLightPosition(position)` _macOS_ _Deprecated_ * `position` [Point](structures/point.md) Set a custom position for the traffic light buttons in frameless window. Passing `{ x: 0, y: 0 }` will reset the position to default. > **Note** > This function is deprecated. Use [setWindowButtonPosition](#winsetwindowbuttonpositionposition-macos) instead. #### `win.getTrafficLightPosition()` _macOS_ _Deprecated_ Returns `Point` - The custom position for the traffic light buttons in frameless window, `{ x: 0, y: 0 }` will be returned when there is no custom position. > **Note** > This function is deprecated. Use [getWindowButtonPosition](#wingetwindowbuttonposition-macos) instead. #### `win.setTouchBar(touchBar)` _macOS_ * `touchBar` TouchBar | null Sets the touchBar layout for the current window. Specifying `null` or `undefined` clears the touch bar. This method only has an effect if the machine has a touch bar. **Note:** The TouchBar API is currently experimental and may change or be removed in future Electron releases. #### `win.setBrowserView(browserView)` _Experimental_ * `browserView` [BrowserView](browser-view.md) | null - Attach `browserView` to `win`. If there are other `BrowserView`s attached, they will be removed from this window. #### `win.getBrowserView()` _Experimental_ Returns `BrowserView | null` - The `BrowserView` attached to `win`. Returns `null` if one is not attached. Throws an error if multiple `BrowserView`s are attached. #### `win.addBrowserView(browserView)` _Experimental_ * `browserView` [BrowserView](browser-view.md) Replacement API for setBrowserView supporting work with multi browser views. #### `win.removeBrowserView(browserView)` _Experimental_ * `browserView` [BrowserView](browser-view.md) #### `win.setTopBrowserView(browserView)` _Experimental_ * `browserView` [BrowserView](browser-view.md) Raises `browserView` above other `BrowserView`s attached to `win`. Throws an error if `browserView` is not attached to `win`. #### `win.getBrowserViews()` _Experimental_ Returns `BrowserView[]` - a sorted by z-index array of all BrowserViews that have been attached with `addBrowserView` or `setBrowserView`. The top-most BrowserView is the last element of the array. **Note:** The BrowserView API is currently experimental and may change or be removed in future Electron releases. #### `win.setTitleBarOverlay(options)` _Windows_ * `options` Object * `color` String (optional) _Windows_ - The CSS color of the Window Controls Overlay when enabled. * `symbolColor` String (optional) _Windows_ - The CSS color of the symbols on the Window Controls Overlay when enabled. * `height` Integer (optional) _Windows_ - The height of the title bar and Window Controls Overlay in pixels. On a Window with Window Controls Overlay already enabled, this method updates the style of the title bar overlay. [page-visibility-api]: https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API [quick-look]: https://en.wikipedia.org/wiki/Quick_Look [vibrancy-docs]: https://developer.apple.com/documentation/appkit/nsvisualeffectview?preferredLanguage=objc [window-levels]: https://developer.apple.com/documentation/appkit/nswindow/level [event-emitter]: https://nodejs.org/api/events.html#events_class_eventemitter
closed
electron/electron
https://github.com/electron/electron
39,470
[Bug]: with wayland & gnome, maximizing a window to the side results in margin around the 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 25.3.1 and 22.3.18 ### What operating system are you using? Other Linux ### Operating System Version Linux jig 6.1.41-1-MANJARO #1 SMP PREEMPT_DYNAMIC Tue Jul 25 09:17:30 UTC 2023 x86_64 GNU/Linux ### What arch are you using? x64 ### Expected Behavior The demo app maximizes to the right or the left to take up half the screen, and the window extends to the top, bottom, and side all the way. ### Actual Behavior The demo app maximizes to the right or the left to take up half the screen, but the borders of the app don't extend all the way to the side and bottom of the screen. The title-bar extends all the way to the top of the screen, but the title bar is double the height it should be, and it seems to only respond to clicks in the bottom half ![image](https://github.com/electron/electron/assets/133676745/d79fef6a-6db4-45c5-a0e9-036a9e6871da) ### Additional information #### Reproduction steps - Install Manjaro with GNOME Shell 44.3, use gnome with wayland ``` pamac install electron electron --ozone-platform=wayland --enable-features=WaylandWindowDecorations ``` - Drag demo app to side of screen to maximize to the right or the left [Screencast from 2023-08-11 12-25-01.webm](https://github.com/electron/electron/assets/133676745/7e2cec76-df18-4de1-aea3-06c095d8ab68) Note: maximizing full screen works as intended, but this may be related to https://github.com/electron/electron/issues/33161
https://github.com/electron/electron/issues/39470
https://github.com/electron/electron/pull/39523
0621f3929693530076b75befbdaa83755f6cd4fa
c75e193a3e4683b1d55e56152dcef92e93d5eb56
2023-08-11T16:23:29Z
c++
2023-08-17T18:26:49Z
shell/browser/ui/views/client_frame_view_linux.cc
// Copyright (c) 2021 Ryan Gonzalez. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/ui/views/client_frame_view_linux.h" #include <algorithm> #include "base/strings/utf_string_conversions.h" #include "cc/paint/paint_filter.h" #include "cc/paint/paint_flags.h" #include "shell/browser/native_window_views.h" #include "shell/browser/ui/electron_desktop_window_tree_host_linux.h" #include "shell/browser/ui/views/frameless_view.h" #include "ui/base/hit_test.h" #include "ui/base/l10n/l10n_util.h" #include "ui/gfx/canvas.h" #include "ui/gfx/font_list.h" #include "ui/gfx/geometry/insets.h" #include "ui/gfx/geometry/rect.h" #include "ui/gfx/geometry/skia_conversions.h" #include "ui/gfx/skia_util.h" #include "ui/gfx/text_constants.h" #include "ui/gtk/gtk_compat.h" // nogncheck #include "ui/gtk/gtk_util.h" // nogncheck #include "ui/linux/linux_ui.h" #include "ui/linux/nav_button_provider.h" #include "ui/native_theme/native_theme.h" #include "ui/strings/grit/ui_strings.h" #include "ui/views/controls/button/image_button.h" #include "ui/views/style/typography.h" #include "ui/views/widget/widget.h" #include "ui/views/window/frame_buttons.h" #include "ui/views/window/window_button_order_provider.h" namespace electron { namespace { // These values should be the same as Chromium uses. constexpr int kResizeOutsideBorderSize = 10; constexpr int kResizeInsideBoundsSize = 5; ui::NavButtonProvider::ButtonState ButtonStateToNavButtonProviderState( views::Button::ButtonState state) { switch (state) { case views::Button::STATE_NORMAL: return ui::NavButtonProvider::ButtonState::kNormal; case views::Button::STATE_HOVERED: return ui::NavButtonProvider::ButtonState::kHovered; case views::Button::STATE_PRESSED: return ui::NavButtonProvider::ButtonState::kPressed; case views::Button::STATE_DISABLED: return ui::NavButtonProvider::ButtonState::kDisabled; case views::Button::STATE_COUNT: default: NOTREACHED(); return ui::NavButtonProvider::ButtonState::kNormal; } } } // namespace // static const char ClientFrameViewLinux::kViewClassName[] = "ClientFrameView"; ClientFrameViewLinux::ClientFrameViewLinux() : theme_(ui::NativeTheme::GetInstanceForNativeUi()), nav_button_provider_( ui::LinuxUiTheme::GetForProfile(nullptr)->CreateNavButtonProvider()), nav_buttons_{ NavButton{ui::NavButtonProvider::FrameButtonDisplayType::kClose, views::FrameButton::kClose, &views::Widget::Close, IDS_APP_ACCNAME_CLOSE, HTCLOSE}, NavButton{ui::NavButtonProvider::FrameButtonDisplayType::kMaximize, views::FrameButton::kMaximize, &views::Widget::Maximize, IDS_APP_ACCNAME_MAXIMIZE, HTMAXBUTTON}, NavButton{ui::NavButtonProvider::FrameButtonDisplayType::kRestore, views::FrameButton::kMaximize, &views::Widget::Restore, IDS_APP_ACCNAME_RESTORE, HTMAXBUTTON}, NavButton{ui::NavButtonProvider::FrameButtonDisplayType::kMinimize, views::FrameButton::kMinimize, &views::Widget::Minimize, IDS_APP_ACCNAME_MINIMIZE, HTMINBUTTON}, }, trailing_frame_buttons_{views::FrameButton::kMinimize, views::FrameButton::kMaximize, views::FrameButton::kClose} { for (auto& button : nav_buttons_) { button.button = new views::ImageButton(); button.button->SetImageVerticalAlignment(views::ImageButton::ALIGN_MIDDLE); button.button->SetAccessibleName( l10n_util::GetStringUTF16(button.accessibility_id)); AddChildView(button.button); } title_ = new views::Label(); title_->SetSubpixelRenderingEnabled(false); title_->SetAutoColorReadabilityEnabled(false); title_->SetHorizontalAlignment(gfx::ALIGN_CENTER); title_->SetVerticalAlignment(gfx::ALIGN_MIDDLE); title_->SetTextStyle(views::style::STYLE_TAB_ACTIVE); AddChildView(title_); native_theme_observer_.Observe(theme_); if (auto* ui = ui::LinuxUi::instance()) { ui->AddWindowButtonOrderObserver(this); OnWindowButtonOrderingChange(); } } ClientFrameViewLinux::~ClientFrameViewLinux() { if (auto* ui = ui::LinuxUi::instance()) ui->RemoveWindowButtonOrderObserver(this); theme_->RemoveObserver(this); } void ClientFrameViewLinux::Init(NativeWindowViews* window, views::Widget* frame) { FramelessView::Init(window, frame); // Unretained() is safe because the subscription is saved into an instance // member and thus will be cancelled upon the instance's destruction. paint_as_active_changed_subscription_ = frame_->RegisterPaintAsActiveChangedCallback(base::BindRepeating( &ClientFrameViewLinux::PaintAsActiveChanged, base::Unretained(this))); auto* tree_host = static_cast<ElectronDesktopWindowTreeHostLinux*>( ElectronDesktopWindowTreeHostLinux::GetHostForWidget( window->GetAcceleratedWidget())); host_supports_client_frame_shadow_ = tree_host->SupportsClientFrameShadow(); frame_provider_ = ui::LinuxUiTheme::GetForProfile(nullptr)->GetWindowFrameProvider( !host_supports_client_frame_shadow_, frame_->IsMaximized()); UpdateWindowTitle(); for (auto& button : nav_buttons_) { // Unretained() is safe because the buttons are added as children to, and // thus owned by, this view. Thus, the buttons themselves will be destroyed // when this view is destroyed, and the frame's life must never outlive the // view. button.button->SetCallback( base::BindRepeating(button.callback, base::Unretained(frame))); } UpdateThemeValues(); } gfx::Insets ClientFrameViewLinux::GetBorderDecorationInsets() const { return frame_provider_->GetFrameThicknessDip(); } gfx::Insets ClientFrameViewLinux::GetInputInsets() const { return gfx::Insets( host_supports_client_frame_shadow_ ? -kResizeOutsideBorderSize : 0); } gfx::Rect ClientFrameViewLinux::GetWindowContentBounds() const { gfx::Rect content_bounds = bounds(); content_bounds.Inset(GetBorderDecorationInsets()); return content_bounds; } SkRRect ClientFrameViewLinux::GetRoundedWindowContentBounds() const { SkRect rect = gfx::RectToSkRect(GetWindowContentBounds()); SkRRect rrect; if (!frame_->IsMaximized()) { SkPoint round_point{theme_values_.window_border_radius, theme_values_.window_border_radius}; SkPoint radii[] = {round_point, round_point, {}, {}}; rrect.setRectRadii(rect, radii); } else { rrect.setRect(rect); } return rrect; } void ClientFrameViewLinux::OnNativeThemeUpdated( ui::NativeTheme* observed_theme) { UpdateThemeValues(); } void ClientFrameViewLinux::OnWindowButtonOrderingChange() { auto* provider = views::WindowButtonOrderProvider::GetInstance(); leading_frame_buttons_ = provider->leading_buttons(); trailing_frame_buttons_ = provider->trailing_buttons(); InvalidateLayout(); } int ClientFrameViewLinux::ResizingBorderHitTest(const gfx::Point& point) { return ResizingBorderHitTestImpl( point, GetBorderDecorationInsets() + gfx::Insets(kResizeInsideBoundsSize)); } gfx::Rect ClientFrameViewLinux::GetBoundsForClientView() const { gfx::Rect client_bounds = bounds(); if (!frame_->IsFullscreen()) { client_bounds.Inset(GetBorderDecorationInsets()); client_bounds.Inset( gfx::Insets::TLBR(GetTitlebarBounds().height(), 0, 0, 0)); } return client_bounds; } gfx::Rect ClientFrameViewLinux::GetWindowBoundsForClientBounds( const gfx::Rect& client_bounds) const { gfx::Insets insets = bounds().InsetsFrom(GetBoundsForClientView()); return gfx::Rect(std::max(0, client_bounds.x() - insets.left()), std::max(0, client_bounds.y() - insets.top()), client_bounds.width() + insets.width(), client_bounds.height() + insets.height()); } int ClientFrameViewLinux::NonClientHitTest(const gfx::Point& point) { int component = ResizingBorderHitTest(point); if (component != HTNOWHERE) { return component; } for (auto& button : nav_buttons_) { if (button.button->GetVisible() && button.button->GetMirroredBounds().Contains(point)) { return button.hit_test_id; } } if (GetTitlebarBounds().Contains(point)) { return HTCAPTION; } return FramelessView::NonClientHitTest(point); } void ClientFrameViewLinux::GetWindowMask(const gfx::Size& size, SkPath* window_mask) { // Nothing to do here, as transparency is used for decorations, not masks. } void ClientFrameViewLinux::UpdateWindowTitle() { title_->SetText(base::UTF8ToUTF16(window_->GetTitle())); } void ClientFrameViewLinux::SizeConstraintsChanged() { InvalidateLayout(); } gfx::Size ClientFrameViewLinux::CalculatePreferredSize() const { return SizeWithDecorations(FramelessView::CalculatePreferredSize()); } gfx::Size ClientFrameViewLinux::GetMinimumSize() const { return SizeWithDecorations(FramelessView::GetMinimumSize()); } gfx::Size ClientFrameViewLinux::GetMaximumSize() const { return SizeWithDecorations(FramelessView::GetMaximumSize()); } void ClientFrameViewLinux::Layout() { FramelessView::Layout(); if (frame_->IsFullscreen()) { // Just hide everything and return. for (NavButton& button : nav_buttons_) { button.button->SetVisible(false); } title_->SetVisible(false); return; } frame_provider_ = ui::LinuxUiTheme::GetForProfile(nullptr)->GetWindowFrameProvider( !host_supports_client_frame_shadow_, frame_->IsMaximized()); UpdateButtonImages(); LayoutButtons(); gfx::Rect title_bounds(GetTitlebarContentBounds()); title_bounds.Inset(theme_values_.title_padding); title_->SetVisible(true); title_->SetBounds(title_bounds.x(), title_bounds.y(), title_bounds.width(), title_bounds.height()); } void ClientFrameViewLinux::OnPaint(gfx::Canvas* canvas) { if (!frame_->IsFullscreen()) { frame_provider_->PaintWindowFrame(canvas, GetLocalBounds(), GetTitlebarBounds().bottom(), ShouldPaintAsActive(), tiled_edges()); } } const char* ClientFrameViewLinux::GetClassName() const { return kViewClassName; } void ClientFrameViewLinux::PaintAsActiveChanged() { UpdateThemeValues(); } void ClientFrameViewLinux::UpdateThemeValues() { gtk::GtkCssContext window_context = gtk::AppendCssNodeToStyleContext({}, "window.background.csd"); gtk::GtkCssContext headerbar_context = gtk::AppendCssNodeToStyleContext( {}, "headerbar.default-decoration.titlebar"); gtk::GtkCssContext title_context = gtk::AppendCssNodeToStyleContext(headerbar_context, "label.title"); gtk::GtkCssContext button_context = gtk::AppendCssNodeToStyleContext( headerbar_context, "button.image-button"); gtk_style_context_set_parent(headerbar_context, window_context); gtk_style_context_set_parent(title_context, headerbar_context); gtk_style_context_set_parent(button_context, headerbar_context); // ShouldPaintAsActive asks the widget, so assume active if the widget is not // set yet. if (GetWidget() != nullptr && !ShouldPaintAsActive()) { gtk_style_context_set_state(window_context, GTK_STATE_FLAG_BACKDROP); gtk_style_context_set_state(headerbar_context, GTK_STATE_FLAG_BACKDROP); gtk_style_context_set_state(title_context, GTK_STATE_FLAG_BACKDROP); gtk_style_context_set_state(button_context, GTK_STATE_FLAG_BACKDROP); } theme_values_.window_border_radius = frame_provider_->GetTopCornerRadiusDip(); gtk::GtkStyleContextGet(headerbar_context, "min-height", &theme_values_.titlebar_min_height, nullptr); theme_values_.titlebar_padding = gtk::GtkStyleContextGetPadding(headerbar_context); theme_values_.title_color = gtk::GtkStyleContextGetColor(title_context); theme_values_.title_padding = gtk::GtkStyleContextGetPadding(title_context); gtk::GtkStyleContextGet(button_context, "min-height", &theme_values_.button_min_size, nullptr); theme_values_.button_padding = gtk::GtkStyleContextGetPadding(button_context); title_->SetEnabledColor(theme_values_.title_color); InvalidateLayout(); SchedulePaint(); } ui::NavButtonProvider::FrameButtonDisplayType ClientFrameViewLinux::GetButtonTypeToSkip() const { return frame_->IsMaximized() ? ui::NavButtonProvider::FrameButtonDisplayType::kMaximize : ui::NavButtonProvider::FrameButtonDisplayType::kRestore; } void ClientFrameViewLinux::UpdateButtonImages() { nav_button_provider_->RedrawImages(theme_values_.button_min_size, frame_->IsMaximized(), ShouldPaintAsActive()); ui::NavButtonProvider::FrameButtonDisplayType skip_type = GetButtonTypeToSkip(); for (NavButton& button : nav_buttons_) { if (button.type == skip_type) { continue; } for (size_t state_id = 0; state_id < views::Button::STATE_COUNT; state_id++) { views::Button::ButtonState state = static_cast<views::Button::ButtonState>(state_id); button.button->SetImage( state, nav_button_provider_->GetImage( button.type, ButtonStateToNavButtonProviderState(state))); } } } void ClientFrameViewLinux::LayoutButtons() { for (NavButton& button : nav_buttons_) { button.button->SetVisible(false); } gfx::Rect remaining_content_bounds = GetTitlebarContentBounds(); LayoutButtonsOnSide(ButtonSide::kLeading, &remaining_content_bounds); LayoutButtonsOnSide(ButtonSide::kTrailing, &remaining_content_bounds); } void ClientFrameViewLinux::LayoutButtonsOnSide( ButtonSide side, gfx::Rect* remaining_content_bounds) { ui::NavButtonProvider::FrameButtonDisplayType skip_type = GetButtonTypeToSkip(); std::vector<views::FrameButton> frame_buttons; switch (side) { case ButtonSide::kLeading: frame_buttons = leading_frame_buttons_; break; case ButtonSide::kTrailing: frame_buttons = trailing_frame_buttons_; // We always lay buttons out going from the edge towards the center, but // they are given to us as left-to-right, so reverse them. std::reverse(frame_buttons.begin(), frame_buttons.end()); break; default: NOTREACHED(); } for (views::FrameButton frame_button : frame_buttons) { auto* button = std::find_if( nav_buttons_.begin(), nav_buttons_.end(), [&](const NavButton& test) { return test.type != skip_type && test.frame_button == frame_button; }); CHECK(button != nav_buttons_.end()) << "Failed to find frame button: " << static_cast<int>(frame_button); if (button->type == skip_type) { continue; } button->button->SetVisible(true); int button_width = theme_values_.button_min_size; int next_button_offset = button_width + nav_button_provider_->GetInterNavButtonSpacing(); int x_position = 0; gfx::Insets inset_after_placement; switch (side) { case ButtonSide::kLeading: x_position = remaining_content_bounds->x(); inset_after_placement.set_left(next_button_offset); break; case ButtonSide::kTrailing: x_position = remaining_content_bounds->right() - button_width; inset_after_placement.set_right(next_button_offset); break; default: NOTREACHED(); } button->button->SetBounds(x_position, remaining_content_bounds->y(), button_width, remaining_content_bounds->height()); remaining_content_bounds->Inset(inset_after_placement); } } gfx::Rect ClientFrameViewLinux::GetTitlebarBounds() const { if (frame_->IsFullscreen()) { return gfx::Rect(); } int font_height = gfx::FontList().GetHeight(); int titlebar_height = std::max(font_height, theme_values_.titlebar_min_height) + GetTitlebarContentInsets().height(); gfx::Insets decoration_insets = GetBorderDecorationInsets(); // We add the inset height here, so the .Inset() that follows won't reduce it // to be too small. gfx::Rect titlebar(width(), titlebar_height + decoration_insets.height()); titlebar.Inset(decoration_insets); return titlebar; } gfx::Insets ClientFrameViewLinux::GetTitlebarContentInsets() const { return theme_values_.titlebar_padding + nav_button_provider_->GetTopAreaSpacing(); } gfx::Rect ClientFrameViewLinux::GetTitlebarContentBounds() const { gfx::Rect titlebar(GetTitlebarBounds()); titlebar.Inset(GetTitlebarContentInsets()); return titlebar; } gfx::Size ClientFrameViewLinux::SizeWithDecorations(gfx::Size size) const { gfx::Insets decoration_insets = GetBorderDecorationInsets(); size.Enlarge(0, GetTitlebarBounds().height()); size.Enlarge(decoration_insets.width(), decoration_insets.height()); return size; } views::View* ClientFrameViewLinux::TargetForRect(views::View* root, const gfx::Rect& rect) { return views::NonClientFrameView::TargetForRect(root, rect); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
39,470
[Bug]: with wayland & gnome, maximizing a window to the side results in margin around the 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 25.3.1 and 22.3.18 ### What operating system are you using? Other Linux ### Operating System Version Linux jig 6.1.41-1-MANJARO #1 SMP PREEMPT_DYNAMIC Tue Jul 25 09:17:30 UTC 2023 x86_64 GNU/Linux ### What arch are you using? x64 ### Expected Behavior The demo app maximizes to the right or the left to take up half the screen, and the window extends to the top, bottom, and side all the way. ### Actual Behavior The demo app maximizes to the right or the left to take up half the screen, but the borders of the app don't extend all the way to the side and bottom of the screen. The title-bar extends all the way to the top of the screen, but the title bar is double the height it should be, and it seems to only respond to clicks in the bottom half ![image](https://github.com/electron/electron/assets/133676745/d79fef6a-6db4-45c5-a0e9-036a9e6871da) ### Additional information #### Reproduction steps - Install Manjaro with GNOME Shell 44.3, use gnome with wayland ``` pamac install electron electron --ozone-platform=wayland --enable-features=WaylandWindowDecorations ``` - Drag demo app to side of screen to maximize to the right or the left [Screencast from 2023-08-11 12-25-01.webm](https://github.com/electron/electron/assets/133676745/7e2cec76-df18-4de1-aea3-06c095d8ab68) Note: maximizing full screen works as intended, but this may be related to https://github.com/electron/electron/issues/33161
https://github.com/electron/electron/issues/39470
https://github.com/electron/electron/pull/39523
0621f3929693530076b75befbdaa83755f6cd4fa
c75e193a3e4683b1d55e56152dcef92e93d5eb56
2023-08-11T16:23:29Z
c++
2023-08-17T18:26:49Z
shell/browser/ui/views/client_frame_view_linux.cc
// Copyright (c) 2021 Ryan Gonzalez. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/ui/views/client_frame_view_linux.h" #include <algorithm> #include "base/strings/utf_string_conversions.h" #include "cc/paint/paint_filter.h" #include "cc/paint/paint_flags.h" #include "shell/browser/native_window_views.h" #include "shell/browser/ui/electron_desktop_window_tree_host_linux.h" #include "shell/browser/ui/views/frameless_view.h" #include "ui/base/hit_test.h" #include "ui/base/l10n/l10n_util.h" #include "ui/gfx/canvas.h" #include "ui/gfx/font_list.h" #include "ui/gfx/geometry/insets.h" #include "ui/gfx/geometry/rect.h" #include "ui/gfx/geometry/skia_conversions.h" #include "ui/gfx/skia_util.h" #include "ui/gfx/text_constants.h" #include "ui/gtk/gtk_compat.h" // nogncheck #include "ui/gtk/gtk_util.h" // nogncheck #include "ui/linux/linux_ui.h" #include "ui/linux/nav_button_provider.h" #include "ui/native_theme/native_theme.h" #include "ui/strings/grit/ui_strings.h" #include "ui/views/controls/button/image_button.h" #include "ui/views/style/typography.h" #include "ui/views/widget/widget.h" #include "ui/views/window/frame_buttons.h" #include "ui/views/window/window_button_order_provider.h" namespace electron { namespace { // These values should be the same as Chromium uses. constexpr int kResizeOutsideBorderSize = 10; constexpr int kResizeInsideBoundsSize = 5; ui::NavButtonProvider::ButtonState ButtonStateToNavButtonProviderState( views::Button::ButtonState state) { switch (state) { case views::Button::STATE_NORMAL: return ui::NavButtonProvider::ButtonState::kNormal; case views::Button::STATE_HOVERED: return ui::NavButtonProvider::ButtonState::kHovered; case views::Button::STATE_PRESSED: return ui::NavButtonProvider::ButtonState::kPressed; case views::Button::STATE_DISABLED: return ui::NavButtonProvider::ButtonState::kDisabled; case views::Button::STATE_COUNT: default: NOTREACHED(); return ui::NavButtonProvider::ButtonState::kNormal; } } } // namespace // static const char ClientFrameViewLinux::kViewClassName[] = "ClientFrameView"; ClientFrameViewLinux::ClientFrameViewLinux() : theme_(ui::NativeTheme::GetInstanceForNativeUi()), nav_button_provider_( ui::LinuxUiTheme::GetForProfile(nullptr)->CreateNavButtonProvider()), nav_buttons_{ NavButton{ui::NavButtonProvider::FrameButtonDisplayType::kClose, views::FrameButton::kClose, &views::Widget::Close, IDS_APP_ACCNAME_CLOSE, HTCLOSE}, NavButton{ui::NavButtonProvider::FrameButtonDisplayType::kMaximize, views::FrameButton::kMaximize, &views::Widget::Maximize, IDS_APP_ACCNAME_MAXIMIZE, HTMAXBUTTON}, NavButton{ui::NavButtonProvider::FrameButtonDisplayType::kRestore, views::FrameButton::kMaximize, &views::Widget::Restore, IDS_APP_ACCNAME_RESTORE, HTMAXBUTTON}, NavButton{ui::NavButtonProvider::FrameButtonDisplayType::kMinimize, views::FrameButton::kMinimize, &views::Widget::Minimize, IDS_APP_ACCNAME_MINIMIZE, HTMINBUTTON}, }, trailing_frame_buttons_{views::FrameButton::kMinimize, views::FrameButton::kMaximize, views::FrameButton::kClose} { for (auto& button : nav_buttons_) { button.button = new views::ImageButton(); button.button->SetImageVerticalAlignment(views::ImageButton::ALIGN_MIDDLE); button.button->SetAccessibleName( l10n_util::GetStringUTF16(button.accessibility_id)); AddChildView(button.button); } title_ = new views::Label(); title_->SetSubpixelRenderingEnabled(false); title_->SetAutoColorReadabilityEnabled(false); title_->SetHorizontalAlignment(gfx::ALIGN_CENTER); title_->SetVerticalAlignment(gfx::ALIGN_MIDDLE); title_->SetTextStyle(views::style::STYLE_TAB_ACTIVE); AddChildView(title_); native_theme_observer_.Observe(theme_); if (auto* ui = ui::LinuxUi::instance()) { ui->AddWindowButtonOrderObserver(this); OnWindowButtonOrderingChange(); } } ClientFrameViewLinux::~ClientFrameViewLinux() { if (auto* ui = ui::LinuxUi::instance()) ui->RemoveWindowButtonOrderObserver(this); theme_->RemoveObserver(this); } void ClientFrameViewLinux::Init(NativeWindowViews* window, views::Widget* frame) { FramelessView::Init(window, frame); // Unretained() is safe because the subscription is saved into an instance // member and thus will be cancelled upon the instance's destruction. paint_as_active_changed_subscription_ = frame_->RegisterPaintAsActiveChangedCallback(base::BindRepeating( &ClientFrameViewLinux::PaintAsActiveChanged, base::Unretained(this))); auto* tree_host = static_cast<ElectronDesktopWindowTreeHostLinux*>( ElectronDesktopWindowTreeHostLinux::GetHostForWidget( window->GetAcceleratedWidget())); host_supports_client_frame_shadow_ = tree_host->SupportsClientFrameShadow(); frame_provider_ = ui::LinuxUiTheme::GetForProfile(nullptr)->GetWindowFrameProvider( !host_supports_client_frame_shadow_, frame_->IsMaximized()); UpdateWindowTitle(); for (auto& button : nav_buttons_) { // Unretained() is safe because the buttons are added as children to, and // thus owned by, this view. Thus, the buttons themselves will be destroyed // when this view is destroyed, and the frame's life must never outlive the // view. button.button->SetCallback( base::BindRepeating(button.callback, base::Unretained(frame))); } UpdateThemeValues(); } gfx::Insets ClientFrameViewLinux::GetBorderDecorationInsets() const { return frame_provider_->GetFrameThicknessDip(); } gfx::Insets ClientFrameViewLinux::GetInputInsets() const { return gfx::Insets( host_supports_client_frame_shadow_ ? -kResizeOutsideBorderSize : 0); } gfx::Rect ClientFrameViewLinux::GetWindowContentBounds() const { gfx::Rect content_bounds = bounds(); content_bounds.Inset(GetBorderDecorationInsets()); return content_bounds; } SkRRect ClientFrameViewLinux::GetRoundedWindowContentBounds() const { SkRect rect = gfx::RectToSkRect(GetWindowContentBounds()); SkRRect rrect; if (!frame_->IsMaximized()) { SkPoint round_point{theme_values_.window_border_radius, theme_values_.window_border_radius}; SkPoint radii[] = {round_point, round_point, {}, {}}; rrect.setRectRadii(rect, radii); } else { rrect.setRect(rect); } return rrect; } void ClientFrameViewLinux::OnNativeThemeUpdated( ui::NativeTheme* observed_theme) { UpdateThemeValues(); } void ClientFrameViewLinux::OnWindowButtonOrderingChange() { auto* provider = views::WindowButtonOrderProvider::GetInstance(); leading_frame_buttons_ = provider->leading_buttons(); trailing_frame_buttons_ = provider->trailing_buttons(); InvalidateLayout(); } int ClientFrameViewLinux::ResizingBorderHitTest(const gfx::Point& point) { return ResizingBorderHitTestImpl( point, GetBorderDecorationInsets() + gfx::Insets(kResizeInsideBoundsSize)); } gfx::Rect ClientFrameViewLinux::GetBoundsForClientView() const { gfx::Rect client_bounds = bounds(); if (!frame_->IsFullscreen()) { client_bounds.Inset(GetBorderDecorationInsets()); client_bounds.Inset( gfx::Insets::TLBR(GetTitlebarBounds().height(), 0, 0, 0)); } return client_bounds; } gfx::Rect ClientFrameViewLinux::GetWindowBoundsForClientBounds( const gfx::Rect& client_bounds) const { gfx::Insets insets = bounds().InsetsFrom(GetBoundsForClientView()); return gfx::Rect(std::max(0, client_bounds.x() - insets.left()), std::max(0, client_bounds.y() - insets.top()), client_bounds.width() + insets.width(), client_bounds.height() + insets.height()); } int ClientFrameViewLinux::NonClientHitTest(const gfx::Point& point) { int component = ResizingBorderHitTest(point); if (component != HTNOWHERE) { return component; } for (auto& button : nav_buttons_) { if (button.button->GetVisible() && button.button->GetMirroredBounds().Contains(point)) { return button.hit_test_id; } } if (GetTitlebarBounds().Contains(point)) { return HTCAPTION; } return FramelessView::NonClientHitTest(point); } void ClientFrameViewLinux::GetWindowMask(const gfx::Size& size, SkPath* window_mask) { // Nothing to do here, as transparency is used for decorations, not masks. } void ClientFrameViewLinux::UpdateWindowTitle() { title_->SetText(base::UTF8ToUTF16(window_->GetTitle())); } void ClientFrameViewLinux::SizeConstraintsChanged() { InvalidateLayout(); } gfx::Size ClientFrameViewLinux::CalculatePreferredSize() const { return SizeWithDecorations(FramelessView::CalculatePreferredSize()); } gfx::Size ClientFrameViewLinux::GetMinimumSize() const { return SizeWithDecorations(FramelessView::GetMinimumSize()); } gfx::Size ClientFrameViewLinux::GetMaximumSize() const { return SizeWithDecorations(FramelessView::GetMaximumSize()); } void ClientFrameViewLinux::Layout() { FramelessView::Layout(); if (frame_->IsFullscreen()) { // Just hide everything and return. for (NavButton& button : nav_buttons_) { button.button->SetVisible(false); } title_->SetVisible(false); return; } frame_provider_ = ui::LinuxUiTheme::GetForProfile(nullptr)->GetWindowFrameProvider( !host_supports_client_frame_shadow_, frame_->IsMaximized()); UpdateButtonImages(); LayoutButtons(); gfx::Rect title_bounds(GetTitlebarContentBounds()); title_bounds.Inset(theme_values_.title_padding); title_->SetVisible(true); title_->SetBounds(title_bounds.x(), title_bounds.y(), title_bounds.width(), title_bounds.height()); } void ClientFrameViewLinux::OnPaint(gfx::Canvas* canvas) { if (!frame_->IsFullscreen()) { frame_provider_->PaintWindowFrame(canvas, GetLocalBounds(), GetTitlebarBounds().bottom(), ShouldPaintAsActive(), tiled_edges()); } } const char* ClientFrameViewLinux::GetClassName() const { return kViewClassName; } void ClientFrameViewLinux::PaintAsActiveChanged() { UpdateThemeValues(); } void ClientFrameViewLinux::UpdateThemeValues() { gtk::GtkCssContext window_context = gtk::AppendCssNodeToStyleContext({}, "window.background.csd"); gtk::GtkCssContext headerbar_context = gtk::AppendCssNodeToStyleContext( {}, "headerbar.default-decoration.titlebar"); gtk::GtkCssContext title_context = gtk::AppendCssNodeToStyleContext(headerbar_context, "label.title"); gtk::GtkCssContext button_context = gtk::AppendCssNodeToStyleContext( headerbar_context, "button.image-button"); gtk_style_context_set_parent(headerbar_context, window_context); gtk_style_context_set_parent(title_context, headerbar_context); gtk_style_context_set_parent(button_context, headerbar_context); // ShouldPaintAsActive asks the widget, so assume active if the widget is not // set yet. if (GetWidget() != nullptr && !ShouldPaintAsActive()) { gtk_style_context_set_state(window_context, GTK_STATE_FLAG_BACKDROP); gtk_style_context_set_state(headerbar_context, GTK_STATE_FLAG_BACKDROP); gtk_style_context_set_state(title_context, GTK_STATE_FLAG_BACKDROP); gtk_style_context_set_state(button_context, GTK_STATE_FLAG_BACKDROP); } theme_values_.window_border_radius = frame_provider_->GetTopCornerRadiusDip(); gtk::GtkStyleContextGet(headerbar_context, "min-height", &theme_values_.titlebar_min_height, nullptr); theme_values_.titlebar_padding = gtk::GtkStyleContextGetPadding(headerbar_context); theme_values_.title_color = gtk::GtkStyleContextGetColor(title_context); theme_values_.title_padding = gtk::GtkStyleContextGetPadding(title_context); gtk::GtkStyleContextGet(button_context, "min-height", &theme_values_.button_min_size, nullptr); theme_values_.button_padding = gtk::GtkStyleContextGetPadding(button_context); title_->SetEnabledColor(theme_values_.title_color); InvalidateLayout(); SchedulePaint(); } ui::NavButtonProvider::FrameButtonDisplayType ClientFrameViewLinux::GetButtonTypeToSkip() const { return frame_->IsMaximized() ? ui::NavButtonProvider::FrameButtonDisplayType::kMaximize : ui::NavButtonProvider::FrameButtonDisplayType::kRestore; } void ClientFrameViewLinux::UpdateButtonImages() { nav_button_provider_->RedrawImages(theme_values_.button_min_size, frame_->IsMaximized(), ShouldPaintAsActive()); ui::NavButtonProvider::FrameButtonDisplayType skip_type = GetButtonTypeToSkip(); for (NavButton& button : nav_buttons_) { if (button.type == skip_type) { continue; } for (size_t state_id = 0; state_id < views::Button::STATE_COUNT; state_id++) { views::Button::ButtonState state = static_cast<views::Button::ButtonState>(state_id); button.button->SetImage( state, nav_button_provider_->GetImage( button.type, ButtonStateToNavButtonProviderState(state))); } } } void ClientFrameViewLinux::LayoutButtons() { for (NavButton& button : nav_buttons_) { button.button->SetVisible(false); } gfx::Rect remaining_content_bounds = GetTitlebarContentBounds(); LayoutButtonsOnSide(ButtonSide::kLeading, &remaining_content_bounds); LayoutButtonsOnSide(ButtonSide::kTrailing, &remaining_content_bounds); } void ClientFrameViewLinux::LayoutButtonsOnSide( ButtonSide side, gfx::Rect* remaining_content_bounds) { ui::NavButtonProvider::FrameButtonDisplayType skip_type = GetButtonTypeToSkip(); std::vector<views::FrameButton> frame_buttons; switch (side) { case ButtonSide::kLeading: frame_buttons = leading_frame_buttons_; break; case ButtonSide::kTrailing: frame_buttons = trailing_frame_buttons_; // We always lay buttons out going from the edge towards the center, but // they are given to us as left-to-right, so reverse them. std::reverse(frame_buttons.begin(), frame_buttons.end()); break; default: NOTREACHED(); } for (views::FrameButton frame_button : frame_buttons) { auto* button = std::find_if( nav_buttons_.begin(), nav_buttons_.end(), [&](const NavButton& test) { return test.type != skip_type && test.frame_button == frame_button; }); CHECK(button != nav_buttons_.end()) << "Failed to find frame button: " << static_cast<int>(frame_button); if (button->type == skip_type) { continue; } button->button->SetVisible(true); int button_width = theme_values_.button_min_size; int next_button_offset = button_width + nav_button_provider_->GetInterNavButtonSpacing(); int x_position = 0; gfx::Insets inset_after_placement; switch (side) { case ButtonSide::kLeading: x_position = remaining_content_bounds->x(); inset_after_placement.set_left(next_button_offset); break; case ButtonSide::kTrailing: x_position = remaining_content_bounds->right() - button_width; inset_after_placement.set_right(next_button_offset); break; default: NOTREACHED(); } button->button->SetBounds(x_position, remaining_content_bounds->y(), button_width, remaining_content_bounds->height()); remaining_content_bounds->Inset(inset_after_placement); } } gfx::Rect ClientFrameViewLinux::GetTitlebarBounds() const { if (frame_->IsFullscreen()) { return gfx::Rect(); } int font_height = gfx::FontList().GetHeight(); int titlebar_height = std::max(font_height, theme_values_.titlebar_min_height) + GetTitlebarContentInsets().height(); gfx::Insets decoration_insets = GetBorderDecorationInsets(); // We add the inset height here, so the .Inset() that follows won't reduce it // to be too small. gfx::Rect titlebar(width(), titlebar_height + decoration_insets.height()); titlebar.Inset(decoration_insets); return titlebar; } gfx::Insets ClientFrameViewLinux::GetTitlebarContentInsets() const { return theme_values_.titlebar_padding + nav_button_provider_->GetTopAreaSpacing(); } gfx::Rect ClientFrameViewLinux::GetTitlebarContentBounds() const { gfx::Rect titlebar(GetTitlebarBounds()); titlebar.Inset(GetTitlebarContentInsets()); return titlebar; } gfx::Size ClientFrameViewLinux::SizeWithDecorations(gfx::Size size) const { gfx::Insets decoration_insets = GetBorderDecorationInsets(); size.Enlarge(0, GetTitlebarBounds().height()); size.Enlarge(decoration_insets.width(), decoration_insets.height()); return size; } views::View* ClientFrameViewLinux::TargetForRect(views::View* root, const gfx::Rect& rect) { return views::NonClientFrameView::TargetForRect(root, rect); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
39,535
[Bug]: cannot open chrome://gpu on Linux
### 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 25.5.0 ### What operating system are you using? Other Linux ### Operating System Version openSUSE Tumbleweed ### What arch are you using? x64 ### Last Known Working Electron version 24.7.1 ### Expected Behavior When running `electron chrome://gpu` a page of system diagnostics should open. ### Actual Behavior Instead a blank window opens and `(node:14996) electron: Failed to load URL: chrome://gpu/ with error: ERR_FAILED` gets printed to console. ### Testcase Gist URL _No response_ ### Additional Information This issue happens with electron 25 and 26. It was fine in electron 24.
https://github.com/electron/electron/issues/39535
https://github.com/electron/electron/pull/39556
c75e193a3e4683b1d55e56152dcef92e93d5eb56
95bf9d8adb33bc2aaf988977b18663f9a770ef77
2023-08-16T14:34:57Z
c++
2023-08-21T00:41:00Z
electron_paks.gni
import("//build/config/locales.gni") import("//electron/buildflags/buildflags.gni") import("//printing/buildflags/buildflags.gni") import("//tools/grit/repack.gni") import("//ui/base/ui_features.gni") # See: //chrome/chrome_paks.gni template("electron_repack_percent") { percent = invoker.percent repack(target_name) { forward_variables_from(invoker, [ "copy_data_to_bundle", "repack_whitelist", "visibility", ]) # All sources should also have deps for completeness. sources = [ "$root_gen_dir/components/components_resources_${percent}_percent.pak", "$root_gen_dir/third_party/blink/public/resources/blink_scaled_resources_${percent}_percent.pak", "$root_gen_dir/ui/resources/ui_resources_${percent}_percent.pak", ] deps = [ "//components/resources", "//third_party/blink/public:scaled_resources_${percent}_percent", "//ui/resources", ] if (defined(invoker.deps)) { deps += invoker.deps } if (toolkit_views) { sources += [ "$root_gen_dir/ui/views/resources/views_resources_${percent}_percent.pak" ] deps += [ "//ui/views/resources" ] } output = "${invoker.output_dir}/chrome_${percent}_percent.pak" } } template("electron_extra_paks") { repack(target_name) { forward_variables_from(invoker, [ "copy_data_to_bundle", "repack_whitelist", "visibility", ]) output = "${invoker.output_dir}/resources.pak" sources = [ "$root_gen_dir/chrome/accessibility_resources.pak", "$root_gen_dir/chrome/browser_resources.pak", "$root_gen_dir/chrome/common_resources.pak", "$root_gen_dir/chrome/dev_ui_browser_resources.pak", "$root_gen_dir/components/components_resources.pak", "$root_gen_dir/content/browser/resources/media/media_internals_resources.pak", "$root_gen_dir/content/browser/tracing/tracing_resources.pak", "$root_gen_dir/content/browser/webrtc/resources/webrtc_internals_resources.pak", "$root_gen_dir/content/content_resources.pak", "$root_gen_dir/mojo/public/js/mojo_bindings_resources.pak", "$root_gen_dir/net/net_resources.pak", "$root_gen_dir/third_party/blink/public/resources/blink_resources.pak", "$root_gen_dir/third_party/blink/public/resources/inspector_overlay_resources.pak", "$target_gen_dir/electron_resources.pak", ] deps = [ "//chrome/browser:dev_ui_browser_resources", "//chrome/browser:resources", "//chrome/browser/resources/accessibility:resources", "//chrome/common:resources", "//components/resources", "//content:content_resources", "//content/browser/resources/media:resources", "//content/browser/tracing:resources", "//content/browser/webrtc/resources", "//electron:resources", "//mojo/public/js:resources", "//net:net_resources", "//third_party/blink/public:devtools_inspector_resources", "//third_party/blink/public:resources", "//ui/resources", ] if (defined(invoker.deps)) { deps += invoker.deps } if (defined(invoker.additional_paks)) { sources += invoker.additional_paks } # New paks should be added here by default. sources += [ "$root_gen_dir/content/browser/devtools/devtools_resources.pak", "$root_gen_dir/ui/resources/webui_resources.pak", ] deps += [ "//content/browser/devtools:devtools_resources" ] if (enable_pdf_viewer) { sources += [ "$root_gen_dir/chrome/pdf_resources.pak" ] deps += [ "//chrome/browser/resources/pdf:resources" ] } if (enable_print_preview) { sources += [ "$root_gen_dir/chrome/print_preview_resources.pak" ] deps += [ "//chrome/browser/resources/print_preview:resources" ] } if (enable_electron_extensions) { sources += [ "$root_gen_dir/chrome/component_extension_resources.pak", "$root_gen_dir/extensions/extensions_renderer_resources.pak", "$root_gen_dir/extensions/extensions_resources.pak", ] deps += [ "//chrome/browser/resources:component_extension_resources", "//extensions:extensions_resources", ] } } } template("electron_paks") { electron_repack_percent("${target_name}_100_percent") { percent = "100" forward_variables_from(invoker, [ "copy_data_to_bundle", "deps", "output_dir", "repack_whitelist", "visibility", ]) } if (enable_hidpi) { electron_repack_percent("${target_name}_200_percent") { percent = "200" forward_variables_from(invoker, [ "copy_data_to_bundle", "deps", "output_dir", "repack_whitelist", "visibility", ]) } } electron_extra_paks("${target_name}_extra") { forward_variables_from(invoker, [ "copy_data_to_bundle", "deps", "output_dir", "repack_whitelist", "visibility", ]) if (defined(invoker.additional_extra_paks)) { additional_paks = invoker.additional_extra_paks } } repack_locales("${target_name}_locales") { forward_variables_from(invoker, [ "copy_data_to_bundle", "deps", "visibility", ]) if (defined(invoker.locale_whitelist)) { repack_whitelist = invoker.locale_whitelist } else if (defined(invoker.repack_whitelist)) { repack_whitelist = invoker.repack_whitelist } source_patterns = [ "${root_gen_dir}/chrome/chromium_strings_", "${root_gen_dir}/chrome/locale_settings_", "${root_gen_dir}/chrome/platform_locale_settings_", "${root_gen_dir}/chrome/generated_resources_", "${root_gen_dir}/components/strings/components_locale_settings_", "${root_gen_dir}/components/strings/components_strings_", "${root_gen_dir}/device/bluetooth/strings/bluetooth_strings_", "${root_gen_dir}/extensions/strings/extensions_strings_", "${root_gen_dir}/services/strings/services_strings_", "${root_gen_dir}/third_party/blink/public/strings/blink_accessibility_strings_", "${root_gen_dir}/third_party/blink/public/strings/blink_strings_", "${root_gen_dir}/ui/strings/app_locale_settings_", "${root_gen_dir}/ui/strings/ax_strings_", "${root_gen_dir}/ui/strings/ui_strings_", ] deps = [ "//chrome/app:chromium_strings", "//chrome/app:generated_resources", "//chrome/app/resources:locale_settings", "//chrome/app/resources:platform_locale_settings", "//components/strings:components_locale_settings", "//components/strings:components_strings", "//device/bluetooth/strings", "//extensions/strings", "//services/strings", "//third_party/blink/public/strings", "//third_party/blink/public/strings:accessibility_strings", "//ui/strings:app_locale_settings", "//ui/strings:ax_strings", "//ui/strings:ui_strings", ] input_locales = platform_pak_locales output_dir = "${invoker.output_dir}/locales" if (is_mac) { output_locales = locales_as_apple_outputs } else { output_locales = platform_pak_locales } } group(target_name) { forward_variables_from(invoker, [ "deps" ]) public_deps = [ ":${target_name}_100_percent", ":${target_name}_extra", ":${target_name}_locales", ] if (enable_hidpi) { public_deps += [ ":${target_name}_200_percent" ] } if (defined(invoker.public_deps)) { public_deps += invoker.public_deps } } }
closed
electron/electron
https://github.com/electron/electron
39,535
[Bug]: cannot open chrome://gpu on Linux
### 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 25.5.0 ### What operating system are you using? Other Linux ### Operating System Version openSUSE Tumbleweed ### What arch are you using? x64 ### Last Known Working Electron version 24.7.1 ### Expected Behavior When running `electron chrome://gpu` a page of system diagnostics should open. ### Actual Behavior Instead a blank window opens and `(node:14996) electron: Failed to load URL: chrome://gpu/ with error: ERR_FAILED` gets printed to console. ### Testcase Gist URL _No response_ ### Additional Information This issue happens with electron 25 and 26. It was fine in electron 24.
https://github.com/electron/electron/issues/39535
https://github.com/electron/electron/pull/39556
c75e193a3e4683b1d55e56152dcef92e93d5eb56
95bf9d8adb33bc2aaf988977b18663f9a770ef77
2023-08-16T14:34:57Z
c++
2023-08-21T00:41:00Z
spec/chromium-spec.ts
import { expect } from 'chai'; import { BrowserWindow, WebContents, webFrameMain, session, ipcMain, app, protocol, webContents } from 'electron/main'; import { closeAllWindows } from './lib/window-helpers'; import * as https from 'node:https'; import * as http from 'node:http'; import * as path from 'node:path'; import * as fs from 'node:fs'; import * as url from 'node:url'; import * as ChildProcess from 'node:child_process'; import { EventEmitter, once } from 'node:events'; import { promisify } from 'node:util'; import { ifit, ifdescribe, defer, itremote, listen } from './lib/spec-helpers'; import { PipeTransport } from './pipe-transport'; import * as ws from 'ws'; import { setTimeout } from 'node:timers/promises'; const features = process._linkedBinding('electron_common_features'); const fixturesPath = path.resolve(__dirname, 'fixtures'); const certPath = path.join(fixturesPath, 'certificates'); describe('reporting api', () => { it('sends a report for an intervention', async () => { const reporting = new EventEmitter(); // The Reporting API only works on https with valid certs. To dodge having // to set up a trusted certificate, hack the validator. session.defaultSession.setCertificateVerifyProc((req, cb) => { cb(0); }); const options = { key: fs.readFileSync(path.join(certPath, 'server.key')), cert: fs.readFileSync(path.join(certPath, 'server.pem')), ca: [ fs.readFileSync(path.join(certPath, 'rootCA.pem')), fs.readFileSync(path.join(certPath, 'intermediateCA.pem')) ], requestCert: true, rejectUnauthorized: false }; const server = https.createServer(options, (req, res) => { if (req.url?.endsWith('report')) { let data = ''; req.on('data', (d) => { data += d.toString('utf-8'); }); req.on('end', () => { reporting.emit('report', JSON.parse(data)); }); } const { port } = server.address() as any; res.setHeader('Reporting-Endpoints', `default="https://localhost:${port}/report"`); res.setHeader('Content-Type', 'text/html'); res.end('<script>window.navigator.vibrate(1)</script>'); }); await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve)); const bw = new BrowserWindow({ show: false }); try { const reportGenerated = once(reporting, 'report'); await bw.loadURL(`https://localhost:${(server.address() as any).port}/a`); const [reports] = await reportGenerated; expect(reports).to.be.an('array').with.lengthOf(1); const { type, url, body } = reports[0]; expect(type).to.equal('intervention'); expect(url).to.equal(url); expect(body.id).to.equal('NavigatorVibrate'); expect(body.message).to.match(/Blocked call to navigator.vibrate because user hasn't tapped on the frame or any embedded frame yet/); } finally { bw.destroy(); server.close(); } }); }); describe('window.postMessage', () => { afterEach(async () => { await closeAllWindows(); }); it('sets the source and origin correctly', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadURL(`file://${fixturesPath}/pages/window-open-postMessage-driver.html`); const [, message] = await once(ipcMain, 'complete'); expect(message.data).to.equal('testing'); expect(message.origin).to.equal('file://'); expect(message.sourceEqualsOpener).to.equal(true); expect(message.eventOrigin).to.equal('file://'); }); }); describe('focus handling', () => { let webviewContents: WebContents; let w: BrowserWindow; beforeEach(async () => { w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true, webviewTag: true, contextIsolation: false } }); const webviewReady = once(w.webContents, 'did-attach-webview') as Promise<[any, WebContents]>; await w.loadFile(path.join(fixturesPath, 'pages', 'tab-focus-loop-elements.html')); const [, wvContents] = await webviewReady; webviewContents = wvContents; await once(webviewContents, 'did-finish-load'); w.focus(); }); afterEach(() => { webviewContents = null as unknown as WebContents; w.destroy(); w = null as unknown as BrowserWindow; }); const expectFocusChange = async () => { const [, focusedElementId] = await once(ipcMain, 'focus-changed'); return focusedElementId; }; describe('a TAB press', () => { const tabPressEvent: any = { type: 'keyDown', keyCode: 'Tab' }; it('moves focus to the next focusable item', async () => { let focusChange = expectFocusChange(); w.webContents.sendInputEvent(tabPressEvent); let focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-element-1', `should start focused in element-1, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); w.webContents.sendInputEvent(tabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-element-2', `focus should've moved to element-2, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); w.webContents.sendInputEvent(tabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-wv-element-1', `focus should've moved to the webview's element-1, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); webviewContents.sendInputEvent(tabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-wv-element-2', `focus should've moved to the webview's element-2, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); webviewContents.sendInputEvent(tabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-element-3', `focus should've moved to element-3, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); w.webContents.sendInputEvent(tabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-element-1', `focus should've looped back to element-1, it's instead in ${focusedElementId}`); }); }); describe('a SHIFT + TAB press', () => { const shiftTabPressEvent: any = { type: 'keyDown', modifiers: ['Shift'], keyCode: 'Tab' }; it('moves focus to the previous focusable item', async () => { let focusChange = expectFocusChange(); w.webContents.sendInputEvent(shiftTabPressEvent); let focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-element-3', `should start focused in element-3, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); w.webContents.sendInputEvent(shiftTabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-wv-element-2', `focus should've moved to the webview's element-2, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); webviewContents.sendInputEvent(shiftTabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-wv-element-1', `focus should've moved to the webview's element-1, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); webviewContents.sendInputEvent(shiftTabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-element-2', `focus should've moved to element-2, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); w.webContents.sendInputEvent(shiftTabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-element-1', `focus should've moved to element-1, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); w.webContents.sendInputEvent(shiftTabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-element-3', `focus should've looped back to element-3, it's instead in ${focusedElementId}`); }); }); }); describe('web security', () => { afterEach(closeAllWindows); let server: http.Server; let serverUrl: string; before(async () => { server = http.createServer((req, res) => { res.setHeader('Content-Type', 'text/html'); res.end('<body>'); }); serverUrl = (await listen(server)).url; }); after(() => { server.close(); }); it('engages CORB when web security is not disabled', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: true, nodeIntegration: true, contextIsolation: false } }); const p = once(ipcMain, 'success'); await w.loadURL(`data:text/html,<script> const s = document.createElement('script') s.src = "${serverUrl}" // The script will load successfully but its body will be emptied out // by CORB, so we don't expect a syntax error. s.onload = () => { require('electron').ipcRenderer.send('success') } document.documentElement.appendChild(s) </script>`); await p; }); it('bypasses CORB when web security is disabled', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: false, nodeIntegration: true, contextIsolation: false } }); const p = once(ipcMain, 'success'); await w.loadURL(`data:text/html, <script> window.onerror = (e) => { require('electron').ipcRenderer.send('success', e) } </script> <script src="${serverUrl}"></script>`); await p; }); it('engages CORS when web security is not disabled', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: true, nodeIntegration: true, contextIsolation: false } }); const p = once(ipcMain, 'response'); await w.loadURL(`data:text/html,<script> (async function() { try { await fetch('${serverUrl}'); require('electron').ipcRenderer.send('response', 'passed'); } catch { require('electron').ipcRenderer.send('response', 'failed'); } })(); </script>`); const [, response] = await p; expect(response).to.equal('failed'); }); it('bypasses CORS when web security is disabled', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: false, nodeIntegration: true, contextIsolation: false } }); const p = once(ipcMain, 'response'); await w.loadURL(`data:text/html,<script> (async function() { try { await fetch('${serverUrl}'); require('electron').ipcRenderer.send('response', 'passed'); } catch { require('electron').ipcRenderer.send('response', 'failed'); } })(); </script>`); const [, response] = await p; expect(response).to.equal('passed'); }); describe('accessing file://', () => { async function loadFile (w: BrowserWindow) { const thisFile = url.format({ pathname: __filename.replace(/\\/g, '/'), protocol: 'file', slashes: true }); await w.loadURL(`data:text/html,<script> function loadFile() { return new Promise((resolve) => { fetch('${thisFile}').then( () => resolve('loaded'), () => resolve('failed') ) }); } </script>`); return await w.webContents.executeJavaScript('loadFile()'); } it('is forbidden when web security is enabled', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: true } }); const result = await loadFile(w); expect(result).to.equal('failed'); }); it('is allowed when web security is disabled', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: false } }); const result = await loadFile(w); expect(result).to.equal('loaded'); }); }); describe('wasm-eval csp', () => { async function loadWasm (csp: string) { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, enableBlinkFeatures: 'WebAssemblyCSP' } }); await w.loadURL(`data:text/html,<head> <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-inline' ${csp}"> </head> <script> function loadWasm() { const wasmBin = new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0]) return new Promise((resolve) => { WebAssembly.instantiate(wasmBin).then(() => { resolve('loaded') }).catch((error) => { resolve(error.message) }) }); } </script>`); return await w.webContents.executeJavaScript('loadWasm()'); } it('wasm codegen is disallowed by default', async () => { const r = await loadWasm(''); expect(r).to.equal('WebAssembly.instantiate(): Refused to compile or instantiate WebAssembly module because \'unsafe-eval\' is not an allowed source of script in the following Content Security Policy directive: "script-src \'self\' \'unsafe-inline\'"'); }); it('wasm codegen is allowed with "wasm-unsafe-eval" csp', async () => { const r = await loadWasm("'wasm-unsafe-eval'"); expect(r).to.equal('loaded'); }); }); describe('csp', () => { for (const sandbox of [true, false]) { describe(`when sandbox: ${sandbox}`, () => { for (const contextIsolation of [true, false]) { describe(`when contextIsolation: ${contextIsolation}`, () => { it('prevents eval from running in an inline script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox, contextIsolation } }); w.loadURL(`data:text/html,<head> <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-inline'"> </head> <script> try { // We use console.log here because it is easier than making a // preload script, and the behavior under test changes when // contextIsolation: false console.log(eval('true')) } catch (e) { console.log(e.message) } </script>`); const [,, message] = await once(w.webContents, 'console-message'); expect(message).to.match(/Refused to evaluate a string/); }); it('does not prevent eval from running in an inline script when there is no csp', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox, contextIsolation } }); w.loadURL(`data:text/html, <script> try { // We use console.log here because it is easier than making a // preload script, and the behavior under test changes when // contextIsolation: false console.log(eval('true')) } catch (e) { console.log(e.message) } </script>`); const [,, message] = await once(w.webContents, 'console-message'); expect(message).to.equal('true'); }); it('prevents eval from running in executeJavaScript', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox, contextIsolation } }); w.loadURL('data:text/html,<head><meta http-equiv="Content-Security-Policy" content="default-src \'self\'; script-src \'self\' \'unsafe-inline\'"></meta></head>'); await expect(w.webContents.executeJavaScript('eval("true")')).to.be.rejected(); }); it('does not prevent eval from running in executeJavaScript when there is no csp', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox, contextIsolation } }); w.loadURL('data:text/html,'); expect(await w.webContents.executeJavaScript('eval("true")')).to.be.true(); }); }); } }); } }); it('does not crash when multiple WebContent are created with web security disabled', () => { const options = { show: false, webPreferences: { webSecurity: false } }; const w1 = new BrowserWindow(options); w1.loadURL(serverUrl); const w2 = new BrowserWindow(options); w2.loadURL(serverUrl); }); }); describe('command line switches', () => { let appProcess: ChildProcess.ChildProcessWithoutNullStreams | undefined; afterEach(() => { if (appProcess && !appProcess.killed) { appProcess.kill(); appProcess = undefined; } }); describe('--lang switch', () => { const currentLocale = app.getLocale(); const currentSystemLocale = app.getSystemLocale(); const currentPreferredLanguages = JSON.stringify(app.getPreferredSystemLanguages()); const testLocale = async (locale: string, result: string, printEnv: boolean = false) => { const appPath = path.join(fixturesPath, 'api', 'locale-check'); const args = [appPath, `--set-lang=${locale}`]; if (printEnv) { args.push('--print-env'); } appProcess = ChildProcess.spawn(process.execPath, args); let output = ''; appProcess.stdout.on('data', (data) => { output += data; }); let stderr = ''; appProcess.stderr.on('data', (data) => { stderr += data; }); const [code, signal] = await once(appProcess, 'exit'); if (code !== 0) { throw new Error(`Process exited with code "${code}" signal "${signal}" output "${output}" stderr "${stderr}"`); } output = output.replace(/(\r\n|\n|\r)/gm, ''); expect(output).to.equal(result); }; it('should set the locale', async () => testLocale('fr', `fr|${currentSystemLocale}|${currentPreferredLanguages}`)); it('should set the locale with country code', async () => testLocale('zh-CN', `zh-CN|${currentSystemLocale}|${currentPreferredLanguages}`)); it('should not set an invalid locale', async () => testLocale('asdfkl', `${currentLocale}|${currentSystemLocale}|${currentPreferredLanguages}`)); const lcAll = String(process.env.LC_ALL); ifit(process.platform === 'linux')('current process has a valid LC_ALL env', async () => { // The LC_ALL env should not be set to DOM locale string. expect(lcAll).to.not.equal(app.getLocale()); }); ifit(process.platform === 'linux')('should not change LC_ALL', async () => testLocale('fr', lcAll, true)); ifit(process.platform === 'linux')('should not change LC_ALL when setting invalid locale', async () => testLocale('asdfkl', lcAll, true)); ifit(process.platform === 'linux')('should not change LC_ALL when --lang is not set', async () => testLocale('', lcAll, true)); }); describe('--remote-debugging-pipe switch', () => { it('should expose CDP via pipe', async () => { const electronPath = process.execPath; appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-pipe'], { stdio: ['inherit', 'inherit', 'inherit', 'pipe', 'pipe'] }) as ChildProcess.ChildProcessWithoutNullStreams; const stdio = appProcess.stdio as unknown as [NodeJS.ReadableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.ReadableStream]; const pipe = new PipeTransport(stdio[3], stdio[4]); const versionPromise = new Promise(resolve => { pipe.onmessage = resolve; }); pipe.send({ id: 1, method: 'Browser.getVersion', params: {} }); const message = (await versionPromise) as any; expect(message.id).to.equal(1); expect(message.result.product).to.contain('Chrome'); expect(message.result.userAgent).to.contain('Electron'); }); it('should override --remote-debugging-port switch', async () => { const electronPath = process.execPath; appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-pipe', '--remote-debugging-port=0'], { stdio: ['inherit', 'inherit', 'pipe', 'pipe', 'pipe'] }) as ChildProcess.ChildProcessWithoutNullStreams; let stderr = ''; appProcess.stderr.on('data', (data: string) => { stderr += data; }); const stdio = appProcess.stdio as unknown as [NodeJS.ReadableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.ReadableStream]; const pipe = new PipeTransport(stdio[3], stdio[4]); const versionPromise = new Promise(resolve => { pipe.onmessage = resolve; }); pipe.send({ id: 1, method: 'Browser.getVersion', params: {} }); const message = (await versionPromise) as any; expect(message.id).to.equal(1); expect(stderr).to.not.include('DevTools listening on'); }); it('should shut down Electron upon Browser.close CDP command', async () => { const electronPath = process.execPath; appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-pipe'], { stdio: ['inherit', 'inherit', 'inherit', 'pipe', 'pipe'] }) as ChildProcess.ChildProcessWithoutNullStreams; const stdio = appProcess.stdio as unknown as [NodeJS.ReadableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.ReadableStream]; const pipe = new PipeTransport(stdio[3], stdio[4]); pipe.send({ id: 1, method: 'Browser.close', params: {} }); await once(appProcess, 'exit'); }); }); describe('--remote-debugging-port switch', () => { it('should display the discovery page', (done) => { const electronPath = process.execPath; let output = ''; appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-port=']); appProcess.stdout.on('data', (data) => { console.log(data); }); appProcess.stderr.on('data', (data) => { console.log(data); output += data; const m = /DevTools listening on ws:\/\/127.0.0.1:(\d+)\//.exec(output); if (m) { appProcess!.stderr.removeAllListeners('data'); const port = m[1]; http.get(`http://127.0.0.1:${port}`, (res) => { try { expect(res.statusCode).to.eql(200); expect(parseInt(res.headers['content-length']!)).to.be.greaterThan(0); done(); } catch (e) { done(e); } finally { res.destroy(); } }); } }); }); }); }); describe('chromium features', () => { afterEach(closeAllWindows); describe('accessing key names also used as Node.js module names', () => { it('does not crash', (done) => { const w = new BrowserWindow({ show: false }); w.webContents.once('did-finish-load', () => { done(); }); w.webContents.once('render-process-gone', () => done(new Error('WebContents crashed.'))); w.loadFile(path.join(fixturesPath, 'pages', 'external-string.html')); }); }); describe('first party sets', () => { const fps = [ 'https://fps-member1.glitch.me', 'https://fps-member2.glitch.me', 'https://fps-member3.glitch.me' ]; it('loads first party sets', async () => { const appPath = path.join(fixturesPath, 'api', 'first-party-sets', 'base'); const fpsProcess = ChildProcess.spawn(process.execPath, [appPath]); let output = ''; fpsProcess.stdout.on('data', data => { output += data; }); await once(fpsProcess, 'exit'); expect(output).to.include(fps.join(',')); }); it('loads sets from the command line', async () => { const appPath = path.join(fixturesPath, 'api', 'first-party-sets', 'command-line'); const args = [appPath, `--use-first-party-set=${fps}`]; const fpsProcess = ChildProcess.spawn(process.execPath, args); let output = ''; fpsProcess.stdout.on('data', data => { output += data; }); await once(fpsProcess, 'exit'); expect(output).to.include(fps.join(',')); }); }); describe('loading jquery', () => { it('does not crash', (done) => { const w = new BrowserWindow({ show: false }); w.webContents.once('did-finish-load', () => { done(); }); w.webContents.once('render-process-gone', () => done(new Error('WebContents crashed.'))); w.loadFile(path.join(__dirname, 'fixtures', 'pages', 'jquery.html')); }); }); describe('navigator.languages', () => { it('should return the system locale only', async () => { const appLocale = app.getLocale(); const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const languages = await w.webContents.executeJavaScript('navigator.languages'); expect(languages.length).to.be.greaterThan(0); expect(languages).to.contain(appLocale); }); }); describe('navigator.serviceWorker', () => { it('should register for file scheme', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, partition: 'sw-file-scheme-spec', contextIsolation: false } }); w.webContents.on('ipc-message', (event, channel, message) => { if (channel === 'reload') { w.webContents.reload(); } else if (channel === 'error') { done(message); } else if (channel === 'response') { expect(message).to.equal('Hello from serviceWorker!'); session.fromPartition('sw-file-scheme-spec').clearStorageData({ storages: ['serviceworkers'] }).then(() => done()); } }); w.webContents.on('render-process-gone', () => done(new Error('WebContents crashed.'))); w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'index.html')); }); it('should register for intercepted file scheme', (done) => { const customSession = session.fromPartition('intercept-file'); customSession.protocol.interceptBufferProtocol('file', (request, callback) => { let file = url.parse(request.url).pathname!; if (file[0] === '/' && process.platform === 'win32') file = file.slice(1); const content = fs.readFileSync(path.normalize(file)); const ext = path.extname(file); let type = 'text/html'; if (ext === '.js') type = 'application/javascript'; callback({ data: content, mimeType: type } as any); }); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, session: customSession, contextIsolation: false } }); w.webContents.on('ipc-message', (event, channel, message) => { if (channel === 'reload') { w.webContents.reload(); } else if (channel === 'error') { done(`unexpected error : ${message}`); } else if (channel === 'response') { expect(message).to.equal('Hello from serviceWorker!'); customSession.clearStorageData({ storages: ['serviceworkers'] }).then(() => { customSession.protocol.uninterceptProtocol('file'); done(); }); } }); w.webContents.on('render-process-gone', () => done(new Error('WebContents crashed.'))); w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'index.html')); }); it('should register for custom scheme', (done) => { const customSession = session.fromPartition('custom-scheme'); customSession.protocol.registerFileProtocol(serviceWorkerScheme, (request, callback) => { let file = url.parse(request.url).pathname!; if (file[0] === '/' && process.platform === 'win32') file = file.slice(1); callback({ path: path.normalize(file) } as any); }); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, session: customSession, contextIsolation: false } }); w.webContents.on('ipc-message', (event, channel, message) => { if (channel === 'reload') { w.webContents.reload(); } else if (channel === 'error') { done(`unexpected error : ${message}`); } else if (channel === 'response') { expect(message).to.equal('Hello from serviceWorker!'); customSession.clearStorageData({ storages: ['serviceworkers'] }).then(() => { customSession.protocol.uninterceptProtocol(serviceWorkerScheme); done(); }); } }); w.webContents.on('render-process-gone', () => done(new Error('WebContents crashed.'))); w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'custom-scheme-index.html')); }); it('should not allow nodeIntegrationInWorker', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, nodeIntegrationInWorker: true, partition: 'sw-file-scheme-worker-spec', contextIsolation: false } }); await w.loadURL(`file://${fixturesPath}/pages/service-worker/empty.html`); const data = await w.webContents.executeJavaScript(` navigator.serviceWorker.register('worker-no-node.js', { scope: './' }).then(() => navigator.serviceWorker.ready) new Promise((resolve) => { navigator.serviceWorker.onmessage = event => resolve(event.data); }); `); expect(data).to.equal('undefined undefined undefined undefined'); }); }); describe('navigator.geolocation', () => { ifit(features.isFakeLocationProviderEnabled())('returns error when permission is denied', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, partition: 'geolocation-spec', contextIsolation: false } }); const message = once(w.webContents, 'ipc-message'); w.webContents.session.setPermissionRequestHandler((wc, permission, callback) => { if (permission === 'geolocation') { callback(false); } else { callback(true); } }); w.loadFile(path.join(fixturesPath, 'pages', 'geolocation', 'index.html')); const [, channel] = await message; expect(channel).to.equal('success', 'unexpected response from geolocation api'); }); ifit(!features.isFakeLocationProviderEnabled())('returns position when permission is granted', async () => { const w = new BrowserWindow({ show: false, webPreferences: { partition: 'geolocation-spec' } }); w.webContents.session.setPermissionRequestHandler((_wc, _permission, callback) => { callback(true); }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const position = await w.webContents.executeJavaScript(`new Promise((resolve, reject) => navigator.geolocation.getCurrentPosition( x => resolve({coords: x.coords, timestamp: x.timestamp}), err => reject(new Error(err.message))))`); expect(position).to.have.property('coords'); expect(position).to.have.property('timestamp'); }); }); describe('web workers', () => { let appProcess: ChildProcess.ChildProcessWithoutNullStreams | undefined; afterEach(() => { if (appProcess && !appProcess.killed) { appProcess.kill(); appProcess = undefined; } }); it('Worker with nodeIntegrationInWorker has access to self.module.paths', async () => { const appPath = path.join(__dirname, 'fixtures', 'apps', 'self-module-paths'); appProcess = ChildProcess.spawn(process.execPath, [appPath]); const [code] = await once(appProcess, 'exit'); expect(code).to.equal(0); }); it('Worker can work', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const data = await w.webContents.executeJavaScript(` const worker = new Worker('../workers/worker.js'); const message = 'ping'; const eventPromise = new Promise((resolve) => { worker.onmessage = resolve; }); worker.postMessage(message); eventPromise.then(t => t.data) `); expect(data).to.equal('ping'); }); it('Worker has no node integration by default', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const data = await w.webContents.executeJavaScript(` const worker = new Worker('../workers/worker_node.js'); new Promise((resolve) => { worker.onmessage = e => resolve(e.data); }) `); expect(data).to.equal('undefined undefined undefined undefined'); }); it('Worker has node integration with nodeIntegrationInWorker', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, nodeIntegrationInWorker: true, contextIsolation: false } }); w.loadURL(`file://${fixturesPath}/pages/worker.html`); const [, data] = await once(ipcMain, 'worker-result'); expect(data).to.equal('object function object function'); }); describe('SharedWorker', () => { it('can work', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const data = await w.webContents.executeJavaScript(` const worker = new SharedWorker('../workers/shared_worker.js'); const message = 'ping'; const eventPromise = new Promise((resolve) => { worker.port.onmessage = e => resolve(e.data); }); worker.port.postMessage(message); eventPromise `); expect(data).to.equal('ping'); }); it('has no node integration by default', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const data = await w.webContents.executeJavaScript(` const worker = new SharedWorker('../workers/shared_worker_node.js'); new Promise((resolve) => { worker.port.onmessage = e => resolve(e.data); }) `); expect(data).to.equal('undefined undefined undefined undefined'); }); it('does not have node integration with nodeIntegrationInWorker', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, nodeIntegrationInWorker: true, contextIsolation: false } }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const data = await w.webContents.executeJavaScript(` const worker = new SharedWorker('../workers/shared_worker_node.js'); new Promise((resolve) => { worker.port.onmessage = e => resolve(e.data); }) `); expect(data).to.equal('undefined undefined undefined undefined'); }); }); }); describe('form submit', () => { let server: http.Server; let serverUrl: string; before(async () => { server = http.createServer((req, res) => { let body = ''; req.on('data', (chunk) => { body += chunk; }); res.setHeader('Content-Type', 'application/json'); req.on('end', () => { res.end(`body:${body}`); }); }); serverUrl = (await listen(server)).url; }); after(async () => { server.close(); await closeAllWindows(); }); [true, false].forEach((isSandboxEnabled) => describe(`sandbox=${isSandboxEnabled}`, () => { it('posts data in the same window', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: isSandboxEnabled } }); await w.loadFile(path.join(fixturesPath, 'pages', 'form-with-data.html')); const loadPromise = once(w.webContents, 'did-finish-load'); w.webContents.executeJavaScript(` const form = document.querySelector('form') form.action = '${serverUrl}'; form.submit(); `); await loadPromise; const res = await w.webContents.executeJavaScript('document.body.innerText'); expect(res).to.equal('body:greeting=hello'); }); it('posts data to a new window with target=_blank', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: isSandboxEnabled } }); await w.loadFile(path.join(fixturesPath, 'pages', 'form-with-data.html')); const windowCreatedPromise = once(app, 'browser-window-created') as Promise<[any, BrowserWindow]>; w.webContents.executeJavaScript(` const form = document.querySelector('form') form.action = '${serverUrl}'; form.target = '_blank'; form.submit(); `); const [, newWin] = await windowCreatedPromise; const res = await newWin.webContents.executeJavaScript('document.body.innerText'); expect(res).to.equal('body:greeting=hello'); }); }) ); }); describe('window.open', () => { for (const show of [true, false]) { it(`shows the child regardless of parent visibility when parent {show=${show}}`, async () => { const w = new BrowserWindow({ show }); // toggle visibility if (show) { w.hide(); } else { w.show(); } defer(() => { w.close(); }); const promise = once(app, 'browser-window-created') as Promise<[any, BrowserWindow]>; w.loadFile(path.join(fixturesPath, 'pages', 'window-open.html')); const [, newWindow] = await promise; expect(newWindow.isVisible()).to.equal(true); }); } // FIXME(zcbenz): This test is making the spec runner hang on exit on Windows. ifit(process.platform !== 'win32')('disables node integration when it is disabled on the parent window', async () => { const windowUrl = url.pathToFileURL(path.join(fixturesPath, 'pages', 'window-opener-no-node-integration.html')); windowUrl.searchParams.set('p', `${fixturesPath}/pages/window-opener-node.html`); const w = new BrowserWindow({ show: false }); w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); const { eventData } = await w.webContents.executeJavaScript(`(async () => { const message = new Promise(resolve => window.addEventListener('message', resolve, {once: true})); const b = window.open(${JSON.stringify(windowUrl)}, '', 'show=false') const e = await message b.close(); return { eventData: e.data } })()`); expect(eventData.isProcessGlobalUndefined).to.be.true(); }); it('disables node integration when it is disabled on the parent window for chrome devtools URLs', async () => { // NB. webSecurity is disabled because native window.open() is not // allowed to load devtools:// URLs. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webSecurity: false } }); w.loadURL('about:blank'); w.webContents.executeJavaScript(` { b = window.open('devtools://devtools/bundled/inspector.html', '', 'nodeIntegration=no,show=no'); null } `); const [, contents] = await once(app, 'web-contents-created') as [any, WebContents]; const typeofProcessGlobal = await contents.executeJavaScript('typeof process'); expect(typeofProcessGlobal).to.equal('undefined'); }); it('can disable node integration when it is enabled on the parent window', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); w.loadURL('about:blank'); w.webContents.executeJavaScript(` { b = window.open('about:blank', '', 'nodeIntegration=no,show=no'); null } `); const [, contents] = await once(app, 'web-contents-created') as [any, WebContents]; const typeofProcessGlobal = await contents.executeJavaScript('typeof process'); expect(typeofProcessGlobal).to.equal('undefined'); }); // TODO(jkleinsc) fix this flaky test on WOA ifit(process.platform !== 'win32' || process.arch !== 'arm64')('disables JavaScript when it is disabled on the parent window', async () => { const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true } }); w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); const windowUrl = require('node:url').format({ pathname: `${fixturesPath}/pages/window-no-javascript.html`, protocol: 'file', slashes: true }); w.webContents.executeJavaScript(` { b = window.open(${JSON.stringify(windowUrl)}, '', 'javascript=no,show=no'); null } `); const [, contents] = await once(app, 'web-contents-created') as [any, WebContents]; await once(contents, 'did-finish-load'); // Click link on page contents.sendInputEvent({ type: 'mouseDown', clickCount: 1, x: 1, y: 1 }); contents.sendInputEvent({ type: 'mouseUp', clickCount: 1, x: 1, y: 1 }); const [, window] = await once(app, 'browser-window-created') as [any, BrowserWindow]; const preferences = window.webContents.getLastWebPreferences(); expect(preferences!.javascript).to.be.false(); }); it('defines a window.location getter', async () => { let targetURL: string; if (process.platform === 'win32') { targetURL = `file:///${fixturesPath.replace(/\\/g, '/')}/pages/base-page.html`; } else { targetURL = `file://${fixturesPath}/pages/base-page.html`; } const w = new BrowserWindow({ show: false }); w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); w.webContents.executeJavaScript(`{ b = window.open(${JSON.stringify(targetURL)}); null }`); const [, window] = await once(app, 'browser-window-created') as [any, BrowserWindow]; await once(window.webContents, 'did-finish-load'); expect(await w.webContents.executeJavaScript('b.location.href')).to.equal(targetURL); }); it('defines a window.location setter', async () => { const w = new BrowserWindow({ show: false }); w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); w.webContents.executeJavaScript('{ b = window.open("about:blank"); null }'); const [, { webContents }] = await once(app, 'browser-window-created') as [any, BrowserWindow]; await once(webContents, 'did-finish-load'); // When it loads, redirect w.webContents.executeJavaScript(`{ b.location = ${JSON.stringify(`file://${fixturesPath}/pages/base-page.html`)}; null }`); await once(webContents, 'did-finish-load'); }); it('defines a window.location.href setter', async () => { const w = new BrowserWindow({ show: false }); w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); w.webContents.executeJavaScript('{ b = window.open("about:blank"); null }'); const [, { webContents }] = await once(app, 'browser-window-created') as [any, BrowserWindow]; await once(webContents, 'did-finish-load'); // When it loads, redirect w.webContents.executeJavaScript(`{ b.location.href = ${JSON.stringify(`file://${fixturesPath}/pages/base-page.html`)}; null }`); await once(webContents, 'did-finish-load'); }); it('open a blank page when no URL is specified', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.executeJavaScript('{ b = window.open(); null }'); const [, { webContents }] = await once(app, 'browser-window-created') as [any, BrowserWindow]; await once(webContents, 'did-finish-load'); expect(await w.webContents.executeJavaScript('b.location.href')).to.equal('about:blank'); }); it('open a blank page when an empty URL is specified', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.executeJavaScript('{ b = window.open(\'\'); null }'); const [, { webContents }] = await once(app, 'browser-window-created') as [any, BrowserWindow]; await once(webContents, 'did-finish-load'); expect(await w.webContents.executeJavaScript('b.location.href')).to.equal('about:blank'); }); it('does not throw an exception when the frameName is a built-in object property', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.executeJavaScript('{ b = window.open(\'\', \'__proto__\'); null }'); const frameName = await new Promise((resolve) => { w.webContents.setWindowOpenHandler(details => { setImmediate(() => resolve(details.frameName)); return { action: 'allow' }; }); }); expect(frameName).to.equal('__proto__'); }); it('works when used in conjunction with the vm module', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); await w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); const { contextObject } = await w.webContents.executeJavaScript(`(async () => { const vm = require('node:vm'); const contextObject = { count: 1, type: 'gecko' }; window.open(''); vm.runInNewContext('count += 1; type = "chameleon";', contextObject); return { contextObject }; })()`); expect(contextObject).to.deep.equal({ count: 2, type: 'chameleon' }); }); // FIXME(nornagon): I'm not sure this ... ever was correct? xit('inherit options of parent window', async () => { const w = new BrowserWindow({ show: false, width: 123, height: 456 }); w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); const url = `file://${fixturesPath}/pages/window-open-size.html`; const { width, height, eventData } = await w.webContents.executeJavaScript(`(async () => { const message = new Promise(resolve => window.addEventListener('message', resolve, {once: true})); const b = window.open(${JSON.stringify(url)}, '', 'show=false') const e = await message b.close(); const width = outerWidth; const height = outerHeight; return { width, height, eventData: e.data } })()`); expect(eventData).to.equal(`size: ${width} ${height}`); expect(eventData).to.equal('size: 123 456'); }); it('does not override child options', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); const windowUrl = `file://${fixturesPath}/pages/window-open-size.html`; const { eventData } = await w.webContents.executeJavaScript(`(async () => { const message = new Promise(resolve => window.addEventListener('message', resolve, {once: true})); const b = window.open(${JSON.stringify(windowUrl)}, '', 'show=no,width=350,height=450') const e = await message b.close(); return { eventData: e.data } })()`); expect(eventData).to.equal('size: 350 450'); }); it('loads preload script after setting opener to null', async () => { const w = new BrowserWindow({ show: false }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: path.join(fixturesPath, 'module', 'preload.js') } } })); w.loadURL('about:blank'); w.webContents.executeJavaScript('window.child = window.open(); child.opener = null'); const [, { webContents }] = await once(app, 'browser-window-created'); const [,, message] = await once(webContents, 'console-message'); expect(message).to.equal('{"require":"function","module":"undefined","process":"object","Buffer":"function"}'); }); it('disables the <webview> tag when it is disabled on the parent window', async () => { const windowUrl = url.pathToFileURL(path.join(fixturesPath, 'pages', 'window-opener-no-webview-tag.html')); windowUrl.searchParams.set('p', `${fixturesPath}/pages/window-opener-webview.html`); const w = new BrowserWindow({ show: false }); w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); const { eventData } = await w.webContents.executeJavaScript(`(async () => { const message = new Promise(resolve => window.addEventListener('message', resolve, {once: true})); const b = window.open(${JSON.stringify(windowUrl)}, '', 'webviewTag=no,contextIsolation=no,nodeIntegration=yes,show=no') const e = await message b.close(); return { eventData: e.data } })()`); expect(eventData.isWebViewGlobalUndefined).to.be.true(); }); it('throws an exception when the arguments cannot be converted to strings', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); await expect( w.webContents.executeJavaScript('window.open(\'\', { toString: null })') ).to.eventually.be.rejected(); await expect( w.webContents.executeJavaScript('window.open(\'\', \'\', { toString: 3 })') ).to.eventually.be.rejected(); }); it('does not throw an exception when the features include webPreferences', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); await expect( w.webContents.executeJavaScript('window.open(\'\', \'\', \'show=no,webPreferences=\'); null') ).to.eventually.be.fulfilled(); }); }); describe('window.opener', () => { it('is null for main window', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixturesPath, 'pages', 'window-opener.html')); const [, channel, opener] = await once(w.webContents, 'ipc-message'); expect(channel).to.equal('opener'); expect(opener).to.equal(null); }); it('is not null for window opened by window.open', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); const windowUrl = `file://${fixturesPath}/pages/window-opener.html`; const eventData = await w.webContents.executeJavaScript(` const b = window.open(${JSON.stringify(windowUrl)}, '', 'show=no'); new Promise(resolve => window.addEventListener('message', resolve, {once: true})).then(e => e.data); `); expect(eventData).to.equal('object'); }); }); describe('window.opener.postMessage', () => { it('sets source and origin correctly', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); const windowUrl = `file://${fixturesPath}/pages/window-opener-postMessage.html`; const { sourceIsChild, origin } = await w.webContents.executeJavaScript(` const b = window.open(${JSON.stringify(windowUrl)}, '', 'show=no'); new Promise(resolve => window.addEventListener('message', resolve, {once: true})).then(e => ({ sourceIsChild: e.source === b, origin: e.origin })); `); expect(sourceIsChild).to.be.true(); expect(origin).to.equal('file://'); }); it('supports windows opened from a <webview>', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } }); w.loadURL('about:blank'); const childWindowUrl = url.pathToFileURL(path.join(fixturesPath, 'pages', 'webview-opener-postMessage.html')); childWindowUrl.searchParams.set('p', `${fixturesPath}/pages/window-opener-postMessage.html`); const message = await w.webContents.executeJavaScript(` const webview = new WebView(); webview.allowpopups = true; webview.setAttribute('webpreferences', 'contextIsolation=no'); webview.src = ${JSON.stringify(childWindowUrl)} const consoleMessage = new Promise(resolve => webview.addEventListener('console-message', resolve, {once: true})); document.body.appendChild(webview); consoleMessage.then(e => e.message) `); expect(message).to.equal('message'); }); describe('targetOrigin argument', () => { let serverURL: string; let server: any; beforeEach(async () => { server = http.createServer((req, res) => { res.writeHead(200); const filePath = path.join(fixturesPath, 'pages', 'window-opener-targetOrigin.html'); res.end(fs.readFileSync(filePath, 'utf8')); }); serverURL = (await listen(server)).url; }); afterEach(() => { server.close(); }); it('delivers messages that match the origin', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); const data = await w.webContents.executeJavaScript(` window.open(${JSON.stringify(serverURL)}, '', 'show=no,contextIsolation=no,nodeIntegration=yes'); new Promise(resolve => window.addEventListener('message', resolve, {once: true})).then(e => e.data) `); expect(data).to.equal('deliver'); }); }); }); describe('IdleDetection', () => { afterEach(closeAllWindows); afterEach(() => { session.defaultSession.setPermissionCheckHandler(null); session.defaultSession.setPermissionRequestHandler(null); }); it('can grant a permission request', async () => { session.defaultSession.setPermissionRequestHandler( (_wc, permission, callback) => { callback(permission === 'idle-detection'); } ); const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'button.html')); const permission = await w.webContents.executeJavaScript(` new Promise((resolve, reject) => { const button = document.getElementById('button'); button.addEventListener("click", async () => { const permission = await IdleDetector.requestPermission(); resolve(permission); }); button.click(); }); `, true); expect(permission).to.eq('granted'); }); it('can deny a permission request', async () => { session.defaultSession.setPermissionRequestHandler( (_wc, permission, callback) => { callback(permission !== 'idle-detection'); } ); const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'button.html')); const permission = await w.webContents.executeJavaScript(` new Promise((resolve, reject) => { const button = document.getElementById('button'); button.addEventListener("click", async () => { const permission = await IdleDetector.requestPermission(); resolve(permission); }); button.click(); }); `, true); expect(permission).to.eq('denied'); }); it('can allow the IdleDetector to start', async () => { session.defaultSession.setPermissionCheckHandler((wc, permission) => { return permission === 'idle-detection'; }); const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); const result = await w.webContents.executeJavaScript(` const detector = new IdleDetector({ threshold: 60000 }); detector.start().then(() => { return 'success'; }).catch(e => e.message); `, true); expect(result).to.eq('success'); }); it('can prevent the IdleDetector from starting', async () => { session.defaultSession.setPermissionCheckHandler((wc, permission) => { return permission !== 'idle-detection'; }); const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); const result = await w.webContents.executeJavaScript(` const detector = new IdleDetector({ threshold: 60000 }); detector.start().then(() => { console.log('success') }).catch(e => e.message); `, true); expect(result).to.eq('Idle detection permission denied'); }); }); describe('navigator.mediaDevices', () => { afterEach(closeAllWindows); afterEach(() => { session.defaultSession.setPermissionCheckHandler(null); session.defaultSession.setPermissionRequestHandler(null); }); it('can return labels of enumerated devices', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); const labels = await w.webContents.executeJavaScript('navigator.mediaDevices.enumerateDevices().then(ds => ds.map(d => d.label))'); expect(labels.some((l: any) => l)).to.be.true(); }); it('does not return labels of enumerated devices when permission denied', async () => { session.defaultSession.setPermissionCheckHandler(() => false); const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); const labels = await w.webContents.executeJavaScript('navigator.mediaDevices.enumerateDevices().then(ds => ds.map(d => d.label))'); expect(labels.some((l: any) => l)).to.be.false(); }); it('returns the same device ids across reloads', async () => { const ses = session.fromPartition('persist:media-device-id'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, session: ses, contextIsolation: false } }); w.loadFile(path.join(fixturesPath, 'pages', 'media-id-reset.html')); const [, firstDeviceIds] = await once(ipcMain, 'deviceIds'); w.webContents.reload(); const [, secondDeviceIds] = await once(ipcMain, 'deviceIds'); expect(firstDeviceIds).to.deep.equal(secondDeviceIds); }); it('can return new device id when cookie storage is cleared', async () => { const ses = session.fromPartition('persist:media-device-id'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, session: ses, contextIsolation: false } }); w.loadFile(path.join(fixturesPath, 'pages', 'media-id-reset.html')); const [, firstDeviceIds] = await once(ipcMain, 'deviceIds'); await ses.clearStorageData({ storages: ['cookies'] }); w.webContents.reload(); const [, secondDeviceIds] = await once(ipcMain, 'deviceIds'); expect(firstDeviceIds).to.not.deep.equal(secondDeviceIds); }); it('provides a securityOrigin to the request handler', async () => { session.defaultSession.setPermissionRequestHandler( (wc, permission, callback, details) => { if (details.securityOrigin !== undefined) { callback(true); } else { callback(false); } } ); const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); const labels = await w.webContents.executeJavaScript(`navigator.mediaDevices.getUserMedia({ video: { mandatory: { chromeMediaSource: "desktop", minWidth: 1280, maxWidth: 1280, minHeight: 720, maxHeight: 720 } } }).then((stream) => stream.getVideoTracks())`); expect(labels.some((l: any) => l)).to.be.true(); }); it('fails with "not supported" for getDisplayMedia', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); const { ok, err } = await w.webContents.executeJavaScript('navigator.mediaDevices.getDisplayMedia({video: true}).then(s => ({ok: true}), e => ({ok: false, err: e.message}))', true); expect(ok).to.be.false(); expect(err).to.equal('Not supported'); }); }); describe('window.opener access', () => { const scheme = 'app'; const fileUrl = `file://${fixturesPath}/pages/window-opener-location.html`; const httpUrl1 = `${scheme}://origin1`; const httpUrl2 = `${scheme}://origin2`; const fileBlank = `file://${fixturesPath}/pages/blank.html`; const httpBlank = `${scheme}://origin1/blank`; const table = [ { parent: fileBlank, child: httpUrl1, nodeIntegration: false, openerAccessible: false }, { parent: fileBlank, child: httpUrl1, nodeIntegration: true, openerAccessible: false }, // {parent: httpBlank, child: fileUrl, nodeIntegration: false, openerAccessible: false}, // can't window.open() // {parent: httpBlank, child: fileUrl, nodeIntegration: true, openerAccessible: false}, // can't window.open() // NB. this is different from Chrome's behavior, which isolates file: urls from each other { parent: fileBlank, child: fileUrl, nodeIntegration: false, openerAccessible: true }, { parent: fileBlank, child: fileUrl, nodeIntegration: true, openerAccessible: true }, { parent: httpBlank, child: httpUrl1, nodeIntegration: false, openerAccessible: true }, { parent: httpBlank, child: httpUrl1, nodeIntegration: true, openerAccessible: true }, { parent: httpBlank, child: httpUrl2, nodeIntegration: false, openerAccessible: false }, { parent: httpBlank, child: httpUrl2, nodeIntegration: true, openerAccessible: false } ]; const s = (url: string) => url.startsWith('file') ? 'file://...' : url; before(() => { protocol.registerFileProtocol(scheme, (request, callback) => { if (request.url.includes('blank')) { callback(`${fixturesPath}/pages/blank.html`); } else { callback(`${fixturesPath}/pages/window-opener-location.html`); } }); }); after(() => { protocol.unregisterProtocol(scheme); }); afterEach(closeAllWindows); describe('when opened from main window', () => { for (const { parent, child, nodeIntegration, openerAccessible } of table) { for (const sandboxPopup of [false, true]) { const description = `when parent=${s(parent)} opens child=${s(child)} with nodeIntegration=${nodeIntegration} sandboxPopup=${sandboxPopup}, child should ${openerAccessible ? '' : 'not '}be able to access opener`; it(description, async () => { const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { sandbox: sandboxPopup } } })); await w.loadURL(parent); const childOpenerLocation = await w.webContents.executeJavaScript(`new Promise(resolve => { window.addEventListener('message', function f(e) { resolve(e.data) }) window.open(${JSON.stringify(child)}, "", "show=no,nodeIntegration=${nodeIntegration ? 'yes' : 'no'}") })`); if (openerAccessible) { expect(childOpenerLocation).to.be.a('string'); } else { expect(childOpenerLocation).to.be.null(); } }); } } }); describe('when opened from <webview>', () => { for (const { parent, child, nodeIntegration, openerAccessible } of table) { const description = `when parent=${s(parent)} opens child=${s(child)} with nodeIntegration=${nodeIntegration}, child should ${openerAccessible ? '' : 'not '}be able to access opener`; it(description, async () => { // This test involves three contexts: // 1. The root BrowserWindow in which the test is run, // 2. A <webview> belonging to the root window, // 3. A window opened by calling window.open() from within the <webview>. // We are testing whether context (3) can access context (2) under various conditions. // This is context (1), the base window for the test. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webviewTag: true, contextIsolation: false } }); await w.loadURL('about:blank'); const parentCode = `new Promise((resolve) => { // This is context (3), a child window of the WebView. const child = window.open(${JSON.stringify(child)}, "", "show=no,contextIsolation=no,nodeIntegration=yes") window.addEventListener("message", e => { resolve(e.data) }) })`; const childOpenerLocation = await w.webContents.executeJavaScript(`new Promise((resolve, reject) => { // This is context (2), a WebView which will call window.open() const webview = new WebView() webview.setAttribute('nodeintegration', '${nodeIntegration ? 'on' : 'off'}') webview.setAttribute('webpreferences', 'contextIsolation=no') webview.setAttribute('allowpopups', 'on') webview.src = ${JSON.stringify(parent + '?p=' + encodeURIComponent(child))} webview.addEventListener('dom-ready', async () => { webview.executeJavaScript(${JSON.stringify(parentCode)}).then(resolve, reject) }) document.body.appendChild(webview) })`); if (openerAccessible) { expect(childOpenerLocation).to.be.a('string'); } else { expect(childOpenerLocation).to.be.null(); } }); } }); }); describe('storage', () => { describe('custom non standard schemes', () => { const protocolName = 'storage'; let contents: WebContents; before(() => { protocol.registerFileProtocol(protocolName, (request, callback) => { const parsedUrl = url.parse(request.url); let filename; switch (parsedUrl.pathname) { case '/localStorage' : filename = 'local_storage.html'; break; case '/sessionStorage' : filename = 'session_storage.html'; break; case '/WebSQL' : filename = 'web_sql.html'; break; case '/indexedDB' : filename = 'indexed_db.html'; break; case '/cookie' : filename = 'cookie.html'; break; default : filename = ''; } callback({ path: `${fixturesPath}/pages/storage/${filename}` }); }); }); after(() => { protocol.unregisterProtocol(protocolName); }); beforeEach(() => { contents = (webContents as typeof ElectronInternal.WebContents).create({ nodeIntegration: true, contextIsolation: false }); }); afterEach(() => { contents.destroy(); contents = null as any; }); it('cannot access localStorage', async () => { const response = once(ipcMain, 'local-storage-response'); contents.loadURL(protocolName + '://host/localStorage'); const [, error] = await response; expect(error).to.equal('Failed to read the \'localStorage\' property from \'Window\': Access is denied for this document.'); }); it('cannot access sessionStorage', async () => { const response = once(ipcMain, 'session-storage-response'); contents.loadURL(`${protocolName}://host/sessionStorage`); const [, error] = await response; expect(error).to.equal('Failed to read the \'sessionStorage\' property from \'Window\': Access is denied for this document.'); }); it('cannot access WebSQL database', async () => { const response = once(ipcMain, 'web-sql-response'); contents.loadURL(`${protocolName}://host/WebSQL`); const [, error] = await response; expect(error).to.equal('Failed to execute \'openDatabase\' on \'Window\': Access to the WebDatabase API is denied in this context.'); }); it('cannot access indexedDB', async () => { const response = once(ipcMain, 'indexed-db-response'); contents.loadURL(`${protocolName}://host/indexedDB`); const [, error] = await response; expect(error).to.equal('Failed to execute \'open\' on \'IDBFactory\': access to the Indexed Database API is denied in this context.'); }); it('cannot access cookie', async () => { const response = once(ipcMain, 'cookie-response'); contents.loadURL(`${protocolName}://host/cookie`); const [, error] = await response; expect(error).to.equal('Failed to set the \'cookie\' property on \'Document\': Access is denied for this document.'); }); }); describe('can be accessed', () => { let server: http.Server; let serverUrl: string; let serverCrossSiteUrl: string; before(async () => { server = http.createServer((req, res) => { const respond = () => { if (req.url === '/redirect-cross-site') { res.setHeader('Location', `${serverCrossSiteUrl}/redirected`); res.statusCode = 302; res.end(); } else if (req.url === '/redirected') { res.end('<html><script>window.localStorage</script></html>'); } else { res.end(); } }; setTimeout().then(respond); }); serverUrl = (await listen(server)).url; serverCrossSiteUrl = serverUrl.replace('127.0.0.1', 'localhost'); }); after(() => { server.close(); server = null as any; }); afterEach(closeAllWindows); const testLocalStorageAfterXSiteRedirect = (testTitle: string, extraPreferences = {}) => { it(testTitle, async () => { const w = new BrowserWindow({ show: false, ...extraPreferences }); let redirected = false; w.webContents.on('render-process-gone', () => { expect.fail('renderer crashed / was killed'); }); w.webContents.on('did-redirect-navigation', (event, url) => { expect(url).to.equal(`${serverCrossSiteUrl}/redirected`); redirected = true; }); await w.loadURL(`${serverUrl}/redirect-cross-site`); expect(redirected).to.be.true('didnt redirect'); }); }; testLocalStorageAfterXSiteRedirect('after a cross-site redirect'); testLocalStorageAfterXSiteRedirect('after a cross-site redirect in sandbox mode', { sandbox: true }); }); describe('enableWebSQL webpreference', () => { const origin = `${standardScheme}://fake-host`; const filePath = path.join(fixturesPath, 'pages', 'storage', 'web_sql.html'); const sqlPartition = 'web-sql-preference-test'; const sqlSession = session.fromPartition(sqlPartition); const securityError = 'An attempt was made to break through the security policy of the user agent.'; let contents: WebContents, w: BrowserWindow; before(() => { sqlSession.protocol.registerFileProtocol(standardScheme, (request, callback) => { callback({ path: filePath }); }); }); after(() => { sqlSession.protocol.unregisterProtocol(standardScheme); }); afterEach(async () => { if (contents) { contents.destroy(); contents = null as any; } await closeAllWindows(); (w as any) = null; }); it('default value allows websql', async () => { contents = (webContents as typeof ElectronInternal.WebContents).create({ session: sqlSession, nodeIntegration: true, contextIsolation: false }); contents.loadURL(origin); const [, error] = await once(ipcMain, 'web-sql-response'); expect(error).to.be.null(); }); it('when set to false can disallow websql', async () => { contents = (webContents as typeof ElectronInternal.WebContents).create({ session: sqlSession, nodeIntegration: true, enableWebSQL: false, contextIsolation: false }); contents.loadURL(origin); const [, error] = await once(ipcMain, 'web-sql-response'); expect(error).to.equal(securityError); }); it('when set to false does not disable indexedDB', async () => { contents = (webContents as typeof ElectronInternal.WebContents).create({ session: sqlSession, nodeIntegration: true, enableWebSQL: false, contextIsolation: false }); contents.loadURL(origin); const [, error] = await once(ipcMain, 'web-sql-response'); expect(error).to.equal(securityError); const dbName = 'random'; const result = await contents.executeJavaScript(` new Promise((resolve, reject) => { try { let req = window.indexedDB.open('${dbName}'); req.onsuccess = (event) => { let db = req.result; resolve(db.name); } req.onerror = (event) => { resolve(event.target.code); } } catch (e) { resolve(e.message); } }); `); expect(result).to.equal(dbName); }); it('child webContents can override when the embedder has allowed websql', async () => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webviewTag: true, session: sqlSession, contextIsolation: false } }); w.webContents.loadURL(origin); const [, error] = await once(ipcMain, 'web-sql-response'); expect(error).to.be.null(); const webviewResult = once(ipcMain, 'web-sql-response'); await w.webContents.executeJavaScript(` new Promise((resolve, reject) => { const webview = new WebView(); webview.setAttribute('src', '${origin}'); webview.setAttribute('webpreferences', 'enableWebSQL=0,contextIsolation=no'); webview.setAttribute('partition', '${sqlPartition}'); webview.setAttribute('nodeIntegration', 'on'); document.body.appendChild(webview); webview.addEventListener('dom-ready', () => resolve()); }); `); const [, childError] = await webviewResult; expect(childError).to.equal(securityError); }); it('child webContents cannot override when the embedder has disallowed websql', async () => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, enableWebSQL: false, webviewTag: true, session: sqlSession, contextIsolation: false } }); w.webContents.loadURL('data:text/html,<html></html>'); const webviewResult = once(ipcMain, 'web-sql-response'); await w.webContents.executeJavaScript(` new Promise((resolve, reject) => { const webview = new WebView(); webview.setAttribute('src', '${origin}'); webview.setAttribute('webpreferences', 'enableWebSQL=1,contextIsolation=no'); webview.setAttribute('partition', '${sqlPartition}'); webview.setAttribute('nodeIntegration', 'on'); document.body.appendChild(webview); webview.addEventListener('dom-ready', () => resolve()); }); `); const [, childError] = await webviewResult; expect(childError).to.equal(securityError); }); it('child webContents can use websql when the embedder has allowed websql', async () => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webviewTag: true, session: sqlSession, contextIsolation: false } }); w.webContents.loadURL(origin); const [, error] = await once(ipcMain, 'web-sql-response'); expect(error).to.be.null(); const webviewResult = once(ipcMain, 'web-sql-response'); await w.webContents.executeJavaScript(` new Promise((resolve, reject) => { const webview = new WebView(); webview.setAttribute('src', '${origin}'); webview.setAttribute('webpreferences', 'enableWebSQL=1,contextIsolation=no'); webview.setAttribute('partition', '${sqlPartition}'); webview.setAttribute('nodeIntegration', 'on'); document.body.appendChild(webview); webview.addEventListener('dom-ready', () => resolve()); }); `); const [, childError] = await webviewResult; expect(childError).to.be.null(); }); }); describe('DOM storage quota increase', () => { ['localStorage', 'sessionStorage'].forEach((storageName) => { it(`allows saving at least 40MiB in ${storageName}`, async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); // Although JavaScript strings use UTF-16, the underlying // storage provider may encode strings differently, muddling the // translation between character and byte counts. However, // a string of 40 * 2^20 characters will require at least 40MiB // and presumably no more than 80MiB, a size guaranteed to // to exceed the original 10MiB quota yet stay within the // new 100MiB quota. // Note that both the key name and value affect the total size. const testKeyName = '_electronDOMStorageQuotaIncreasedTest'; const length = 40 * Math.pow(2, 20) - testKeyName.length; await w.webContents.executeJavaScript(` ${storageName}.setItem(${JSON.stringify(testKeyName)}, 'X'.repeat(${length})); `); // Wait at least one turn of the event loop to help avoid false positives // Although not entirely necessary, the previous version of this test case // failed to detect a real problem (perhaps related to DOM storage data caching) // wherein calling `getItem` immediately after `setItem` would appear to work // but then later (e.g. next tick) it would not. await setTimeout(1); try { const storedLength = await w.webContents.executeJavaScript(`${storageName}.getItem(${JSON.stringify(testKeyName)}).length`); expect(storedLength).to.equal(length); } finally { await w.webContents.executeJavaScript(`${storageName}.removeItem(${JSON.stringify(testKeyName)});`); } }); it(`throws when attempting to use more than 128MiB in ${storageName}`, async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); await expect((async () => { const testKeyName = '_electronDOMStorageQuotaStillEnforcedTest'; const length = 128 * Math.pow(2, 20) - testKeyName.length; try { await w.webContents.executeJavaScript(` ${storageName}.setItem(${JSON.stringify(testKeyName)}, 'X'.repeat(${length})); `); } finally { await w.webContents.executeJavaScript(`${storageName}.removeItem(${JSON.stringify(testKeyName)});`); } })()).to.eventually.be.rejected(); }); }); }); describe('persistent storage', () => { it('can be requested', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); const grantedBytes = await w.webContents.executeJavaScript(`new Promise(resolve => { navigator.webkitPersistentStorage.requestQuota(1024 * 1024, resolve); })`); expect(grantedBytes).to.equal(1048576); }); }); }); ifdescribe(features.isPDFViewerEnabled())('PDF Viewer', () => { const pdfSource = url.format({ pathname: path.join(__dirname, 'fixtures', 'cat.pdf').replace(/\\/g, '/'), protocol: 'file', slashes: true }); it('successfully loads a PDF file', async () => { const w = new BrowserWindow({ show: false }); w.loadURL(pdfSource); await once(w.webContents, 'did-finish-load'); }); it('opens when loading a pdf resource as top level navigation', async () => { const w = new BrowserWindow({ show: false }); w.loadURL(pdfSource); const [, contents] = await once(app, 'web-contents-created') as [any, WebContents]; await once(contents, 'did-navigate'); expect(contents.getURL()).to.equal('chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/index.html'); }); it('opens when loading a pdf resource in a iframe', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(__dirname, 'fixtures', 'pages', 'pdf-in-iframe.html')); const [, contents] = await once(app, 'web-contents-created') as [any, WebContents]; await once(contents, 'did-navigate'); expect(contents.getURL()).to.equal('chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/index.html'); }); }); describe('window.history', () => { describe('window.history.pushState', () => { it('should push state after calling history.pushState() from the same url', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); // History should have current page by now. expect((w.webContents as any).length()).to.equal(1); const waitCommit = once(w.webContents, 'navigation-entry-committed'); w.webContents.executeJavaScript('window.history.pushState({}, "")'); await waitCommit; // Initial page + pushed state. expect((w.webContents as any).length()).to.equal(2); }); }); describe('window.history.back', () => { it('should not allow sandboxed iframe to modify main frame state', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('data:text/html,<iframe sandbox="allow-scripts"></iframe>'); await Promise.all([ once(w.webContents, 'navigation-entry-committed'), once(w.webContents, 'did-frame-navigate'), once(w.webContents, 'did-navigate') ]); w.webContents.executeJavaScript('window.history.pushState(1, "")'); await Promise.all([ once(w.webContents, 'navigation-entry-committed'), once(w.webContents, 'did-navigate-in-page') ]); (w.webContents as any).once('navigation-entry-committed', () => { expect.fail('Unexpected navigation-entry-committed'); }); w.webContents.once('did-navigate-in-page', () => { expect.fail('Unexpected did-navigate-in-page'); }); await w.webContents.mainFrame.frames[0].executeJavaScript('window.history.back()'); expect(await w.webContents.executeJavaScript('window.history.state')).to.equal(1); expect((w.webContents as any).getActiveIndex()).to.equal(1); }); }); }); describe('chrome://media-internals', () => { it('loads the page successfully', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('chrome://media-internals'); const pageExists = await w.webContents.executeJavaScript( "window.hasOwnProperty('chrome') && window.chrome.hasOwnProperty('send')" ); expect(pageExists).to.be.true(); }); }); describe('chrome://webrtc-internals', () => { it('loads the page successfully', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('chrome://webrtc-internals'); const pageExists = await w.webContents.executeJavaScript( "window.hasOwnProperty('chrome') && window.chrome.hasOwnProperty('send')" ); expect(pageExists).to.be.true(); }); }); describe('document.hasFocus', () => { it('has correct value when multiple windows are opened', async () => { const w1 = new BrowserWindow({ show: true }); const w2 = new BrowserWindow({ show: true }); const w3 = new BrowserWindow({ show: false }); await w1.loadFile(path.join(__dirname, 'fixtures', 'blank.html')); await w2.loadFile(path.join(__dirname, 'fixtures', 'blank.html')); await w3.loadFile(path.join(__dirname, 'fixtures', 'blank.html')); expect(webContents.getFocusedWebContents()?.id).to.equal(w2.webContents.id); let focus = false; focus = await w1.webContents.executeJavaScript( 'document.hasFocus()' ); expect(focus).to.be.false(); focus = await w2.webContents.executeJavaScript( 'document.hasFocus()' ); expect(focus).to.be.true(); focus = await w3.webContents.executeJavaScript( 'document.hasFocus()' ); expect(focus).to.be.false(); }); }); // https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation describe('navigator.connection', () => { it('returns the correct value', async () => { const w = new BrowserWindow({ show: false }); w.webContents.session.enableNetworkEmulation({ latency: 500, downloadThroughput: 6400, uploadThroughput: 6400 }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const rtt = await w.webContents.executeJavaScript('navigator.connection.rtt'); expect(rtt).to.be.a('number'); const downlink = await w.webContents.executeJavaScript('navigator.connection.downlink'); expect(downlink).to.be.a('number'); const effectiveTypes = ['slow-2g', '2g', '3g', '4g']; const effectiveType = await w.webContents.executeJavaScript('navigator.connection.effectiveType'); expect(effectiveTypes).to.include(effectiveType); }); }); describe('navigator.userAgentData', () => { // These tests are done on an http server because navigator.userAgentData // requires a secure context. let server: http.Server; let serverUrl: string; before(async () => { server = http.createServer((req, res) => { res.setHeader('Content-Type', 'text/html'); res.end(''); }); serverUrl = (await listen(server)).url; }); after(() => { server.close(); }); describe('is not empty', () => { it('by default', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(serverUrl); const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform'); expect(platform).not.to.be.empty(); }); it('when there is a session-wide UA override', async () => { const ses = session.fromPartition(`${Math.random()}`); ses.setUserAgent('foobar'); const w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await w.loadURL(serverUrl); const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform'); expect(platform).not.to.be.empty(); }); it('when there is a WebContents-specific UA override', async () => { const w = new BrowserWindow({ show: false }); w.webContents.setUserAgent('foo'); await w.loadURL(serverUrl); const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform'); expect(platform).not.to.be.empty(); }); it('when there is a WebContents-specific UA override at load time', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(serverUrl, { userAgent: 'foo' }); const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform'); expect(platform).not.to.be.empty(); }); }); describe('brand list', () => { it('contains chromium', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(serverUrl); const brands = await w.webContents.executeJavaScript('navigator.userAgentData.brands'); expect(brands.map((b: any) => b.brand)).to.include('Chromium'); }); }); }); describe('Badging API', () => { it('does not crash', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); await w.webContents.executeJavaScript('navigator.setAppBadge(42)'); await w.webContents.executeJavaScript('navigator.setAppBadge()'); await w.webContents.executeJavaScript('navigator.clearAppBadge()'); }); }); describe('navigator.webkitGetUserMedia', () => { it('calls its callbacks', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); await w.webContents.executeJavaScript(`new Promise((resolve) => { navigator.webkitGetUserMedia({ audio: true, video: false }, () => resolve(), () => resolve()); })`); }); }); describe('navigator.language', () => { it('should not be empty', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); expect(await w.webContents.executeJavaScript('navigator.language')).to.not.equal(''); }); }); describe('heap snapshot', () => { it('does not crash', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadURL('about:blank'); await w.webContents.executeJavaScript('process._linkedBinding(\'electron_common_v8_util\').takeHeapSnapshot()'); }); }); // This is intentionally disabled on arm macs: https://chromium-review.googlesource.com/c/chromium/src/+/4143761 ifdescribe(process.platform === 'darwin' && process.arch !== 'arm64')('webgl', () => { it('can be gotten as context in canvas', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const canWebglContextBeCreated = await w.webContents.executeJavaScript(` document.createElement('canvas').getContext('webgl') != null; `); expect(canWebglContextBeCreated).to.be.true(); }); }); describe('iframe', () => { it('does not have node integration', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const result = await w.webContents.executeJavaScript(` const iframe = document.createElement('iframe') iframe.src = './set-global.html'; document.body.appendChild(iframe); new Promise(resolve => iframe.onload = e => resolve(iframe.contentWindow.test)) `); expect(result).to.equal('undefined undefined undefined'); }); }); describe('websockets', () => { it('has user agent', async () => { const server = http.createServer(); const { port } = await listen(server); const wss = new ws.Server({ server: server }); const finished = new Promise<string | undefined>((resolve, reject) => { wss.on('error', reject); wss.on('connection', (ws, upgradeReq) => { resolve(upgradeReq.headers['user-agent']); }); }); const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.executeJavaScript(` new WebSocket('ws://127.0.0.1:${port}'); `); expect(await finished).to.include('Electron'); }); }); describe('fetch', () => { it('does not crash', async () => { const server = http.createServer((req, res) => { res.end('test'); }); defer(() => server.close()); const { port } = await listen(server); const w = new BrowserWindow({ show: false }); w.loadURL(`file://${fixturesPath}/pages/blank.html`); const x = await w.webContents.executeJavaScript(` fetch('http://127.0.0.1:${port}').then((res) => res.body.getReader()) .then((reader) => { return reader.read().then((r) => { reader.cancel(); return r.value; }); }) `); expect(x).to.deep.equal(new Uint8Array([116, 101, 115, 116])); }); }); describe('Promise', () => { before(() => { ipcMain.handle('ping', (e, arg) => arg); }); after(() => { ipcMain.removeHandler('ping'); }); itremote('resolves correctly in Node.js calls', async () => { await new Promise<void>((resolve, reject) => { class XElement extends HTMLElement {} customElements.define('x-element', XElement); setImmediate(() => { let called = false; Promise.resolve().then(() => { if (called) resolve(); else reject(new Error('wrong sequence')); }); document.createElement('x-element'); called = true; }); }); }); itremote('resolves correctly in Electron calls', async () => { await new Promise<void>((resolve, reject) => { class YElement extends HTMLElement {} customElements.define('y-element', YElement); require('electron').ipcRenderer.invoke('ping').then(() => { let called = false; Promise.resolve().then(() => { if (called) resolve(); else reject(new Error('wrong sequence')); }); document.createElement('y-element'); called = true; }); }); }); }); describe('synchronous prompts', () => { describe('window.alert(message, title)', () => { itremote('throws an exception when the arguments cannot be converted to strings', () => { expect(() => { window.alert({ toString: null }); }).to.throw('Cannot convert object to primitive value'); }); }); describe('window.confirm(message, title)', () => { itremote('throws an exception when the arguments cannot be converted to strings', () => { expect(() => { (window.confirm as any)({ toString: null }, 'title'); }).to.throw('Cannot convert object to primitive value'); }); }); }); describe('window.history', () => { describe('window.history.go(offset)', () => { itremote('throws an exception when the argument cannot be converted to a string', () => { expect(() => { (window.history.go as any)({ toString: null }); }).to.throw('Cannot convert object to primitive value'); }); }); }); describe('console functions', () => { itremote('should exist', () => { expect(console.log, 'log').to.be.a('function'); expect(console.error, 'error').to.be.a('function'); expect(console.warn, 'warn').to.be.a('function'); expect(console.info, 'info').to.be.a('function'); expect(console.debug, 'debug').to.be.a('function'); expect(console.trace, 'trace').to.be.a('function'); expect(console.time, 'time').to.be.a('function'); expect(console.timeEnd, 'timeEnd').to.be.a('function'); }); }); // FIXME(nornagon): this is broken on CI, it triggers: // [FATAL:speech_synthesis.mojom-shared.h(237)] The outgoing message will // trigger VALIDATION_ERROR_UNEXPECTED_NULL_POINTER at the receiving side // (null text in SpeechSynthesisUtterance struct). describe('SpeechSynthesis', () => { itremote('should emit lifecycle events', async () => { const sentence = `long sentence which will take at least a few seconds to utter so that it's possible to pause and resume before the end`; const utter = new SpeechSynthesisUtterance(sentence); // Create a dummy utterance so that speech synthesis state // is initialized for later calls. speechSynthesis.speak(new SpeechSynthesisUtterance()); speechSynthesis.cancel(); speechSynthesis.speak(utter); // paused state after speak() expect(speechSynthesis.paused).to.be.false(); await new Promise((resolve) => { utter.onstart = resolve; }); // paused state after start event expect(speechSynthesis.paused).to.be.false(); speechSynthesis.pause(); // paused state changes async, right before the pause event expect(speechSynthesis.paused).to.be.false(); await new Promise((resolve) => { utter.onpause = resolve; }); expect(speechSynthesis.paused).to.be.true(); speechSynthesis.resume(); await new Promise((resolve) => { utter.onresume = resolve; }); // paused state after resume event expect(speechSynthesis.paused).to.be.false(); await new Promise((resolve) => { utter.onend = resolve; }); }); }); }); describe('font fallback', () => { async function getRenderedFonts (html: string) { const w = new BrowserWindow({ show: false }); try { await w.loadURL(`data:text/html,${html}`); w.webContents.debugger.attach(); const sendCommand = (method: string, commandParams?: any) => w.webContents.debugger.sendCommand(method, commandParams); const { nodeId } = (await sendCommand('DOM.getDocument')).root.children[0]; await sendCommand('CSS.enable'); const { fonts } = await sendCommand('CSS.getPlatformFontsForNode', { nodeId }); return fonts; } finally { w.close(); } } it('should use Helvetica for sans-serif on Mac, and Arial on Windows and Linux', async () => { const html = '<body style="font-family: sans-serif">test</body>'; const fonts = await getRenderedFonts(html); expect(fonts).to.be.an('array'); expect(fonts).to.have.length(1); if (process.platform === 'win32') { expect(fonts[0].familyName).to.equal('Arial'); } else if (process.platform === 'darwin') { expect(fonts[0].familyName).to.equal('Helvetica'); } else if (process.platform === 'linux') { expect(fonts[0].familyName).to.equal('DejaVu Sans'); } // I think this depends on the distro? We don't specify a default. }); ifit(process.platform !== 'linux')('should fall back to Japanese font for sans-serif Japanese script', async function () { const html = ` <html lang="ja-JP"> <head> <meta charset="utf-8" /> </head> <body style="font-family: sans-serif">test 智史</body> </html> `; const fonts = await getRenderedFonts(html); expect(fonts).to.be.an('array'); expect(fonts).to.have.length(1); if (process.platform === 'win32') { expect(fonts[0].familyName).to.be.oneOf(['Meiryo', 'Yu Gothic']); } else if (process.platform === 'darwin') { expect(fonts[0].familyName).to.equal('Hiragino Kaku Gothic ProN'); } }); }); describe('iframe using HTML fullscreen API while window is OS-fullscreened', () => { const fullscreenChildHtml = promisify(fs.readFile)( path.join(fixturesPath, 'pages', 'fullscreen-oopif.html') ); let w: BrowserWindow; let server: http.Server; let crossSiteUrl: string; beforeEach(async () => { server = http.createServer(async (_req, res) => { res.writeHead(200, { 'Content-Type': 'text/html' }); res.write(await fullscreenChildHtml); res.end(); }); const serverUrl = (await listen(server)).url; crossSiteUrl = serverUrl.replace('127.0.0.1', 'localhost'); w = new BrowserWindow({ show: true, fullscreen: true, webPreferences: { nodeIntegration: true, nodeIntegrationInSubFrames: true, contextIsolation: false } }); }); afterEach(async () => { await closeAllWindows(); (w as any) = null; server.close(); }); ifit(process.platform !== 'darwin')('can fullscreen from out-of-process iframes (non-macOS)', async () => { const fullscreenChange = once(ipcMain, 'fullscreenChange'); const html = `<iframe style="width: 0" frameborder=0 src="${crossSiteUrl}" allowfullscreen></iframe>`; w.loadURL(`data:text/html,${html}`); await fullscreenChange; const fullscreenWidth = await w.webContents.executeJavaScript( "document.querySelector('iframe').offsetWidth" ); expect(fullscreenWidth > 0).to.be.true(); await w.webContents.executeJavaScript( "document.querySelector('iframe').contentWindow.postMessage('exitFullscreen', '*')" ); await setTimeout(500); const width = await w.webContents.executeJavaScript( "document.querySelector('iframe').offsetWidth" ); expect(width).to.equal(0); }); ifit(process.platform === 'darwin')('can fullscreen from out-of-process iframes (macOS)', async () => { await once(w, 'enter-full-screen'); const fullscreenChange = once(ipcMain, 'fullscreenChange'); const html = `<iframe style="width: 0" frameborder=0 src="${crossSiteUrl}" allowfullscreen></iframe>`; w.loadURL(`data:text/html,${html}`); await fullscreenChange; const fullscreenWidth = await w.webContents.executeJavaScript( "document.querySelector('iframe').offsetWidth" ); expect(fullscreenWidth > 0).to.be.true(); await w.webContents.executeJavaScript( "document.querySelector('iframe').contentWindow.postMessage('exitFullscreen', '*')" ); await once(w.webContents, 'leave-html-full-screen'); const width = await w.webContents.executeJavaScript( "document.querySelector('iframe').offsetWidth" ); expect(width).to.equal(0); w.setFullScreen(false); await once(w, 'leave-full-screen'); }); // TODO(jkleinsc) fix this flaky test on WOA ifit(process.platform !== 'win32' || process.arch !== 'arm64')('can fullscreen from in-process iframes', async () => { if (process.platform === 'darwin') await once(w, 'enter-full-screen'); const fullscreenChange = once(ipcMain, 'fullscreenChange'); w.loadFile(path.join(fixturesPath, 'pages', 'fullscreen-ipif.html')); await fullscreenChange; const fullscreenWidth = await w.webContents.executeJavaScript( "document.querySelector('iframe').offsetWidth" ); expect(fullscreenWidth > 0).to.true(); await w.webContents.executeJavaScript('document.exitFullscreen()'); const width = await w.webContents.executeJavaScript( "document.querySelector('iframe').offsetWidth" ); expect(width).to.equal(0); }); }); describe('navigator.serial', () => { let w: BrowserWindow; before(async () => { w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); }); const getPorts: any = () => { return w.webContents.executeJavaScript(` navigator.serial.requestPort().then(port => port.toString()).catch(err => err.toString()); `, true); }; const notFoundError = 'NotFoundError: Failed to execute \'requestPort\' on \'Serial\': No port selected by the user.'; after(closeAllWindows); afterEach(() => { session.defaultSession.setPermissionCheckHandler(null); session.defaultSession.removeAllListeners('select-serial-port'); }); it('does not return a port if select-serial-port event is not defined', async () => { w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); const port = await getPorts(); expect(port).to.equal(notFoundError); }); it('does not return a port when permission denied', async () => { w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => { callback(portList[0].portId); }); session.defaultSession.setPermissionCheckHandler(() => false); const port = await getPorts(); expect(port).to.equal(notFoundError); }); it('does not crash when select-serial-port is called with an invalid port', async () => { w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => { callback('i-do-not-exist'); }); const port = await getPorts(); expect(port).to.equal(notFoundError); }); it('returns a port when select-serial-port event is defined', async () => { let havePorts = false; w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => { if (portList.length > 0) { havePorts = true; callback(portList[0].portId); } else { callback(''); } }); const port = await getPorts(); if (havePorts) { expect(port).to.equal('[object SerialPort]'); } else { expect(port).to.equal(notFoundError); } }); it('navigator.serial.getPorts() returns values', async () => { let havePorts = false; w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => { if (portList.length > 0) { havePorts = true; callback(portList[0].portId); } else { callback(''); } }); await getPorts(); if (havePorts) { const grantedPorts = await w.webContents.executeJavaScript('navigator.serial.getPorts()'); expect(grantedPorts).to.not.be.empty(); } }); it('supports port.forget()', async () => { let forgottenPortFromEvent = {}; let havePorts = false; w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => { if (portList.length > 0) { havePorts = true; callback(portList[0].portId); } else { callback(''); } }); w.webContents.session.on('serial-port-revoked', (event, details) => { forgottenPortFromEvent = details.port; }); await getPorts(); if (havePorts) { const grantedPorts = await w.webContents.executeJavaScript('navigator.serial.getPorts()'); if (grantedPorts.length > 0) { const forgottenPort = await w.webContents.executeJavaScript(` navigator.serial.getPorts().then(async(ports) => { const portInfo = await ports[0].getInfo(); await ports[0].forget(); if (portInfo.usbVendorId && portInfo.usbProductId) { return { vendorId: '' + portInfo.usbVendorId, productId: '' + portInfo.usbProductId } } else { return {}; } }) `); const grantedPorts2 = await w.webContents.executeJavaScript('navigator.serial.getPorts()'); expect(grantedPorts2.length).to.be.lessThan(grantedPorts.length); if (forgottenPort.vendorId && forgottenPort.productId) { expect(forgottenPortFromEvent).to.include(forgottenPort); } } } }); }); describe('window.getScreenDetails', () => { let w: BrowserWindow; before(async () => { w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); }); after(closeAllWindows); afterEach(() => { session.defaultSession.setPermissionRequestHandler(null); }); const getScreenDetails: any = () => { return w.webContents.executeJavaScript('window.getScreenDetails().then(data => data.screens).catch(err => err.message)', true); }; it('returns screens when a PermissionRequestHandler is not defined', async () => { const screens = await getScreenDetails(); expect(screens).to.not.equal('Read permission denied.'); }); it('returns an error when permission denied', async () => { session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => { if (permission === 'window-management') { callback(false); } else { callback(true); } }); const screens = await getScreenDetails(); expect(screens).to.equal('Permission denied.'); }); it('returns screens when permission is granted', async () => { session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => { if (permission === 'window-management') { callback(true); } else { callback(false); } }); const screens = await getScreenDetails(); expect(screens).to.not.equal('Permission denied.'); }); }); describe('navigator.clipboard.read', () => { let w: BrowserWindow; before(async () => { w = new BrowserWindow(); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); }); const readClipboard: any = () => { return w.webContents.executeJavaScript(` navigator.clipboard.read().then(clipboard => clipboard.toString()).catch(err => err.message); `, true); }; after(closeAllWindows); afterEach(() => { session.defaultSession.setPermissionRequestHandler(null); }); it('returns clipboard contents when a PermissionRequestHandler is not defined', async () => { const clipboard = await readClipboard(); expect(clipboard).to.not.equal('Read permission denied.'); }); it('returns an error when permission denied', async () => { session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => { if (permission === 'clipboard-read') { callback(false); } else { callback(true); } }); const clipboard = await readClipboard(); expect(clipboard).to.equal('Read permission denied.'); }); it('returns clipboard contents when permission is granted', async () => { session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => { if (permission === 'clipboard-read') { callback(true); } else { callback(false); } }); const clipboard = await readClipboard(); expect(clipboard).to.not.equal('Read permission denied.'); }); }); describe('navigator.clipboard.write', () => { let w: BrowserWindow; before(async () => { w = new BrowserWindow(); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); }); const writeClipboard: any = () => { return w.webContents.executeJavaScript(` navigator.clipboard.writeText('Hello World!').catch(err => err.message); `, true); }; after(closeAllWindows); afterEach(() => { session.defaultSession.setPermissionRequestHandler(null); }); it('returns clipboard contents when a PermissionRequestHandler is not defined', async () => { const clipboard = await writeClipboard(); expect(clipboard).to.not.equal('Write permission denied.'); }); it('returns an error when permission denied', async () => { session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => { if (permission === 'clipboard-sanitized-write') { callback(false); } else { callback(true); } }); const clipboard = await writeClipboard(); expect(clipboard).to.equal('Write permission denied.'); }); it('returns clipboard contents when permission is granted', async () => { session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => { if (permission === 'clipboard-sanitized-write') { callback(true); } else { callback(false); } }); const clipboard = await writeClipboard(); expect(clipboard).to.not.equal('Write permission denied.'); }); }); ifdescribe((process.platform !== 'linux' || app.isUnityRunning()))('navigator.setAppBadge/clearAppBadge', () => { let w: BrowserWindow; const expectedBadgeCount = 42; const fireAppBadgeAction: any = (action: string, value: any) => { return w.webContents.executeJavaScript(` navigator.${action}AppBadge(${value}).then(() => 'success').catch(err => err.message)`); }; // For some reason on macOS changing the badge count doesn't happen right away, so wait // until it changes. async function waitForBadgeCount (value: number) { let badgeCount = app.getBadgeCount(); while (badgeCount !== value) { await setTimeout(10); badgeCount = app.getBadgeCount(); } return badgeCount; } describe('in the renderer', () => { before(async () => { w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); }); after(() => { app.badgeCount = 0; closeAllWindows(); }); it('setAppBadge can set a numerical value', async () => { const result = await fireAppBadgeAction('set', expectedBadgeCount); expect(result).to.equal('success'); expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount); }); it('setAppBadge can set an empty(dot) value', async () => { const result = await fireAppBadgeAction('set'); expect(result).to.equal('success'); expect(waitForBadgeCount(0)).to.eventually.equal(0); }); it('clearAppBadge can clear a value', async () => { let result = await fireAppBadgeAction('set', expectedBadgeCount); expect(result).to.equal('success'); expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount); result = await fireAppBadgeAction('clear'); expect(result).to.equal('success'); expect(waitForBadgeCount(0)).to.eventually.equal(0); }); }); describe('in a service worker', () => { beforeEach(async () => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, partition: 'sw-file-scheme-spec', contextIsolation: false } }); }); afterEach(() => { app.badgeCount = 0; closeAllWindows(); }); it('setAppBadge can be called in a ServiceWorker', (done) => { w.webContents.on('ipc-message', (event, channel, message) => { if (channel === 'reload') { w.webContents.reload(); } else if (channel === 'error') { done(message); } else if (channel === 'response') { expect(message).to.equal('SUCCESS setting app badge'); expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount); session.fromPartition('sw-file-scheme-spec').clearStorageData({ storages: ['serviceworkers'] }).then(() => done()); } }); w.webContents.on('render-process-gone', () => done(new Error('WebContents crashed.'))); w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'badge-index.html'), { search: '?setBadge' }); }); it('clearAppBadge can be called in a ServiceWorker', (done) => { w.webContents.on('ipc-message', (event, channel, message) => { if (channel === 'reload') { w.webContents.reload(); } else if (channel === 'setAppBadge') { expect(message).to.equal('SUCCESS setting app badge'); expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount); } else if (channel === 'error') { done(message); } else if (channel === 'response') { expect(message).to.equal('SUCCESS clearing app badge'); expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount); session.fromPartition('sw-file-scheme-spec').clearStorageData({ storages: ['serviceworkers'] }).then(() => done()); } }); w.webContents.on('render-process-gone', () => done(new Error('WebContents crashed.'))); w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'badge-index.html'), { search: '?clearBadge' }); }); }); }); describe('navigator.bluetooth', () => { let w: BrowserWindow; before(async () => { w = new BrowserWindow({ show: false, webPreferences: { enableBlinkFeatures: 'WebBluetooth' } }); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); }); after(closeAllWindows); it('can request bluetooth devices', async () => { const bluetooth = await w.webContents.executeJavaScript(` navigator.bluetooth.requestDevice({ acceptAllDevices: true}).then(device => "Found a device!").catch(err => err.message);`, true); expect(bluetooth).to.be.oneOf(['Found a device!', 'Bluetooth adapter not available.', 'User cancelled the requestDevice() chooser.']); }); }); describe('navigator.hid', () => { let w: BrowserWindow; let server: http.Server; let serverUrl: string; before(async () => { w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); server = http.createServer((req, res) => { res.setHeader('Content-Type', 'text/html'); res.end('<body>'); }); serverUrl = (await listen(server)).url; }); const requestDevices: any = () => { return w.webContents.executeJavaScript(` navigator.hid.requestDevice({filters: []}).then(device => device.toString()).catch(err => err.toString()); `, true); }; after(() => { server.close(); closeAllWindows(); }); afterEach(() => { session.defaultSession.setPermissionCheckHandler(null); session.defaultSession.setDevicePermissionHandler(null); session.defaultSession.removeAllListeners('select-hid-device'); }); it('does not return a device if select-hid-device event is not defined', async () => { w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); const device = await requestDevices(); expect(device).to.equal(''); }); it('does not return a device when permission denied', async () => { let selectFired = false; w.webContents.session.on('select-hid-device', (event, details, callback) => { selectFired = true; callback(); }); session.defaultSession.setPermissionCheckHandler(() => false); const device = await requestDevices(); expect(selectFired).to.be.false(); expect(device).to.equal(''); }); it('returns a device when select-hid-device event is defined', async () => { let haveDevices = false; let selectFired = false; w.webContents.session.on('select-hid-device', (event, details, callback) => { expect(details.frame).to.have.property('frameTreeNodeId').that.is.a('number'); selectFired = true; if (details.deviceList.length > 0) { haveDevices = true; callback(details.deviceList[0].deviceId); } else { callback(); } }); const device = await requestDevices(); expect(selectFired).to.be.true(); if (haveDevices) { expect(device).to.contain('[object HIDDevice]'); } else { expect(device).to.equal(''); } if (haveDevices) { // Verify that navigation will clear device permissions const grantedDevices = await w.webContents.executeJavaScript('navigator.hid.getDevices()'); expect(grantedDevices).to.not.be.empty(); w.loadURL(serverUrl); const [,,,,, frameProcessId, frameRoutingId] = await once(w.webContents, 'did-frame-navigate'); const frame = webFrameMain.fromId(frameProcessId, frameRoutingId); expect(!!frame).to.be.true(); if (frame) { const grantedDevicesOnNewPage = await frame.executeJavaScript('navigator.hid.getDevices()'); expect(grantedDevicesOnNewPage).to.be.empty(); } } }); it('returns a device when DevicePermissionHandler is defined', async () => { let haveDevices = false; let selectFired = false; let gotDevicePerms = false; w.webContents.session.on('select-hid-device', (event, details, callback) => { selectFired = true; if (details.deviceList.length > 0) { const foundDevice = details.deviceList.find((device) => { if (device.name && device.name !== '' && device.serialNumber && device.serialNumber !== '') { haveDevices = true; return true; } }); if (foundDevice) { callback(foundDevice.deviceId); return; } } callback(); }); session.defaultSession.setDevicePermissionHandler(() => { gotDevicePerms = true; return true; }); await w.webContents.executeJavaScript('navigator.hid.getDevices();', true); const device = await requestDevices(); expect(selectFired).to.be.true(); if (haveDevices) { expect(device).to.contain('[object HIDDevice]'); expect(gotDevicePerms).to.be.true(); } else { expect(device).to.equal(''); } }); it('excludes a device when a exclusionFilter is specified', async () => { const exclusionFilters = <any>[]; let haveDevices = false; let checkForExcludedDevice = false; w.webContents.session.on('select-hid-device', (event, details, callback) => { if (details.deviceList.length > 0) { details.deviceList.find((device) => { if (device.name && device.name !== '' && device.serialNumber && device.serialNumber !== '') { if (checkForExcludedDevice) { const compareDevice = { vendorId: device.vendorId, productId: device.productId }; expect(compareDevice).to.not.equal(exclusionFilters[0], 'excluded device should not be returned'); } else { haveDevices = true; exclusionFilters.push({ vendorId: device.vendorId, productId: device.productId }); return true; } } }); } callback(); }); await requestDevices(); if (haveDevices) { // We have devices to exclude, so check if exclusionFilters work checkForExcludedDevice = true; await w.webContents.executeJavaScript(` navigator.hid.requestDevice({filters: [], exclusionFilters: ${JSON.stringify(exclusionFilters)}}).then(device => device.toString()).catch(err => err.toString()); `, true); } }); it('supports device.forget()', async () => { let deletedDeviceFromEvent; let haveDevices = false; w.webContents.session.on('select-hid-device', (event, details, callback) => { if (details.deviceList.length > 0) { haveDevices = true; callback(details.deviceList[0].deviceId); } else { callback(); } }); w.webContents.session.on('hid-device-revoked', (event, details) => { deletedDeviceFromEvent = details.device; }); await requestDevices(); if (haveDevices) { const grantedDevices = await w.webContents.executeJavaScript('navigator.hid.getDevices()'); if (grantedDevices.length > 0) { const deletedDevice = await w.webContents.executeJavaScript(` navigator.hid.getDevices().then(devices => { devices[0].forget(); return { vendorId: devices[0].vendorId, productId: devices[0].productId, name: devices[0].productName } }) `); const grantedDevices2 = await w.webContents.executeJavaScript('navigator.hid.getDevices()'); expect(grantedDevices2.length).to.be.lessThan(grantedDevices.length); if (deletedDevice.name !== '' && deletedDevice.productId && deletedDevice.vendorId) { expect(deletedDeviceFromEvent).to.include(deletedDevice); } } } }); }); describe('navigator.usb', () => { let w: BrowserWindow; let server: http.Server; let serverUrl: string; before(async () => { w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); server = http.createServer((req, res) => { res.setHeader('Content-Type', 'text/html'); res.end('<body>'); }); serverUrl = (await listen(server)).url; }); const requestDevices: any = () => { return w.webContents.executeJavaScript(` navigator.usb.requestDevice({filters: []}).then(device => device.toString()).catch(err => err.toString()); `, true); }; const notFoundError = 'NotFoundError: Failed to execute \'requestDevice\' on \'USB\': No device selected.'; after(() => { server.close(); closeAllWindows(); }); afterEach(() => { session.defaultSession.setPermissionCheckHandler(null); session.defaultSession.setDevicePermissionHandler(null); session.defaultSession.removeAllListeners('select-usb-device'); }); it('does not return a device if select-usb-device event is not defined', async () => { w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); const device = await requestDevices(); expect(device).to.equal(notFoundError); }); it('does not return a device when permission denied', async () => { let selectFired = false; w.webContents.session.on('select-usb-device', (event, details, callback) => { selectFired = true; callback(); }); session.defaultSession.setPermissionCheckHandler(() => false); const device = await requestDevices(); expect(selectFired).to.be.false(); expect(device).to.equal(notFoundError); }); it('returns a device when select-usb-device event is defined', async () => { let haveDevices = false; let selectFired = false; w.webContents.session.on('select-usb-device', (event, details, callback) => { expect(details.frame).to.have.property('frameTreeNodeId').that.is.a('number'); selectFired = true; if (details.deviceList.length > 0) { haveDevices = true; callback(details.deviceList[0].deviceId); } else { callback(); } }); const device = await requestDevices(); expect(selectFired).to.be.true(); if (haveDevices) { expect(device).to.contain('[object USBDevice]'); } else { expect(device).to.equal(notFoundError); } if (haveDevices) { // Verify that navigation will clear device permissions const grantedDevices = await w.webContents.executeJavaScript('navigator.usb.getDevices()'); expect(grantedDevices).to.not.be.empty(); w.loadURL(serverUrl); const [,,,,, frameProcessId, frameRoutingId] = await once(w.webContents, 'did-frame-navigate'); const frame = webFrameMain.fromId(frameProcessId, frameRoutingId); expect(!!frame).to.be.true(); if (frame) { const grantedDevicesOnNewPage = await frame.executeJavaScript('navigator.usb.getDevices()'); expect(grantedDevicesOnNewPage).to.be.empty(); } } }); it('returns a device when DevicePermissionHandler is defined', async () => { let haveDevices = false; let selectFired = false; let gotDevicePerms = false; w.webContents.session.on('select-usb-device', (event, details, callback) => { selectFired = true; if (details.deviceList.length > 0) { const foundDevice = details.deviceList.find((device) => { if (device.productName && device.productName !== '' && device.serialNumber && device.serialNumber !== '') { haveDevices = true; return true; } }); if (foundDevice) { callback(foundDevice.deviceId); return; } } callback(); }); session.defaultSession.setDevicePermissionHandler(() => { gotDevicePerms = true; return true; }); await w.webContents.executeJavaScript('navigator.usb.getDevices();', true); const device = await requestDevices(); expect(selectFired).to.be.true(); if (haveDevices) { expect(device).to.contain('[object USBDevice]'); expect(gotDevicePerms).to.be.true(); } else { expect(device).to.equal(notFoundError); } }); it('supports device.forget()', async () => { let deletedDeviceFromEvent; let haveDevices = false; w.webContents.session.on('select-usb-device', (event, details, callback) => { if (details.deviceList.length > 0) { haveDevices = true; callback(details.deviceList[0].deviceId); } else { callback(); } }); w.webContents.session.on('usb-device-revoked', (event, details) => { deletedDeviceFromEvent = details.device; }); await requestDevices(); if (haveDevices) { const grantedDevices = await w.webContents.executeJavaScript('navigator.usb.getDevices()'); if (grantedDevices.length > 0) { const deletedDevice: Electron.USBDevice = await w.webContents.executeJavaScript(` navigator.usb.getDevices().then(devices => { devices[0].forget(); return { vendorId: devices[0].vendorId, productId: devices[0].productId, productName: devices[0].productName } }) `); const grantedDevices2 = await w.webContents.executeJavaScript('navigator.usb.getDevices()'); expect(grantedDevices2.length).to.be.lessThan(grantedDevices.length); if (deletedDevice.productName !== '' && deletedDevice.productId && deletedDevice.vendorId) { expect(deletedDeviceFromEvent).to.include(deletedDevice); } } } }); });
closed
electron/electron
https://github.com/electron/electron
39,535
[Bug]: cannot open chrome://gpu on Linux
### 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 25.5.0 ### What operating system are you using? Other Linux ### Operating System Version openSUSE Tumbleweed ### What arch are you using? x64 ### Last Known Working Electron version 24.7.1 ### Expected Behavior When running `electron chrome://gpu` a page of system diagnostics should open. ### Actual Behavior Instead a blank window opens and `(node:14996) electron: Failed to load URL: chrome://gpu/ with error: ERR_FAILED` gets printed to console. ### Testcase Gist URL _No response_ ### Additional Information This issue happens with electron 25 and 26. It was fine in electron 24.
https://github.com/electron/electron/issues/39535
https://github.com/electron/electron/pull/39556
c75e193a3e4683b1d55e56152dcef92e93d5eb56
95bf9d8adb33bc2aaf988977b18663f9a770ef77
2023-08-16T14:34:57Z
c++
2023-08-21T00:41:00Z
electron_paks.gni
import("//build/config/locales.gni") import("//electron/buildflags/buildflags.gni") import("//printing/buildflags/buildflags.gni") import("//tools/grit/repack.gni") import("//ui/base/ui_features.gni") # See: //chrome/chrome_paks.gni template("electron_repack_percent") { percent = invoker.percent repack(target_name) { forward_variables_from(invoker, [ "copy_data_to_bundle", "repack_whitelist", "visibility", ]) # All sources should also have deps for completeness. sources = [ "$root_gen_dir/components/components_resources_${percent}_percent.pak", "$root_gen_dir/third_party/blink/public/resources/blink_scaled_resources_${percent}_percent.pak", "$root_gen_dir/ui/resources/ui_resources_${percent}_percent.pak", ] deps = [ "//components/resources", "//third_party/blink/public:scaled_resources_${percent}_percent", "//ui/resources", ] if (defined(invoker.deps)) { deps += invoker.deps } if (toolkit_views) { sources += [ "$root_gen_dir/ui/views/resources/views_resources_${percent}_percent.pak" ] deps += [ "//ui/views/resources" ] } output = "${invoker.output_dir}/chrome_${percent}_percent.pak" } } template("electron_extra_paks") { repack(target_name) { forward_variables_from(invoker, [ "copy_data_to_bundle", "repack_whitelist", "visibility", ]) output = "${invoker.output_dir}/resources.pak" sources = [ "$root_gen_dir/chrome/accessibility_resources.pak", "$root_gen_dir/chrome/browser_resources.pak", "$root_gen_dir/chrome/common_resources.pak", "$root_gen_dir/chrome/dev_ui_browser_resources.pak", "$root_gen_dir/components/components_resources.pak", "$root_gen_dir/content/browser/resources/media/media_internals_resources.pak", "$root_gen_dir/content/browser/tracing/tracing_resources.pak", "$root_gen_dir/content/browser/webrtc/resources/webrtc_internals_resources.pak", "$root_gen_dir/content/content_resources.pak", "$root_gen_dir/mojo/public/js/mojo_bindings_resources.pak", "$root_gen_dir/net/net_resources.pak", "$root_gen_dir/third_party/blink/public/resources/blink_resources.pak", "$root_gen_dir/third_party/blink/public/resources/inspector_overlay_resources.pak", "$target_gen_dir/electron_resources.pak", ] deps = [ "//chrome/browser:dev_ui_browser_resources", "//chrome/browser:resources", "//chrome/browser/resources/accessibility:resources", "//chrome/common:resources", "//components/resources", "//content:content_resources", "//content/browser/resources/media:resources", "//content/browser/tracing:resources", "//content/browser/webrtc/resources", "//electron:resources", "//mojo/public/js:resources", "//net:net_resources", "//third_party/blink/public:devtools_inspector_resources", "//third_party/blink/public:resources", "//ui/resources", ] if (defined(invoker.deps)) { deps += invoker.deps } if (defined(invoker.additional_paks)) { sources += invoker.additional_paks } # New paks should be added here by default. sources += [ "$root_gen_dir/content/browser/devtools/devtools_resources.pak", "$root_gen_dir/ui/resources/webui_resources.pak", ] deps += [ "//content/browser/devtools:devtools_resources" ] if (enable_pdf_viewer) { sources += [ "$root_gen_dir/chrome/pdf_resources.pak" ] deps += [ "//chrome/browser/resources/pdf:resources" ] } if (enable_print_preview) { sources += [ "$root_gen_dir/chrome/print_preview_resources.pak" ] deps += [ "//chrome/browser/resources/print_preview:resources" ] } if (enable_electron_extensions) { sources += [ "$root_gen_dir/chrome/component_extension_resources.pak", "$root_gen_dir/extensions/extensions_renderer_resources.pak", "$root_gen_dir/extensions/extensions_resources.pak", ] deps += [ "//chrome/browser/resources:component_extension_resources", "//extensions:extensions_resources", ] } } } template("electron_paks") { electron_repack_percent("${target_name}_100_percent") { percent = "100" forward_variables_from(invoker, [ "copy_data_to_bundle", "deps", "output_dir", "repack_whitelist", "visibility", ]) } if (enable_hidpi) { electron_repack_percent("${target_name}_200_percent") { percent = "200" forward_variables_from(invoker, [ "copy_data_to_bundle", "deps", "output_dir", "repack_whitelist", "visibility", ]) } } electron_extra_paks("${target_name}_extra") { forward_variables_from(invoker, [ "copy_data_to_bundle", "deps", "output_dir", "repack_whitelist", "visibility", ]) if (defined(invoker.additional_extra_paks)) { additional_paks = invoker.additional_extra_paks } } repack_locales("${target_name}_locales") { forward_variables_from(invoker, [ "copy_data_to_bundle", "deps", "visibility", ]) if (defined(invoker.locale_whitelist)) { repack_whitelist = invoker.locale_whitelist } else if (defined(invoker.repack_whitelist)) { repack_whitelist = invoker.repack_whitelist } source_patterns = [ "${root_gen_dir}/chrome/chromium_strings_", "${root_gen_dir}/chrome/locale_settings_", "${root_gen_dir}/chrome/platform_locale_settings_", "${root_gen_dir}/chrome/generated_resources_", "${root_gen_dir}/components/strings/components_locale_settings_", "${root_gen_dir}/components/strings/components_strings_", "${root_gen_dir}/device/bluetooth/strings/bluetooth_strings_", "${root_gen_dir}/extensions/strings/extensions_strings_", "${root_gen_dir}/services/strings/services_strings_", "${root_gen_dir}/third_party/blink/public/strings/blink_accessibility_strings_", "${root_gen_dir}/third_party/blink/public/strings/blink_strings_", "${root_gen_dir}/ui/strings/app_locale_settings_", "${root_gen_dir}/ui/strings/ax_strings_", "${root_gen_dir}/ui/strings/ui_strings_", ] deps = [ "//chrome/app:chromium_strings", "//chrome/app:generated_resources", "//chrome/app/resources:locale_settings", "//chrome/app/resources:platform_locale_settings", "//components/strings:components_locale_settings", "//components/strings:components_strings", "//device/bluetooth/strings", "//extensions/strings", "//services/strings", "//third_party/blink/public/strings", "//third_party/blink/public/strings:accessibility_strings", "//ui/strings:app_locale_settings", "//ui/strings:ax_strings", "//ui/strings:ui_strings", ] input_locales = platform_pak_locales output_dir = "${invoker.output_dir}/locales" if (is_mac) { output_locales = locales_as_apple_outputs } else { output_locales = platform_pak_locales } } group(target_name) { forward_variables_from(invoker, [ "deps" ]) public_deps = [ ":${target_name}_100_percent", ":${target_name}_extra", ":${target_name}_locales", ] if (enable_hidpi) { public_deps += [ ":${target_name}_200_percent" ] } if (defined(invoker.public_deps)) { public_deps += invoker.public_deps } } }
closed
electron/electron
https://github.com/electron/electron
39,535
[Bug]: cannot open chrome://gpu on Linux
### 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 25.5.0 ### What operating system are you using? Other Linux ### Operating System Version openSUSE Tumbleweed ### What arch are you using? x64 ### Last Known Working Electron version 24.7.1 ### Expected Behavior When running `electron chrome://gpu` a page of system diagnostics should open. ### Actual Behavior Instead a blank window opens and `(node:14996) electron: Failed to load URL: chrome://gpu/ with error: ERR_FAILED` gets printed to console. ### Testcase Gist URL _No response_ ### Additional Information This issue happens with electron 25 and 26. It was fine in electron 24.
https://github.com/electron/electron/issues/39535
https://github.com/electron/electron/pull/39556
c75e193a3e4683b1d55e56152dcef92e93d5eb56
95bf9d8adb33bc2aaf988977b18663f9a770ef77
2023-08-16T14:34:57Z
c++
2023-08-21T00:41:00Z
spec/chromium-spec.ts
import { expect } from 'chai'; import { BrowserWindow, WebContents, webFrameMain, session, ipcMain, app, protocol, webContents } from 'electron/main'; import { closeAllWindows } from './lib/window-helpers'; import * as https from 'node:https'; import * as http from 'node:http'; import * as path from 'node:path'; import * as fs from 'node:fs'; import * as url from 'node:url'; import * as ChildProcess from 'node:child_process'; import { EventEmitter, once } from 'node:events'; import { promisify } from 'node:util'; import { ifit, ifdescribe, defer, itremote, listen } from './lib/spec-helpers'; import { PipeTransport } from './pipe-transport'; import * as ws from 'ws'; import { setTimeout } from 'node:timers/promises'; const features = process._linkedBinding('electron_common_features'); const fixturesPath = path.resolve(__dirname, 'fixtures'); const certPath = path.join(fixturesPath, 'certificates'); describe('reporting api', () => { it('sends a report for an intervention', async () => { const reporting = new EventEmitter(); // The Reporting API only works on https with valid certs. To dodge having // to set up a trusted certificate, hack the validator. session.defaultSession.setCertificateVerifyProc((req, cb) => { cb(0); }); const options = { key: fs.readFileSync(path.join(certPath, 'server.key')), cert: fs.readFileSync(path.join(certPath, 'server.pem')), ca: [ fs.readFileSync(path.join(certPath, 'rootCA.pem')), fs.readFileSync(path.join(certPath, 'intermediateCA.pem')) ], requestCert: true, rejectUnauthorized: false }; const server = https.createServer(options, (req, res) => { if (req.url?.endsWith('report')) { let data = ''; req.on('data', (d) => { data += d.toString('utf-8'); }); req.on('end', () => { reporting.emit('report', JSON.parse(data)); }); } const { port } = server.address() as any; res.setHeader('Reporting-Endpoints', `default="https://localhost:${port}/report"`); res.setHeader('Content-Type', 'text/html'); res.end('<script>window.navigator.vibrate(1)</script>'); }); await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve)); const bw = new BrowserWindow({ show: false }); try { const reportGenerated = once(reporting, 'report'); await bw.loadURL(`https://localhost:${(server.address() as any).port}/a`); const [reports] = await reportGenerated; expect(reports).to.be.an('array').with.lengthOf(1); const { type, url, body } = reports[0]; expect(type).to.equal('intervention'); expect(url).to.equal(url); expect(body.id).to.equal('NavigatorVibrate'); expect(body.message).to.match(/Blocked call to navigator.vibrate because user hasn't tapped on the frame or any embedded frame yet/); } finally { bw.destroy(); server.close(); } }); }); describe('window.postMessage', () => { afterEach(async () => { await closeAllWindows(); }); it('sets the source and origin correctly', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadURL(`file://${fixturesPath}/pages/window-open-postMessage-driver.html`); const [, message] = await once(ipcMain, 'complete'); expect(message.data).to.equal('testing'); expect(message.origin).to.equal('file://'); expect(message.sourceEqualsOpener).to.equal(true); expect(message.eventOrigin).to.equal('file://'); }); }); describe('focus handling', () => { let webviewContents: WebContents; let w: BrowserWindow; beforeEach(async () => { w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true, webviewTag: true, contextIsolation: false } }); const webviewReady = once(w.webContents, 'did-attach-webview') as Promise<[any, WebContents]>; await w.loadFile(path.join(fixturesPath, 'pages', 'tab-focus-loop-elements.html')); const [, wvContents] = await webviewReady; webviewContents = wvContents; await once(webviewContents, 'did-finish-load'); w.focus(); }); afterEach(() => { webviewContents = null as unknown as WebContents; w.destroy(); w = null as unknown as BrowserWindow; }); const expectFocusChange = async () => { const [, focusedElementId] = await once(ipcMain, 'focus-changed'); return focusedElementId; }; describe('a TAB press', () => { const tabPressEvent: any = { type: 'keyDown', keyCode: 'Tab' }; it('moves focus to the next focusable item', async () => { let focusChange = expectFocusChange(); w.webContents.sendInputEvent(tabPressEvent); let focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-element-1', `should start focused in element-1, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); w.webContents.sendInputEvent(tabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-element-2', `focus should've moved to element-2, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); w.webContents.sendInputEvent(tabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-wv-element-1', `focus should've moved to the webview's element-1, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); webviewContents.sendInputEvent(tabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-wv-element-2', `focus should've moved to the webview's element-2, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); webviewContents.sendInputEvent(tabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-element-3', `focus should've moved to element-3, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); w.webContents.sendInputEvent(tabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-element-1', `focus should've looped back to element-1, it's instead in ${focusedElementId}`); }); }); describe('a SHIFT + TAB press', () => { const shiftTabPressEvent: any = { type: 'keyDown', modifiers: ['Shift'], keyCode: 'Tab' }; it('moves focus to the previous focusable item', async () => { let focusChange = expectFocusChange(); w.webContents.sendInputEvent(shiftTabPressEvent); let focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-element-3', `should start focused in element-3, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); w.webContents.sendInputEvent(shiftTabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-wv-element-2', `focus should've moved to the webview's element-2, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); webviewContents.sendInputEvent(shiftTabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-wv-element-1', `focus should've moved to the webview's element-1, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); webviewContents.sendInputEvent(shiftTabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-element-2', `focus should've moved to element-2, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); w.webContents.sendInputEvent(shiftTabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-element-1', `focus should've moved to element-1, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); w.webContents.sendInputEvent(shiftTabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-element-3', `focus should've looped back to element-3, it's instead in ${focusedElementId}`); }); }); }); describe('web security', () => { afterEach(closeAllWindows); let server: http.Server; let serverUrl: string; before(async () => { server = http.createServer((req, res) => { res.setHeader('Content-Type', 'text/html'); res.end('<body>'); }); serverUrl = (await listen(server)).url; }); after(() => { server.close(); }); it('engages CORB when web security is not disabled', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: true, nodeIntegration: true, contextIsolation: false } }); const p = once(ipcMain, 'success'); await w.loadURL(`data:text/html,<script> const s = document.createElement('script') s.src = "${serverUrl}" // The script will load successfully but its body will be emptied out // by CORB, so we don't expect a syntax error. s.onload = () => { require('electron').ipcRenderer.send('success') } document.documentElement.appendChild(s) </script>`); await p; }); it('bypasses CORB when web security is disabled', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: false, nodeIntegration: true, contextIsolation: false } }); const p = once(ipcMain, 'success'); await w.loadURL(`data:text/html, <script> window.onerror = (e) => { require('electron').ipcRenderer.send('success', e) } </script> <script src="${serverUrl}"></script>`); await p; }); it('engages CORS when web security is not disabled', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: true, nodeIntegration: true, contextIsolation: false } }); const p = once(ipcMain, 'response'); await w.loadURL(`data:text/html,<script> (async function() { try { await fetch('${serverUrl}'); require('electron').ipcRenderer.send('response', 'passed'); } catch { require('electron').ipcRenderer.send('response', 'failed'); } })(); </script>`); const [, response] = await p; expect(response).to.equal('failed'); }); it('bypasses CORS when web security is disabled', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: false, nodeIntegration: true, contextIsolation: false } }); const p = once(ipcMain, 'response'); await w.loadURL(`data:text/html,<script> (async function() { try { await fetch('${serverUrl}'); require('electron').ipcRenderer.send('response', 'passed'); } catch { require('electron').ipcRenderer.send('response', 'failed'); } })(); </script>`); const [, response] = await p; expect(response).to.equal('passed'); }); describe('accessing file://', () => { async function loadFile (w: BrowserWindow) { const thisFile = url.format({ pathname: __filename.replace(/\\/g, '/'), protocol: 'file', slashes: true }); await w.loadURL(`data:text/html,<script> function loadFile() { return new Promise((resolve) => { fetch('${thisFile}').then( () => resolve('loaded'), () => resolve('failed') ) }); } </script>`); return await w.webContents.executeJavaScript('loadFile()'); } it('is forbidden when web security is enabled', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: true } }); const result = await loadFile(w); expect(result).to.equal('failed'); }); it('is allowed when web security is disabled', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: false } }); const result = await loadFile(w); expect(result).to.equal('loaded'); }); }); describe('wasm-eval csp', () => { async function loadWasm (csp: string) { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, enableBlinkFeatures: 'WebAssemblyCSP' } }); await w.loadURL(`data:text/html,<head> <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-inline' ${csp}"> </head> <script> function loadWasm() { const wasmBin = new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0]) return new Promise((resolve) => { WebAssembly.instantiate(wasmBin).then(() => { resolve('loaded') }).catch((error) => { resolve(error.message) }) }); } </script>`); return await w.webContents.executeJavaScript('loadWasm()'); } it('wasm codegen is disallowed by default', async () => { const r = await loadWasm(''); expect(r).to.equal('WebAssembly.instantiate(): Refused to compile or instantiate WebAssembly module because \'unsafe-eval\' is not an allowed source of script in the following Content Security Policy directive: "script-src \'self\' \'unsafe-inline\'"'); }); it('wasm codegen is allowed with "wasm-unsafe-eval" csp', async () => { const r = await loadWasm("'wasm-unsafe-eval'"); expect(r).to.equal('loaded'); }); }); describe('csp', () => { for (const sandbox of [true, false]) { describe(`when sandbox: ${sandbox}`, () => { for (const contextIsolation of [true, false]) { describe(`when contextIsolation: ${contextIsolation}`, () => { it('prevents eval from running in an inline script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox, contextIsolation } }); w.loadURL(`data:text/html,<head> <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-inline'"> </head> <script> try { // We use console.log here because it is easier than making a // preload script, and the behavior under test changes when // contextIsolation: false console.log(eval('true')) } catch (e) { console.log(e.message) } </script>`); const [,, message] = await once(w.webContents, 'console-message'); expect(message).to.match(/Refused to evaluate a string/); }); it('does not prevent eval from running in an inline script when there is no csp', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox, contextIsolation } }); w.loadURL(`data:text/html, <script> try { // We use console.log here because it is easier than making a // preload script, and the behavior under test changes when // contextIsolation: false console.log(eval('true')) } catch (e) { console.log(e.message) } </script>`); const [,, message] = await once(w.webContents, 'console-message'); expect(message).to.equal('true'); }); it('prevents eval from running in executeJavaScript', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox, contextIsolation } }); w.loadURL('data:text/html,<head><meta http-equiv="Content-Security-Policy" content="default-src \'self\'; script-src \'self\' \'unsafe-inline\'"></meta></head>'); await expect(w.webContents.executeJavaScript('eval("true")')).to.be.rejected(); }); it('does not prevent eval from running in executeJavaScript when there is no csp', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox, contextIsolation } }); w.loadURL('data:text/html,'); expect(await w.webContents.executeJavaScript('eval("true")')).to.be.true(); }); }); } }); } }); it('does not crash when multiple WebContent are created with web security disabled', () => { const options = { show: false, webPreferences: { webSecurity: false } }; const w1 = new BrowserWindow(options); w1.loadURL(serverUrl); const w2 = new BrowserWindow(options); w2.loadURL(serverUrl); }); }); describe('command line switches', () => { let appProcess: ChildProcess.ChildProcessWithoutNullStreams | undefined; afterEach(() => { if (appProcess && !appProcess.killed) { appProcess.kill(); appProcess = undefined; } }); describe('--lang switch', () => { const currentLocale = app.getLocale(); const currentSystemLocale = app.getSystemLocale(); const currentPreferredLanguages = JSON.stringify(app.getPreferredSystemLanguages()); const testLocale = async (locale: string, result: string, printEnv: boolean = false) => { const appPath = path.join(fixturesPath, 'api', 'locale-check'); const args = [appPath, `--set-lang=${locale}`]; if (printEnv) { args.push('--print-env'); } appProcess = ChildProcess.spawn(process.execPath, args); let output = ''; appProcess.stdout.on('data', (data) => { output += data; }); let stderr = ''; appProcess.stderr.on('data', (data) => { stderr += data; }); const [code, signal] = await once(appProcess, 'exit'); if (code !== 0) { throw new Error(`Process exited with code "${code}" signal "${signal}" output "${output}" stderr "${stderr}"`); } output = output.replace(/(\r\n|\n|\r)/gm, ''); expect(output).to.equal(result); }; it('should set the locale', async () => testLocale('fr', `fr|${currentSystemLocale}|${currentPreferredLanguages}`)); it('should set the locale with country code', async () => testLocale('zh-CN', `zh-CN|${currentSystemLocale}|${currentPreferredLanguages}`)); it('should not set an invalid locale', async () => testLocale('asdfkl', `${currentLocale}|${currentSystemLocale}|${currentPreferredLanguages}`)); const lcAll = String(process.env.LC_ALL); ifit(process.platform === 'linux')('current process has a valid LC_ALL env', async () => { // The LC_ALL env should not be set to DOM locale string. expect(lcAll).to.not.equal(app.getLocale()); }); ifit(process.platform === 'linux')('should not change LC_ALL', async () => testLocale('fr', lcAll, true)); ifit(process.platform === 'linux')('should not change LC_ALL when setting invalid locale', async () => testLocale('asdfkl', lcAll, true)); ifit(process.platform === 'linux')('should not change LC_ALL when --lang is not set', async () => testLocale('', lcAll, true)); }); describe('--remote-debugging-pipe switch', () => { it('should expose CDP via pipe', async () => { const electronPath = process.execPath; appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-pipe'], { stdio: ['inherit', 'inherit', 'inherit', 'pipe', 'pipe'] }) as ChildProcess.ChildProcessWithoutNullStreams; const stdio = appProcess.stdio as unknown as [NodeJS.ReadableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.ReadableStream]; const pipe = new PipeTransport(stdio[3], stdio[4]); const versionPromise = new Promise(resolve => { pipe.onmessage = resolve; }); pipe.send({ id: 1, method: 'Browser.getVersion', params: {} }); const message = (await versionPromise) as any; expect(message.id).to.equal(1); expect(message.result.product).to.contain('Chrome'); expect(message.result.userAgent).to.contain('Electron'); }); it('should override --remote-debugging-port switch', async () => { const electronPath = process.execPath; appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-pipe', '--remote-debugging-port=0'], { stdio: ['inherit', 'inherit', 'pipe', 'pipe', 'pipe'] }) as ChildProcess.ChildProcessWithoutNullStreams; let stderr = ''; appProcess.stderr.on('data', (data: string) => { stderr += data; }); const stdio = appProcess.stdio as unknown as [NodeJS.ReadableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.ReadableStream]; const pipe = new PipeTransport(stdio[3], stdio[4]); const versionPromise = new Promise(resolve => { pipe.onmessage = resolve; }); pipe.send({ id: 1, method: 'Browser.getVersion', params: {} }); const message = (await versionPromise) as any; expect(message.id).to.equal(1); expect(stderr).to.not.include('DevTools listening on'); }); it('should shut down Electron upon Browser.close CDP command', async () => { const electronPath = process.execPath; appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-pipe'], { stdio: ['inherit', 'inherit', 'inherit', 'pipe', 'pipe'] }) as ChildProcess.ChildProcessWithoutNullStreams; const stdio = appProcess.stdio as unknown as [NodeJS.ReadableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.ReadableStream]; const pipe = new PipeTransport(stdio[3], stdio[4]); pipe.send({ id: 1, method: 'Browser.close', params: {} }); await once(appProcess, 'exit'); }); }); describe('--remote-debugging-port switch', () => { it('should display the discovery page', (done) => { const electronPath = process.execPath; let output = ''; appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-port=']); appProcess.stdout.on('data', (data) => { console.log(data); }); appProcess.stderr.on('data', (data) => { console.log(data); output += data; const m = /DevTools listening on ws:\/\/127.0.0.1:(\d+)\//.exec(output); if (m) { appProcess!.stderr.removeAllListeners('data'); const port = m[1]; http.get(`http://127.0.0.1:${port}`, (res) => { try { expect(res.statusCode).to.eql(200); expect(parseInt(res.headers['content-length']!)).to.be.greaterThan(0); done(); } catch (e) { done(e); } finally { res.destroy(); } }); } }); }); }); }); describe('chromium features', () => { afterEach(closeAllWindows); describe('accessing key names also used as Node.js module names', () => { it('does not crash', (done) => { const w = new BrowserWindow({ show: false }); w.webContents.once('did-finish-load', () => { done(); }); w.webContents.once('render-process-gone', () => done(new Error('WebContents crashed.'))); w.loadFile(path.join(fixturesPath, 'pages', 'external-string.html')); }); }); describe('first party sets', () => { const fps = [ 'https://fps-member1.glitch.me', 'https://fps-member2.glitch.me', 'https://fps-member3.glitch.me' ]; it('loads first party sets', async () => { const appPath = path.join(fixturesPath, 'api', 'first-party-sets', 'base'); const fpsProcess = ChildProcess.spawn(process.execPath, [appPath]); let output = ''; fpsProcess.stdout.on('data', data => { output += data; }); await once(fpsProcess, 'exit'); expect(output).to.include(fps.join(',')); }); it('loads sets from the command line', async () => { const appPath = path.join(fixturesPath, 'api', 'first-party-sets', 'command-line'); const args = [appPath, `--use-first-party-set=${fps}`]; const fpsProcess = ChildProcess.spawn(process.execPath, args); let output = ''; fpsProcess.stdout.on('data', data => { output += data; }); await once(fpsProcess, 'exit'); expect(output).to.include(fps.join(',')); }); }); describe('loading jquery', () => { it('does not crash', (done) => { const w = new BrowserWindow({ show: false }); w.webContents.once('did-finish-load', () => { done(); }); w.webContents.once('render-process-gone', () => done(new Error('WebContents crashed.'))); w.loadFile(path.join(__dirname, 'fixtures', 'pages', 'jquery.html')); }); }); describe('navigator.languages', () => { it('should return the system locale only', async () => { const appLocale = app.getLocale(); const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const languages = await w.webContents.executeJavaScript('navigator.languages'); expect(languages.length).to.be.greaterThan(0); expect(languages).to.contain(appLocale); }); }); describe('navigator.serviceWorker', () => { it('should register for file scheme', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, partition: 'sw-file-scheme-spec', contextIsolation: false } }); w.webContents.on('ipc-message', (event, channel, message) => { if (channel === 'reload') { w.webContents.reload(); } else if (channel === 'error') { done(message); } else if (channel === 'response') { expect(message).to.equal('Hello from serviceWorker!'); session.fromPartition('sw-file-scheme-spec').clearStorageData({ storages: ['serviceworkers'] }).then(() => done()); } }); w.webContents.on('render-process-gone', () => done(new Error('WebContents crashed.'))); w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'index.html')); }); it('should register for intercepted file scheme', (done) => { const customSession = session.fromPartition('intercept-file'); customSession.protocol.interceptBufferProtocol('file', (request, callback) => { let file = url.parse(request.url).pathname!; if (file[0] === '/' && process.platform === 'win32') file = file.slice(1); const content = fs.readFileSync(path.normalize(file)); const ext = path.extname(file); let type = 'text/html'; if (ext === '.js') type = 'application/javascript'; callback({ data: content, mimeType: type } as any); }); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, session: customSession, contextIsolation: false } }); w.webContents.on('ipc-message', (event, channel, message) => { if (channel === 'reload') { w.webContents.reload(); } else if (channel === 'error') { done(`unexpected error : ${message}`); } else if (channel === 'response') { expect(message).to.equal('Hello from serviceWorker!'); customSession.clearStorageData({ storages: ['serviceworkers'] }).then(() => { customSession.protocol.uninterceptProtocol('file'); done(); }); } }); w.webContents.on('render-process-gone', () => done(new Error('WebContents crashed.'))); w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'index.html')); }); it('should register for custom scheme', (done) => { const customSession = session.fromPartition('custom-scheme'); customSession.protocol.registerFileProtocol(serviceWorkerScheme, (request, callback) => { let file = url.parse(request.url).pathname!; if (file[0] === '/' && process.platform === 'win32') file = file.slice(1); callback({ path: path.normalize(file) } as any); }); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, session: customSession, contextIsolation: false } }); w.webContents.on('ipc-message', (event, channel, message) => { if (channel === 'reload') { w.webContents.reload(); } else if (channel === 'error') { done(`unexpected error : ${message}`); } else if (channel === 'response') { expect(message).to.equal('Hello from serviceWorker!'); customSession.clearStorageData({ storages: ['serviceworkers'] }).then(() => { customSession.protocol.uninterceptProtocol(serviceWorkerScheme); done(); }); } }); w.webContents.on('render-process-gone', () => done(new Error('WebContents crashed.'))); w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'custom-scheme-index.html')); }); it('should not allow nodeIntegrationInWorker', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, nodeIntegrationInWorker: true, partition: 'sw-file-scheme-worker-spec', contextIsolation: false } }); await w.loadURL(`file://${fixturesPath}/pages/service-worker/empty.html`); const data = await w.webContents.executeJavaScript(` navigator.serviceWorker.register('worker-no-node.js', { scope: './' }).then(() => navigator.serviceWorker.ready) new Promise((resolve) => { navigator.serviceWorker.onmessage = event => resolve(event.data); }); `); expect(data).to.equal('undefined undefined undefined undefined'); }); }); describe('navigator.geolocation', () => { ifit(features.isFakeLocationProviderEnabled())('returns error when permission is denied', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, partition: 'geolocation-spec', contextIsolation: false } }); const message = once(w.webContents, 'ipc-message'); w.webContents.session.setPermissionRequestHandler((wc, permission, callback) => { if (permission === 'geolocation') { callback(false); } else { callback(true); } }); w.loadFile(path.join(fixturesPath, 'pages', 'geolocation', 'index.html')); const [, channel] = await message; expect(channel).to.equal('success', 'unexpected response from geolocation api'); }); ifit(!features.isFakeLocationProviderEnabled())('returns position when permission is granted', async () => { const w = new BrowserWindow({ show: false, webPreferences: { partition: 'geolocation-spec' } }); w.webContents.session.setPermissionRequestHandler((_wc, _permission, callback) => { callback(true); }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const position = await w.webContents.executeJavaScript(`new Promise((resolve, reject) => navigator.geolocation.getCurrentPosition( x => resolve({coords: x.coords, timestamp: x.timestamp}), err => reject(new Error(err.message))))`); expect(position).to.have.property('coords'); expect(position).to.have.property('timestamp'); }); }); describe('web workers', () => { let appProcess: ChildProcess.ChildProcessWithoutNullStreams | undefined; afterEach(() => { if (appProcess && !appProcess.killed) { appProcess.kill(); appProcess = undefined; } }); it('Worker with nodeIntegrationInWorker has access to self.module.paths', async () => { const appPath = path.join(__dirname, 'fixtures', 'apps', 'self-module-paths'); appProcess = ChildProcess.spawn(process.execPath, [appPath]); const [code] = await once(appProcess, 'exit'); expect(code).to.equal(0); }); it('Worker can work', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const data = await w.webContents.executeJavaScript(` const worker = new Worker('../workers/worker.js'); const message = 'ping'; const eventPromise = new Promise((resolve) => { worker.onmessage = resolve; }); worker.postMessage(message); eventPromise.then(t => t.data) `); expect(data).to.equal('ping'); }); it('Worker has no node integration by default', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const data = await w.webContents.executeJavaScript(` const worker = new Worker('../workers/worker_node.js'); new Promise((resolve) => { worker.onmessage = e => resolve(e.data); }) `); expect(data).to.equal('undefined undefined undefined undefined'); }); it('Worker has node integration with nodeIntegrationInWorker', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, nodeIntegrationInWorker: true, contextIsolation: false } }); w.loadURL(`file://${fixturesPath}/pages/worker.html`); const [, data] = await once(ipcMain, 'worker-result'); expect(data).to.equal('object function object function'); }); describe('SharedWorker', () => { it('can work', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const data = await w.webContents.executeJavaScript(` const worker = new SharedWorker('../workers/shared_worker.js'); const message = 'ping'; const eventPromise = new Promise((resolve) => { worker.port.onmessage = e => resolve(e.data); }); worker.port.postMessage(message); eventPromise `); expect(data).to.equal('ping'); }); it('has no node integration by default', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const data = await w.webContents.executeJavaScript(` const worker = new SharedWorker('../workers/shared_worker_node.js'); new Promise((resolve) => { worker.port.onmessage = e => resolve(e.data); }) `); expect(data).to.equal('undefined undefined undefined undefined'); }); it('does not have node integration with nodeIntegrationInWorker', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, nodeIntegrationInWorker: true, contextIsolation: false } }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const data = await w.webContents.executeJavaScript(` const worker = new SharedWorker('../workers/shared_worker_node.js'); new Promise((resolve) => { worker.port.onmessage = e => resolve(e.data); }) `); expect(data).to.equal('undefined undefined undefined undefined'); }); }); }); describe('form submit', () => { let server: http.Server; let serverUrl: string; before(async () => { server = http.createServer((req, res) => { let body = ''; req.on('data', (chunk) => { body += chunk; }); res.setHeader('Content-Type', 'application/json'); req.on('end', () => { res.end(`body:${body}`); }); }); serverUrl = (await listen(server)).url; }); after(async () => { server.close(); await closeAllWindows(); }); [true, false].forEach((isSandboxEnabled) => describe(`sandbox=${isSandboxEnabled}`, () => { it('posts data in the same window', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: isSandboxEnabled } }); await w.loadFile(path.join(fixturesPath, 'pages', 'form-with-data.html')); const loadPromise = once(w.webContents, 'did-finish-load'); w.webContents.executeJavaScript(` const form = document.querySelector('form') form.action = '${serverUrl}'; form.submit(); `); await loadPromise; const res = await w.webContents.executeJavaScript('document.body.innerText'); expect(res).to.equal('body:greeting=hello'); }); it('posts data to a new window with target=_blank', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: isSandboxEnabled } }); await w.loadFile(path.join(fixturesPath, 'pages', 'form-with-data.html')); const windowCreatedPromise = once(app, 'browser-window-created') as Promise<[any, BrowserWindow]>; w.webContents.executeJavaScript(` const form = document.querySelector('form') form.action = '${serverUrl}'; form.target = '_blank'; form.submit(); `); const [, newWin] = await windowCreatedPromise; const res = await newWin.webContents.executeJavaScript('document.body.innerText'); expect(res).to.equal('body:greeting=hello'); }); }) ); }); describe('window.open', () => { for (const show of [true, false]) { it(`shows the child regardless of parent visibility when parent {show=${show}}`, async () => { const w = new BrowserWindow({ show }); // toggle visibility if (show) { w.hide(); } else { w.show(); } defer(() => { w.close(); }); const promise = once(app, 'browser-window-created') as Promise<[any, BrowserWindow]>; w.loadFile(path.join(fixturesPath, 'pages', 'window-open.html')); const [, newWindow] = await promise; expect(newWindow.isVisible()).to.equal(true); }); } // FIXME(zcbenz): This test is making the spec runner hang on exit on Windows. ifit(process.platform !== 'win32')('disables node integration when it is disabled on the parent window', async () => { const windowUrl = url.pathToFileURL(path.join(fixturesPath, 'pages', 'window-opener-no-node-integration.html')); windowUrl.searchParams.set('p', `${fixturesPath}/pages/window-opener-node.html`); const w = new BrowserWindow({ show: false }); w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); const { eventData } = await w.webContents.executeJavaScript(`(async () => { const message = new Promise(resolve => window.addEventListener('message', resolve, {once: true})); const b = window.open(${JSON.stringify(windowUrl)}, '', 'show=false') const e = await message b.close(); return { eventData: e.data } })()`); expect(eventData.isProcessGlobalUndefined).to.be.true(); }); it('disables node integration when it is disabled on the parent window for chrome devtools URLs', async () => { // NB. webSecurity is disabled because native window.open() is not // allowed to load devtools:// URLs. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webSecurity: false } }); w.loadURL('about:blank'); w.webContents.executeJavaScript(` { b = window.open('devtools://devtools/bundled/inspector.html', '', 'nodeIntegration=no,show=no'); null } `); const [, contents] = await once(app, 'web-contents-created') as [any, WebContents]; const typeofProcessGlobal = await contents.executeJavaScript('typeof process'); expect(typeofProcessGlobal).to.equal('undefined'); }); it('can disable node integration when it is enabled on the parent window', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); w.loadURL('about:blank'); w.webContents.executeJavaScript(` { b = window.open('about:blank', '', 'nodeIntegration=no,show=no'); null } `); const [, contents] = await once(app, 'web-contents-created') as [any, WebContents]; const typeofProcessGlobal = await contents.executeJavaScript('typeof process'); expect(typeofProcessGlobal).to.equal('undefined'); }); // TODO(jkleinsc) fix this flaky test on WOA ifit(process.platform !== 'win32' || process.arch !== 'arm64')('disables JavaScript when it is disabled on the parent window', async () => { const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true } }); w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); const windowUrl = require('node:url').format({ pathname: `${fixturesPath}/pages/window-no-javascript.html`, protocol: 'file', slashes: true }); w.webContents.executeJavaScript(` { b = window.open(${JSON.stringify(windowUrl)}, '', 'javascript=no,show=no'); null } `); const [, contents] = await once(app, 'web-contents-created') as [any, WebContents]; await once(contents, 'did-finish-load'); // Click link on page contents.sendInputEvent({ type: 'mouseDown', clickCount: 1, x: 1, y: 1 }); contents.sendInputEvent({ type: 'mouseUp', clickCount: 1, x: 1, y: 1 }); const [, window] = await once(app, 'browser-window-created') as [any, BrowserWindow]; const preferences = window.webContents.getLastWebPreferences(); expect(preferences!.javascript).to.be.false(); }); it('defines a window.location getter', async () => { let targetURL: string; if (process.platform === 'win32') { targetURL = `file:///${fixturesPath.replace(/\\/g, '/')}/pages/base-page.html`; } else { targetURL = `file://${fixturesPath}/pages/base-page.html`; } const w = new BrowserWindow({ show: false }); w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); w.webContents.executeJavaScript(`{ b = window.open(${JSON.stringify(targetURL)}); null }`); const [, window] = await once(app, 'browser-window-created') as [any, BrowserWindow]; await once(window.webContents, 'did-finish-load'); expect(await w.webContents.executeJavaScript('b.location.href')).to.equal(targetURL); }); it('defines a window.location setter', async () => { const w = new BrowserWindow({ show: false }); w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); w.webContents.executeJavaScript('{ b = window.open("about:blank"); null }'); const [, { webContents }] = await once(app, 'browser-window-created') as [any, BrowserWindow]; await once(webContents, 'did-finish-load'); // When it loads, redirect w.webContents.executeJavaScript(`{ b.location = ${JSON.stringify(`file://${fixturesPath}/pages/base-page.html`)}; null }`); await once(webContents, 'did-finish-load'); }); it('defines a window.location.href setter', async () => { const w = new BrowserWindow({ show: false }); w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); w.webContents.executeJavaScript('{ b = window.open("about:blank"); null }'); const [, { webContents }] = await once(app, 'browser-window-created') as [any, BrowserWindow]; await once(webContents, 'did-finish-load'); // When it loads, redirect w.webContents.executeJavaScript(`{ b.location.href = ${JSON.stringify(`file://${fixturesPath}/pages/base-page.html`)}; null }`); await once(webContents, 'did-finish-load'); }); it('open a blank page when no URL is specified', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.executeJavaScript('{ b = window.open(); null }'); const [, { webContents }] = await once(app, 'browser-window-created') as [any, BrowserWindow]; await once(webContents, 'did-finish-load'); expect(await w.webContents.executeJavaScript('b.location.href')).to.equal('about:blank'); }); it('open a blank page when an empty URL is specified', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.executeJavaScript('{ b = window.open(\'\'); null }'); const [, { webContents }] = await once(app, 'browser-window-created') as [any, BrowserWindow]; await once(webContents, 'did-finish-load'); expect(await w.webContents.executeJavaScript('b.location.href')).to.equal('about:blank'); }); it('does not throw an exception when the frameName is a built-in object property', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.executeJavaScript('{ b = window.open(\'\', \'__proto__\'); null }'); const frameName = await new Promise((resolve) => { w.webContents.setWindowOpenHandler(details => { setImmediate(() => resolve(details.frameName)); return { action: 'allow' }; }); }); expect(frameName).to.equal('__proto__'); }); it('works when used in conjunction with the vm module', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); await w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); const { contextObject } = await w.webContents.executeJavaScript(`(async () => { const vm = require('node:vm'); const contextObject = { count: 1, type: 'gecko' }; window.open(''); vm.runInNewContext('count += 1; type = "chameleon";', contextObject); return { contextObject }; })()`); expect(contextObject).to.deep.equal({ count: 2, type: 'chameleon' }); }); // FIXME(nornagon): I'm not sure this ... ever was correct? xit('inherit options of parent window', async () => { const w = new BrowserWindow({ show: false, width: 123, height: 456 }); w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); const url = `file://${fixturesPath}/pages/window-open-size.html`; const { width, height, eventData } = await w.webContents.executeJavaScript(`(async () => { const message = new Promise(resolve => window.addEventListener('message', resolve, {once: true})); const b = window.open(${JSON.stringify(url)}, '', 'show=false') const e = await message b.close(); const width = outerWidth; const height = outerHeight; return { width, height, eventData: e.data } })()`); expect(eventData).to.equal(`size: ${width} ${height}`); expect(eventData).to.equal('size: 123 456'); }); it('does not override child options', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); const windowUrl = `file://${fixturesPath}/pages/window-open-size.html`; const { eventData } = await w.webContents.executeJavaScript(`(async () => { const message = new Promise(resolve => window.addEventListener('message', resolve, {once: true})); const b = window.open(${JSON.stringify(windowUrl)}, '', 'show=no,width=350,height=450') const e = await message b.close(); return { eventData: e.data } })()`); expect(eventData).to.equal('size: 350 450'); }); it('loads preload script after setting opener to null', async () => { const w = new BrowserWindow({ show: false }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: path.join(fixturesPath, 'module', 'preload.js') } } })); w.loadURL('about:blank'); w.webContents.executeJavaScript('window.child = window.open(); child.opener = null'); const [, { webContents }] = await once(app, 'browser-window-created'); const [,, message] = await once(webContents, 'console-message'); expect(message).to.equal('{"require":"function","module":"undefined","process":"object","Buffer":"function"}'); }); it('disables the <webview> tag when it is disabled on the parent window', async () => { const windowUrl = url.pathToFileURL(path.join(fixturesPath, 'pages', 'window-opener-no-webview-tag.html')); windowUrl.searchParams.set('p', `${fixturesPath}/pages/window-opener-webview.html`); const w = new BrowserWindow({ show: false }); w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); const { eventData } = await w.webContents.executeJavaScript(`(async () => { const message = new Promise(resolve => window.addEventListener('message', resolve, {once: true})); const b = window.open(${JSON.stringify(windowUrl)}, '', 'webviewTag=no,contextIsolation=no,nodeIntegration=yes,show=no') const e = await message b.close(); return { eventData: e.data } })()`); expect(eventData.isWebViewGlobalUndefined).to.be.true(); }); it('throws an exception when the arguments cannot be converted to strings', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); await expect( w.webContents.executeJavaScript('window.open(\'\', { toString: null })') ).to.eventually.be.rejected(); await expect( w.webContents.executeJavaScript('window.open(\'\', \'\', { toString: 3 })') ).to.eventually.be.rejected(); }); it('does not throw an exception when the features include webPreferences', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); await expect( w.webContents.executeJavaScript('window.open(\'\', \'\', \'show=no,webPreferences=\'); null') ).to.eventually.be.fulfilled(); }); }); describe('window.opener', () => { it('is null for main window', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixturesPath, 'pages', 'window-opener.html')); const [, channel, opener] = await once(w.webContents, 'ipc-message'); expect(channel).to.equal('opener'); expect(opener).to.equal(null); }); it('is not null for window opened by window.open', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); const windowUrl = `file://${fixturesPath}/pages/window-opener.html`; const eventData = await w.webContents.executeJavaScript(` const b = window.open(${JSON.stringify(windowUrl)}, '', 'show=no'); new Promise(resolve => window.addEventListener('message', resolve, {once: true})).then(e => e.data); `); expect(eventData).to.equal('object'); }); }); describe('window.opener.postMessage', () => { it('sets source and origin correctly', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); const windowUrl = `file://${fixturesPath}/pages/window-opener-postMessage.html`; const { sourceIsChild, origin } = await w.webContents.executeJavaScript(` const b = window.open(${JSON.stringify(windowUrl)}, '', 'show=no'); new Promise(resolve => window.addEventListener('message', resolve, {once: true})).then(e => ({ sourceIsChild: e.source === b, origin: e.origin })); `); expect(sourceIsChild).to.be.true(); expect(origin).to.equal('file://'); }); it('supports windows opened from a <webview>', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } }); w.loadURL('about:blank'); const childWindowUrl = url.pathToFileURL(path.join(fixturesPath, 'pages', 'webview-opener-postMessage.html')); childWindowUrl.searchParams.set('p', `${fixturesPath}/pages/window-opener-postMessage.html`); const message = await w.webContents.executeJavaScript(` const webview = new WebView(); webview.allowpopups = true; webview.setAttribute('webpreferences', 'contextIsolation=no'); webview.src = ${JSON.stringify(childWindowUrl)} const consoleMessage = new Promise(resolve => webview.addEventListener('console-message', resolve, {once: true})); document.body.appendChild(webview); consoleMessage.then(e => e.message) `); expect(message).to.equal('message'); }); describe('targetOrigin argument', () => { let serverURL: string; let server: any; beforeEach(async () => { server = http.createServer((req, res) => { res.writeHead(200); const filePath = path.join(fixturesPath, 'pages', 'window-opener-targetOrigin.html'); res.end(fs.readFileSync(filePath, 'utf8')); }); serverURL = (await listen(server)).url; }); afterEach(() => { server.close(); }); it('delivers messages that match the origin', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); const data = await w.webContents.executeJavaScript(` window.open(${JSON.stringify(serverURL)}, '', 'show=no,contextIsolation=no,nodeIntegration=yes'); new Promise(resolve => window.addEventListener('message', resolve, {once: true})).then(e => e.data) `); expect(data).to.equal('deliver'); }); }); }); describe('IdleDetection', () => { afterEach(closeAllWindows); afterEach(() => { session.defaultSession.setPermissionCheckHandler(null); session.defaultSession.setPermissionRequestHandler(null); }); it('can grant a permission request', async () => { session.defaultSession.setPermissionRequestHandler( (_wc, permission, callback) => { callback(permission === 'idle-detection'); } ); const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'button.html')); const permission = await w.webContents.executeJavaScript(` new Promise((resolve, reject) => { const button = document.getElementById('button'); button.addEventListener("click", async () => { const permission = await IdleDetector.requestPermission(); resolve(permission); }); button.click(); }); `, true); expect(permission).to.eq('granted'); }); it('can deny a permission request', async () => { session.defaultSession.setPermissionRequestHandler( (_wc, permission, callback) => { callback(permission !== 'idle-detection'); } ); const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'button.html')); const permission = await w.webContents.executeJavaScript(` new Promise((resolve, reject) => { const button = document.getElementById('button'); button.addEventListener("click", async () => { const permission = await IdleDetector.requestPermission(); resolve(permission); }); button.click(); }); `, true); expect(permission).to.eq('denied'); }); it('can allow the IdleDetector to start', async () => { session.defaultSession.setPermissionCheckHandler((wc, permission) => { return permission === 'idle-detection'; }); const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); const result = await w.webContents.executeJavaScript(` const detector = new IdleDetector({ threshold: 60000 }); detector.start().then(() => { return 'success'; }).catch(e => e.message); `, true); expect(result).to.eq('success'); }); it('can prevent the IdleDetector from starting', async () => { session.defaultSession.setPermissionCheckHandler((wc, permission) => { return permission !== 'idle-detection'; }); const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); const result = await w.webContents.executeJavaScript(` const detector = new IdleDetector({ threshold: 60000 }); detector.start().then(() => { console.log('success') }).catch(e => e.message); `, true); expect(result).to.eq('Idle detection permission denied'); }); }); describe('navigator.mediaDevices', () => { afterEach(closeAllWindows); afterEach(() => { session.defaultSession.setPermissionCheckHandler(null); session.defaultSession.setPermissionRequestHandler(null); }); it('can return labels of enumerated devices', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); const labels = await w.webContents.executeJavaScript('navigator.mediaDevices.enumerateDevices().then(ds => ds.map(d => d.label))'); expect(labels.some((l: any) => l)).to.be.true(); }); it('does not return labels of enumerated devices when permission denied', async () => { session.defaultSession.setPermissionCheckHandler(() => false); const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); const labels = await w.webContents.executeJavaScript('navigator.mediaDevices.enumerateDevices().then(ds => ds.map(d => d.label))'); expect(labels.some((l: any) => l)).to.be.false(); }); it('returns the same device ids across reloads', async () => { const ses = session.fromPartition('persist:media-device-id'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, session: ses, contextIsolation: false } }); w.loadFile(path.join(fixturesPath, 'pages', 'media-id-reset.html')); const [, firstDeviceIds] = await once(ipcMain, 'deviceIds'); w.webContents.reload(); const [, secondDeviceIds] = await once(ipcMain, 'deviceIds'); expect(firstDeviceIds).to.deep.equal(secondDeviceIds); }); it('can return new device id when cookie storage is cleared', async () => { const ses = session.fromPartition('persist:media-device-id'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, session: ses, contextIsolation: false } }); w.loadFile(path.join(fixturesPath, 'pages', 'media-id-reset.html')); const [, firstDeviceIds] = await once(ipcMain, 'deviceIds'); await ses.clearStorageData({ storages: ['cookies'] }); w.webContents.reload(); const [, secondDeviceIds] = await once(ipcMain, 'deviceIds'); expect(firstDeviceIds).to.not.deep.equal(secondDeviceIds); }); it('provides a securityOrigin to the request handler', async () => { session.defaultSession.setPermissionRequestHandler( (wc, permission, callback, details) => { if (details.securityOrigin !== undefined) { callback(true); } else { callback(false); } } ); const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); const labels = await w.webContents.executeJavaScript(`navigator.mediaDevices.getUserMedia({ video: { mandatory: { chromeMediaSource: "desktop", minWidth: 1280, maxWidth: 1280, minHeight: 720, maxHeight: 720 } } }).then((stream) => stream.getVideoTracks())`); expect(labels.some((l: any) => l)).to.be.true(); }); it('fails with "not supported" for getDisplayMedia', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); const { ok, err } = await w.webContents.executeJavaScript('navigator.mediaDevices.getDisplayMedia({video: true}).then(s => ({ok: true}), e => ({ok: false, err: e.message}))', true); expect(ok).to.be.false(); expect(err).to.equal('Not supported'); }); }); describe('window.opener access', () => { const scheme = 'app'; const fileUrl = `file://${fixturesPath}/pages/window-opener-location.html`; const httpUrl1 = `${scheme}://origin1`; const httpUrl2 = `${scheme}://origin2`; const fileBlank = `file://${fixturesPath}/pages/blank.html`; const httpBlank = `${scheme}://origin1/blank`; const table = [ { parent: fileBlank, child: httpUrl1, nodeIntegration: false, openerAccessible: false }, { parent: fileBlank, child: httpUrl1, nodeIntegration: true, openerAccessible: false }, // {parent: httpBlank, child: fileUrl, nodeIntegration: false, openerAccessible: false}, // can't window.open() // {parent: httpBlank, child: fileUrl, nodeIntegration: true, openerAccessible: false}, // can't window.open() // NB. this is different from Chrome's behavior, which isolates file: urls from each other { parent: fileBlank, child: fileUrl, nodeIntegration: false, openerAccessible: true }, { parent: fileBlank, child: fileUrl, nodeIntegration: true, openerAccessible: true }, { parent: httpBlank, child: httpUrl1, nodeIntegration: false, openerAccessible: true }, { parent: httpBlank, child: httpUrl1, nodeIntegration: true, openerAccessible: true }, { parent: httpBlank, child: httpUrl2, nodeIntegration: false, openerAccessible: false }, { parent: httpBlank, child: httpUrl2, nodeIntegration: true, openerAccessible: false } ]; const s = (url: string) => url.startsWith('file') ? 'file://...' : url; before(() => { protocol.registerFileProtocol(scheme, (request, callback) => { if (request.url.includes('blank')) { callback(`${fixturesPath}/pages/blank.html`); } else { callback(`${fixturesPath}/pages/window-opener-location.html`); } }); }); after(() => { protocol.unregisterProtocol(scheme); }); afterEach(closeAllWindows); describe('when opened from main window', () => { for (const { parent, child, nodeIntegration, openerAccessible } of table) { for (const sandboxPopup of [false, true]) { const description = `when parent=${s(parent)} opens child=${s(child)} with nodeIntegration=${nodeIntegration} sandboxPopup=${sandboxPopup}, child should ${openerAccessible ? '' : 'not '}be able to access opener`; it(description, async () => { const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { sandbox: sandboxPopup } } })); await w.loadURL(parent); const childOpenerLocation = await w.webContents.executeJavaScript(`new Promise(resolve => { window.addEventListener('message', function f(e) { resolve(e.data) }) window.open(${JSON.stringify(child)}, "", "show=no,nodeIntegration=${nodeIntegration ? 'yes' : 'no'}") })`); if (openerAccessible) { expect(childOpenerLocation).to.be.a('string'); } else { expect(childOpenerLocation).to.be.null(); } }); } } }); describe('when opened from <webview>', () => { for (const { parent, child, nodeIntegration, openerAccessible } of table) { const description = `when parent=${s(parent)} opens child=${s(child)} with nodeIntegration=${nodeIntegration}, child should ${openerAccessible ? '' : 'not '}be able to access opener`; it(description, async () => { // This test involves three contexts: // 1. The root BrowserWindow in which the test is run, // 2. A <webview> belonging to the root window, // 3. A window opened by calling window.open() from within the <webview>. // We are testing whether context (3) can access context (2) under various conditions. // This is context (1), the base window for the test. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webviewTag: true, contextIsolation: false } }); await w.loadURL('about:blank'); const parentCode = `new Promise((resolve) => { // This is context (3), a child window of the WebView. const child = window.open(${JSON.stringify(child)}, "", "show=no,contextIsolation=no,nodeIntegration=yes") window.addEventListener("message", e => { resolve(e.data) }) })`; const childOpenerLocation = await w.webContents.executeJavaScript(`new Promise((resolve, reject) => { // This is context (2), a WebView which will call window.open() const webview = new WebView() webview.setAttribute('nodeintegration', '${nodeIntegration ? 'on' : 'off'}') webview.setAttribute('webpreferences', 'contextIsolation=no') webview.setAttribute('allowpopups', 'on') webview.src = ${JSON.stringify(parent + '?p=' + encodeURIComponent(child))} webview.addEventListener('dom-ready', async () => { webview.executeJavaScript(${JSON.stringify(parentCode)}).then(resolve, reject) }) document.body.appendChild(webview) })`); if (openerAccessible) { expect(childOpenerLocation).to.be.a('string'); } else { expect(childOpenerLocation).to.be.null(); } }); } }); }); describe('storage', () => { describe('custom non standard schemes', () => { const protocolName = 'storage'; let contents: WebContents; before(() => { protocol.registerFileProtocol(protocolName, (request, callback) => { const parsedUrl = url.parse(request.url); let filename; switch (parsedUrl.pathname) { case '/localStorage' : filename = 'local_storage.html'; break; case '/sessionStorage' : filename = 'session_storage.html'; break; case '/WebSQL' : filename = 'web_sql.html'; break; case '/indexedDB' : filename = 'indexed_db.html'; break; case '/cookie' : filename = 'cookie.html'; break; default : filename = ''; } callback({ path: `${fixturesPath}/pages/storage/${filename}` }); }); }); after(() => { protocol.unregisterProtocol(protocolName); }); beforeEach(() => { contents = (webContents as typeof ElectronInternal.WebContents).create({ nodeIntegration: true, contextIsolation: false }); }); afterEach(() => { contents.destroy(); contents = null as any; }); it('cannot access localStorage', async () => { const response = once(ipcMain, 'local-storage-response'); contents.loadURL(protocolName + '://host/localStorage'); const [, error] = await response; expect(error).to.equal('Failed to read the \'localStorage\' property from \'Window\': Access is denied for this document.'); }); it('cannot access sessionStorage', async () => { const response = once(ipcMain, 'session-storage-response'); contents.loadURL(`${protocolName}://host/sessionStorage`); const [, error] = await response; expect(error).to.equal('Failed to read the \'sessionStorage\' property from \'Window\': Access is denied for this document.'); }); it('cannot access WebSQL database', async () => { const response = once(ipcMain, 'web-sql-response'); contents.loadURL(`${protocolName}://host/WebSQL`); const [, error] = await response; expect(error).to.equal('Failed to execute \'openDatabase\' on \'Window\': Access to the WebDatabase API is denied in this context.'); }); it('cannot access indexedDB', async () => { const response = once(ipcMain, 'indexed-db-response'); contents.loadURL(`${protocolName}://host/indexedDB`); const [, error] = await response; expect(error).to.equal('Failed to execute \'open\' on \'IDBFactory\': access to the Indexed Database API is denied in this context.'); }); it('cannot access cookie', async () => { const response = once(ipcMain, 'cookie-response'); contents.loadURL(`${protocolName}://host/cookie`); const [, error] = await response; expect(error).to.equal('Failed to set the \'cookie\' property on \'Document\': Access is denied for this document.'); }); }); describe('can be accessed', () => { let server: http.Server; let serverUrl: string; let serverCrossSiteUrl: string; before(async () => { server = http.createServer((req, res) => { const respond = () => { if (req.url === '/redirect-cross-site') { res.setHeader('Location', `${serverCrossSiteUrl}/redirected`); res.statusCode = 302; res.end(); } else if (req.url === '/redirected') { res.end('<html><script>window.localStorage</script></html>'); } else { res.end(); } }; setTimeout().then(respond); }); serverUrl = (await listen(server)).url; serverCrossSiteUrl = serverUrl.replace('127.0.0.1', 'localhost'); }); after(() => { server.close(); server = null as any; }); afterEach(closeAllWindows); const testLocalStorageAfterXSiteRedirect = (testTitle: string, extraPreferences = {}) => { it(testTitle, async () => { const w = new BrowserWindow({ show: false, ...extraPreferences }); let redirected = false; w.webContents.on('render-process-gone', () => { expect.fail('renderer crashed / was killed'); }); w.webContents.on('did-redirect-navigation', (event, url) => { expect(url).to.equal(`${serverCrossSiteUrl}/redirected`); redirected = true; }); await w.loadURL(`${serverUrl}/redirect-cross-site`); expect(redirected).to.be.true('didnt redirect'); }); }; testLocalStorageAfterXSiteRedirect('after a cross-site redirect'); testLocalStorageAfterXSiteRedirect('after a cross-site redirect in sandbox mode', { sandbox: true }); }); describe('enableWebSQL webpreference', () => { const origin = `${standardScheme}://fake-host`; const filePath = path.join(fixturesPath, 'pages', 'storage', 'web_sql.html'); const sqlPartition = 'web-sql-preference-test'; const sqlSession = session.fromPartition(sqlPartition); const securityError = 'An attempt was made to break through the security policy of the user agent.'; let contents: WebContents, w: BrowserWindow; before(() => { sqlSession.protocol.registerFileProtocol(standardScheme, (request, callback) => { callback({ path: filePath }); }); }); after(() => { sqlSession.protocol.unregisterProtocol(standardScheme); }); afterEach(async () => { if (contents) { contents.destroy(); contents = null as any; } await closeAllWindows(); (w as any) = null; }); it('default value allows websql', async () => { contents = (webContents as typeof ElectronInternal.WebContents).create({ session: sqlSession, nodeIntegration: true, contextIsolation: false }); contents.loadURL(origin); const [, error] = await once(ipcMain, 'web-sql-response'); expect(error).to.be.null(); }); it('when set to false can disallow websql', async () => { contents = (webContents as typeof ElectronInternal.WebContents).create({ session: sqlSession, nodeIntegration: true, enableWebSQL: false, contextIsolation: false }); contents.loadURL(origin); const [, error] = await once(ipcMain, 'web-sql-response'); expect(error).to.equal(securityError); }); it('when set to false does not disable indexedDB', async () => { contents = (webContents as typeof ElectronInternal.WebContents).create({ session: sqlSession, nodeIntegration: true, enableWebSQL: false, contextIsolation: false }); contents.loadURL(origin); const [, error] = await once(ipcMain, 'web-sql-response'); expect(error).to.equal(securityError); const dbName = 'random'; const result = await contents.executeJavaScript(` new Promise((resolve, reject) => { try { let req = window.indexedDB.open('${dbName}'); req.onsuccess = (event) => { let db = req.result; resolve(db.name); } req.onerror = (event) => { resolve(event.target.code); } } catch (e) { resolve(e.message); } }); `); expect(result).to.equal(dbName); }); it('child webContents can override when the embedder has allowed websql', async () => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webviewTag: true, session: sqlSession, contextIsolation: false } }); w.webContents.loadURL(origin); const [, error] = await once(ipcMain, 'web-sql-response'); expect(error).to.be.null(); const webviewResult = once(ipcMain, 'web-sql-response'); await w.webContents.executeJavaScript(` new Promise((resolve, reject) => { const webview = new WebView(); webview.setAttribute('src', '${origin}'); webview.setAttribute('webpreferences', 'enableWebSQL=0,contextIsolation=no'); webview.setAttribute('partition', '${sqlPartition}'); webview.setAttribute('nodeIntegration', 'on'); document.body.appendChild(webview); webview.addEventListener('dom-ready', () => resolve()); }); `); const [, childError] = await webviewResult; expect(childError).to.equal(securityError); }); it('child webContents cannot override when the embedder has disallowed websql', async () => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, enableWebSQL: false, webviewTag: true, session: sqlSession, contextIsolation: false } }); w.webContents.loadURL('data:text/html,<html></html>'); const webviewResult = once(ipcMain, 'web-sql-response'); await w.webContents.executeJavaScript(` new Promise((resolve, reject) => { const webview = new WebView(); webview.setAttribute('src', '${origin}'); webview.setAttribute('webpreferences', 'enableWebSQL=1,contextIsolation=no'); webview.setAttribute('partition', '${sqlPartition}'); webview.setAttribute('nodeIntegration', 'on'); document.body.appendChild(webview); webview.addEventListener('dom-ready', () => resolve()); }); `); const [, childError] = await webviewResult; expect(childError).to.equal(securityError); }); it('child webContents can use websql when the embedder has allowed websql', async () => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webviewTag: true, session: sqlSession, contextIsolation: false } }); w.webContents.loadURL(origin); const [, error] = await once(ipcMain, 'web-sql-response'); expect(error).to.be.null(); const webviewResult = once(ipcMain, 'web-sql-response'); await w.webContents.executeJavaScript(` new Promise((resolve, reject) => { const webview = new WebView(); webview.setAttribute('src', '${origin}'); webview.setAttribute('webpreferences', 'enableWebSQL=1,contextIsolation=no'); webview.setAttribute('partition', '${sqlPartition}'); webview.setAttribute('nodeIntegration', 'on'); document.body.appendChild(webview); webview.addEventListener('dom-ready', () => resolve()); }); `); const [, childError] = await webviewResult; expect(childError).to.be.null(); }); }); describe('DOM storage quota increase', () => { ['localStorage', 'sessionStorage'].forEach((storageName) => { it(`allows saving at least 40MiB in ${storageName}`, async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); // Although JavaScript strings use UTF-16, the underlying // storage provider may encode strings differently, muddling the // translation between character and byte counts. However, // a string of 40 * 2^20 characters will require at least 40MiB // and presumably no more than 80MiB, a size guaranteed to // to exceed the original 10MiB quota yet stay within the // new 100MiB quota. // Note that both the key name and value affect the total size. const testKeyName = '_electronDOMStorageQuotaIncreasedTest'; const length = 40 * Math.pow(2, 20) - testKeyName.length; await w.webContents.executeJavaScript(` ${storageName}.setItem(${JSON.stringify(testKeyName)}, 'X'.repeat(${length})); `); // Wait at least one turn of the event loop to help avoid false positives // Although not entirely necessary, the previous version of this test case // failed to detect a real problem (perhaps related to DOM storage data caching) // wherein calling `getItem` immediately after `setItem` would appear to work // but then later (e.g. next tick) it would not. await setTimeout(1); try { const storedLength = await w.webContents.executeJavaScript(`${storageName}.getItem(${JSON.stringify(testKeyName)}).length`); expect(storedLength).to.equal(length); } finally { await w.webContents.executeJavaScript(`${storageName}.removeItem(${JSON.stringify(testKeyName)});`); } }); it(`throws when attempting to use more than 128MiB in ${storageName}`, async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); await expect((async () => { const testKeyName = '_electronDOMStorageQuotaStillEnforcedTest'; const length = 128 * Math.pow(2, 20) - testKeyName.length; try { await w.webContents.executeJavaScript(` ${storageName}.setItem(${JSON.stringify(testKeyName)}, 'X'.repeat(${length})); `); } finally { await w.webContents.executeJavaScript(`${storageName}.removeItem(${JSON.stringify(testKeyName)});`); } })()).to.eventually.be.rejected(); }); }); }); describe('persistent storage', () => { it('can be requested', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); const grantedBytes = await w.webContents.executeJavaScript(`new Promise(resolve => { navigator.webkitPersistentStorage.requestQuota(1024 * 1024, resolve); })`); expect(grantedBytes).to.equal(1048576); }); }); }); ifdescribe(features.isPDFViewerEnabled())('PDF Viewer', () => { const pdfSource = url.format({ pathname: path.join(__dirname, 'fixtures', 'cat.pdf').replace(/\\/g, '/'), protocol: 'file', slashes: true }); it('successfully loads a PDF file', async () => { const w = new BrowserWindow({ show: false }); w.loadURL(pdfSource); await once(w.webContents, 'did-finish-load'); }); it('opens when loading a pdf resource as top level navigation', async () => { const w = new BrowserWindow({ show: false }); w.loadURL(pdfSource); const [, contents] = await once(app, 'web-contents-created') as [any, WebContents]; await once(contents, 'did-navigate'); expect(contents.getURL()).to.equal('chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/index.html'); }); it('opens when loading a pdf resource in a iframe', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(__dirname, 'fixtures', 'pages', 'pdf-in-iframe.html')); const [, contents] = await once(app, 'web-contents-created') as [any, WebContents]; await once(contents, 'did-navigate'); expect(contents.getURL()).to.equal('chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/index.html'); }); }); describe('window.history', () => { describe('window.history.pushState', () => { it('should push state after calling history.pushState() from the same url', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); // History should have current page by now. expect((w.webContents as any).length()).to.equal(1); const waitCommit = once(w.webContents, 'navigation-entry-committed'); w.webContents.executeJavaScript('window.history.pushState({}, "")'); await waitCommit; // Initial page + pushed state. expect((w.webContents as any).length()).to.equal(2); }); }); describe('window.history.back', () => { it('should not allow sandboxed iframe to modify main frame state', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('data:text/html,<iframe sandbox="allow-scripts"></iframe>'); await Promise.all([ once(w.webContents, 'navigation-entry-committed'), once(w.webContents, 'did-frame-navigate'), once(w.webContents, 'did-navigate') ]); w.webContents.executeJavaScript('window.history.pushState(1, "")'); await Promise.all([ once(w.webContents, 'navigation-entry-committed'), once(w.webContents, 'did-navigate-in-page') ]); (w.webContents as any).once('navigation-entry-committed', () => { expect.fail('Unexpected navigation-entry-committed'); }); w.webContents.once('did-navigate-in-page', () => { expect.fail('Unexpected did-navigate-in-page'); }); await w.webContents.mainFrame.frames[0].executeJavaScript('window.history.back()'); expect(await w.webContents.executeJavaScript('window.history.state')).to.equal(1); expect((w.webContents as any).getActiveIndex()).to.equal(1); }); }); }); describe('chrome://media-internals', () => { it('loads the page successfully', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('chrome://media-internals'); const pageExists = await w.webContents.executeJavaScript( "window.hasOwnProperty('chrome') && window.chrome.hasOwnProperty('send')" ); expect(pageExists).to.be.true(); }); }); describe('chrome://webrtc-internals', () => { it('loads the page successfully', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('chrome://webrtc-internals'); const pageExists = await w.webContents.executeJavaScript( "window.hasOwnProperty('chrome') && window.chrome.hasOwnProperty('send')" ); expect(pageExists).to.be.true(); }); }); describe('document.hasFocus', () => { it('has correct value when multiple windows are opened', async () => { const w1 = new BrowserWindow({ show: true }); const w2 = new BrowserWindow({ show: true }); const w3 = new BrowserWindow({ show: false }); await w1.loadFile(path.join(__dirname, 'fixtures', 'blank.html')); await w2.loadFile(path.join(__dirname, 'fixtures', 'blank.html')); await w3.loadFile(path.join(__dirname, 'fixtures', 'blank.html')); expect(webContents.getFocusedWebContents()?.id).to.equal(w2.webContents.id); let focus = false; focus = await w1.webContents.executeJavaScript( 'document.hasFocus()' ); expect(focus).to.be.false(); focus = await w2.webContents.executeJavaScript( 'document.hasFocus()' ); expect(focus).to.be.true(); focus = await w3.webContents.executeJavaScript( 'document.hasFocus()' ); expect(focus).to.be.false(); }); }); // https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation describe('navigator.connection', () => { it('returns the correct value', async () => { const w = new BrowserWindow({ show: false }); w.webContents.session.enableNetworkEmulation({ latency: 500, downloadThroughput: 6400, uploadThroughput: 6400 }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const rtt = await w.webContents.executeJavaScript('navigator.connection.rtt'); expect(rtt).to.be.a('number'); const downlink = await w.webContents.executeJavaScript('navigator.connection.downlink'); expect(downlink).to.be.a('number'); const effectiveTypes = ['slow-2g', '2g', '3g', '4g']; const effectiveType = await w.webContents.executeJavaScript('navigator.connection.effectiveType'); expect(effectiveTypes).to.include(effectiveType); }); }); describe('navigator.userAgentData', () => { // These tests are done on an http server because navigator.userAgentData // requires a secure context. let server: http.Server; let serverUrl: string; before(async () => { server = http.createServer((req, res) => { res.setHeader('Content-Type', 'text/html'); res.end(''); }); serverUrl = (await listen(server)).url; }); after(() => { server.close(); }); describe('is not empty', () => { it('by default', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(serverUrl); const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform'); expect(platform).not.to.be.empty(); }); it('when there is a session-wide UA override', async () => { const ses = session.fromPartition(`${Math.random()}`); ses.setUserAgent('foobar'); const w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await w.loadURL(serverUrl); const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform'); expect(platform).not.to.be.empty(); }); it('when there is a WebContents-specific UA override', async () => { const w = new BrowserWindow({ show: false }); w.webContents.setUserAgent('foo'); await w.loadURL(serverUrl); const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform'); expect(platform).not.to.be.empty(); }); it('when there is a WebContents-specific UA override at load time', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(serverUrl, { userAgent: 'foo' }); const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform'); expect(platform).not.to.be.empty(); }); }); describe('brand list', () => { it('contains chromium', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(serverUrl); const brands = await w.webContents.executeJavaScript('navigator.userAgentData.brands'); expect(brands.map((b: any) => b.brand)).to.include('Chromium'); }); }); }); describe('Badging API', () => { it('does not crash', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); await w.webContents.executeJavaScript('navigator.setAppBadge(42)'); await w.webContents.executeJavaScript('navigator.setAppBadge()'); await w.webContents.executeJavaScript('navigator.clearAppBadge()'); }); }); describe('navigator.webkitGetUserMedia', () => { it('calls its callbacks', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); await w.webContents.executeJavaScript(`new Promise((resolve) => { navigator.webkitGetUserMedia({ audio: true, video: false }, () => resolve(), () => resolve()); })`); }); }); describe('navigator.language', () => { it('should not be empty', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); expect(await w.webContents.executeJavaScript('navigator.language')).to.not.equal(''); }); }); describe('heap snapshot', () => { it('does not crash', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadURL('about:blank'); await w.webContents.executeJavaScript('process._linkedBinding(\'electron_common_v8_util\').takeHeapSnapshot()'); }); }); // This is intentionally disabled on arm macs: https://chromium-review.googlesource.com/c/chromium/src/+/4143761 ifdescribe(process.platform === 'darwin' && process.arch !== 'arm64')('webgl', () => { it('can be gotten as context in canvas', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const canWebglContextBeCreated = await w.webContents.executeJavaScript(` document.createElement('canvas').getContext('webgl') != null; `); expect(canWebglContextBeCreated).to.be.true(); }); }); describe('iframe', () => { it('does not have node integration', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const result = await w.webContents.executeJavaScript(` const iframe = document.createElement('iframe') iframe.src = './set-global.html'; document.body.appendChild(iframe); new Promise(resolve => iframe.onload = e => resolve(iframe.contentWindow.test)) `); expect(result).to.equal('undefined undefined undefined'); }); }); describe('websockets', () => { it('has user agent', async () => { const server = http.createServer(); const { port } = await listen(server); const wss = new ws.Server({ server: server }); const finished = new Promise<string | undefined>((resolve, reject) => { wss.on('error', reject); wss.on('connection', (ws, upgradeReq) => { resolve(upgradeReq.headers['user-agent']); }); }); const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.executeJavaScript(` new WebSocket('ws://127.0.0.1:${port}'); `); expect(await finished).to.include('Electron'); }); }); describe('fetch', () => { it('does not crash', async () => { const server = http.createServer((req, res) => { res.end('test'); }); defer(() => server.close()); const { port } = await listen(server); const w = new BrowserWindow({ show: false }); w.loadURL(`file://${fixturesPath}/pages/blank.html`); const x = await w.webContents.executeJavaScript(` fetch('http://127.0.0.1:${port}').then((res) => res.body.getReader()) .then((reader) => { return reader.read().then((r) => { reader.cancel(); return r.value; }); }) `); expect(x).to.deep.equal(new Uint8Array([116, 101, 115, 116])); }); }); describe('Promise', () => { before(() => { ipcMain.handle('ping', (e, arg) => arg); }); after(() => { ipcMain.removeHandler('ping'); }); itremote('resolves correctly in Node.js calls', async () => { await new Promise<void>((resolve, reject) => { class XElement extends HTMLElement {} customElements.define('x-element', XElement); setImmediate(() => { let called = false; Promise.resolve().then(() => { if (called) resolve(); else reject(new Error('wrong sequence')); }); document.createElement('x-element'); called = true; }); }); }); itremote('resolves correctly in Electron calls', async () => { await new Promise<void>((resolve, reject) => { class YElement extends HTMLElement {} customElements.define('y-element', YElement); require('electron').ipcRenderer.invoke('ping').then(() => { let called = false; Promise.resolve().then(() => { if (called) resolve(); else reject(new Error('wrong sequence')); }); document.createElement('y-element'); called = true; }); }); }); }); describe('synchronous prompts', () => { describe('window.alert(message, title)', () => { itremote('throws an exception when the arguments cannot be converted to strings', () => { expect(() => { window.alert({ toString: null }); }).to.throw('Cannot convert object to primitive value'); }); }); describe('window.confirm(message, title)', () => { itremote('throws an exception when the arguments cannot be converted to strings', () => { expect(() => { (window.confirm as any)({ toString: null }, 'title'); }).to.throw('Cannot convert object to primitive value'); }); }); }); describe('window.history', () => { describe('window.history.go(offset)', () => { itremote('throws an exception when the argument cannot be converted to a string', () => { expect(() => { (window.history.go as any)({ toString: null }); }).to.throw('Cannot convert object to primitive value'); }); }); }); describe('console functions', () => { itremote('should exist', () => { expect(console.log, 'log').to.be.a('function'); expect(console.error, 'error').to.be.a('function'); expect(console.warn, 'warn').to.be.a('function'); expect(console.info, 'info').to.be.a('function'); expect(console.debug, 'debug').to.be.a('function'); expect(console.trace, 'trace').to.be.a('function'); expect(console.time, 'time').to.be.a('function'); expect(console.timeEnd, 'timeEnd').to.be.a('function'); }); }); // FIXME(nornagon): this is broken on CI, it triggers: // [FATAL:speech_synthesis.mojom-shared.h(237)] The outgoing message will // trigger VALIDATION_ERROR_UNEXPECTED_NULL_POINTER at the receiving side // (null text in SpeechSynthesisUtterance struct). describe('SpeechSynthesis', () => { itremote('should emit lifecycle events', async () => { const sentence = `long sentence which will take at least a few seconds to utter so that it's possible to pause and resume before the end`; const utter = new SpeechSynthesisUtterance(sentence); // Create a dummy utterance so that speech synthesis state // is initialized for later calls. speechSynthesis.speak(new SpeechSynthesisUtterance()); speechSynthesis.cancel(); speechSynthesis.speak(utter); // paused state after speak() expect(speechSynthesis.paused).to.be.false(); await new Promise((resolve) => { utter.onstart = resolve; }); // paused state after start event expect(speechSynthesis.paused).to.be.false(); speechSynthesis.pause(); // paused state changes async, right before the pause event expect(speechSynthesis.paused).to.be.false(); await new Promise((resolve) => { utter.onpause = resolve; }); expect(speechSynthesis.paused).to.be.true(); speechSynthesis.resume(); await new Promise((resolve) => { utter.onresume = resolve; }); // paused state after resume event expect(speechSynthesis.paused).to.be.false(); await new Promise((resolve) => { utter.onend = resolve; }); }); }); }); describe('font fallback', () => { async function getRenderedFonts (html: string) { const w = new BrowserWindow({ show: false }); try { await w.loadURL(`data:text/html,${html}`); w.webContents.debugger.attach(); const sendCommand = (method: string, commandParams?: any) => w.webContents.debugger.sendCommand(method, commandParams); const { nodeId } = (await sendCommand('DOM.getDocument')).root.children[0]; await sendCommand('CSS.enable'); const { fonts } = await sendCommand('CSS.getPlatformFontsForNode', { nodeId }); return fonts; } finally { w.close(); } } it('should use Helvetica for sans-serif on Mac, and Arial on Windows and Linux', async () => { const html = '<body style="font-family: sans-serif">test</body>'; const fonts = await getRenderedFonts(html); expect(fonts).to.be.an('array'); expect(fonts).to.have.length(1); if (process.platform === 'win32') { expect(fonts[0].familyName).to.equal('Arial'); } else if (process.platform === 'darwin') { expect(fonts[0].familyName).to.equal('Helvetica'); } else if (process.platform === 'linux') { expect(fonts[0].familyName).to.equal('DejaVu Sans'); } // I think this depends on the distro? We don't specify a default. }); ifit(process.platform !== 'linux')('should fall back to Japanese font for sans-serif Japanese script', async function () { const html = ` <html lang="ja-JP"> <head> <meta charset="utf-8" /> </head> <body style="font-family: sans-serif">test 智史</body> </html> `; const fonts = await getRenderedFonts(html); expect(fonts).to.be.an('array'); expect(fonts).to.have.length(1); if (process.platform === 'win32') { expect(fonts[0].familyName).to.be.oneOf(['Meiryo', 'Yu Gothic']); } else if (process.platform === 'darwin') { expect(fonts[0].familyName).to.equal('Hiragino Kaku Gothic ProN'); } }); }); describe('iframe using HTML fullscreen API while window is OS-fullscreened', () => { const fullscreenChildHtml = promisify(fs.readFile)( path.join(fixturesPath, 'pages', 'fullscreen-oopif.html') ); let w: BrowserWindow; let server: http.Server; let crossSiteUrl: string; beforeEach(async () => { server = http.createServer(async (_req, res) => { res.writeHead(200, { 'Content-Type': 'text/html' }); res.write(await fullscreenChildHtml); res.end(); }); const serverUrl = (await listen(server)).url; crossSiteUrl = serverUrl.replace('127.0.0.1', 'localhost'); w = new BrowserWindow({ show: true, fullscreen: true, webPreferences: { nodeIntegration: true, nodeIntegrationInSubFrames: true, contextIsolation: false } }); }); afterEach(async () => { await closeAllWindows(); (w as any) = null; server.close(); }); ifit(process.platform !== 'darwin')('can fullscreen from out-of-process iframes (non-macOS)', async () => { const fullscreenChange = once(ipcMain, 'fullscreenChange'); const html = `<iframe style="width: 0" frameborder=0 src="${crossSiteUrl}" allowfullscreen></iframe>`; w.loadURL(`data:text/html,${html}`); await fullscreenChange; const fullscreenWidth = await w.webContents.executeJavaScript( "document.querySelector('iframe').offsetWidth" ); expect(fullscreenWidth > 0).to.be.true(); await w.webContents.executeJavaScript( "document.querySelector('iframe').contentWindow.postMessage('exitFullscreen', '*')" ); await setTimeout(500); const width = await w.webContents.executeJavaScript( "document.querySelector('iframe').offsetWidth" ); expect(width).to.equal(0); }); ifit(process.platform === 'darwin')('can fullscreen from out-of-process iframes (macOS)', async () => { await once(w, 'enter-full-screen'); const fullscreenChange = once(ipcMain, 'fullscreenChange'); const html = `<iframe style="width: 0" frameborder=0 src="${crossSiteUrl}" allowfullscreen></iframe>`; w.loadURL(`data:text/html,${html}`); await fullscreenChange; const fullscreenWidth = await w.webContents.executeJavaScript( "document.querySelector('iframe').offsetWidth" ); expect(fullscreenWidth > 0).to.be.true(); await w.webContents.executeJavaScript( "document.querySelector('iframe').contentWindow.postMessage('exitFullscreen', '*')" ); await once(w.webContents, 'leave-html-full-screen'); const width = await w.webContents.executeJavaScript( "document.querySelector('iframe').offsetWidth" ); expect(width).to.equal(0); w.setFullScreen(false); await once(w, 'leave-full-screen'); }); // TODO(jkleinsc) fix this flaky test on WOA ifit(process.platform !== 'win32' || process.arch !== 'arm64')('can fullscreen from in-process iframes', async () => { if (process.platform === 'darwin') await once(w, 'enter-full-screen'); const fullscreenChange = once(ipcMain, 'fullscreenChange'); w.loadFile(path.join(fixturesPath, 'pages', 'fullscreen-ipif.html')); await fullscreenChange; const fullscreenWidth = await w.webContents.executeJavaScript( "document.querySelector('iframe').offsetWidth" ); expect(fullscreenWidth > 0).to.true(); await w.webContents.executeJavaScript('document.exitFullscreen()'); const width = await w.webContents.executeJavaScript( "document.querySelector('iframe').offsetWidth" ); expect(width).to.equal(0); }); }); describe('navigator.serial', () => { let w: BrowserWindow; before(async () => { w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); }); const getPorts: any = () => { return w.webContents.executeJavaScript(` navigator.serial.requestPort().then(port => port.toString()).catch(err => err.toString()); `, true); }; const notFoundError = 'NotFoundError: Failed to execute \'requestPort\' on \'Serial\': No port selected by the user.'; after(closeAllWindows); afterEach(() => { session.defaultSession.setPermissionCheckHandler(null); session.defaultSession.removeAllListeners('select-serial-port'); }); it('does not return a port if select-serial-port event is not defined', async () => { w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); const port = await getPorts(); expect(port).to.equal(notFoundError); }); it('does not return a port when permission denied', async () => { w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => { callback(portList[0].portId); }); session.defaultSession.setPermissionCheckHandler(() => false); const port = await getPorts(); expect(port).to.equal(notFoundError); }); it('does not crash when select-serial-port is called with an invalid port', async () => { w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => { callback('i-do-not-exist'); }); const port = await getPorts(); expect(port).to.equal(notFoundError); }); it('returns a port when select-serial-port event is defined', async () => { let havePorts = false; w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => { if (portList.length > 0) { havePorts = true; callback(portList[0].portId); } else { callback(''); } }); const port = await getPorts(); if (havePorts) { expect(port).to.equal('[object SerialPort]'); } else { expect(port).to.equal(notFoundError); } }); it('navigator.serial.getPorts() returns values', async () => { let havePorts = false; w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => { if (portList.length > 0) { havePorts = true; callback(portList[0].portId); } else { callback(''); } }); await getPorts(); if (havePorts) { const grantedPorts = await w.webContents.executeJavaScript('navigator.serial.getPorts()'); expect(grantedPorts).to.not.be.empty(); } }); it('supports port.forget()', async () => { let forgottenPortFromEvent = {}; let havePorts = false; w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => { if (portList.length > 0) { havePorts = true; callback(portList[0].portId); } else { callback(''); } }); w.webContents.session.on('serial-port-revoked', (event, details) => { forgottenPortFromEvent = details.port; }); await getPorts(); if (havePorts) { const grantedPorts = await w.webContents.executeJavaScript('navigator.serial.getPorts()'); if (grantedPorts.length > 0) { const forgottenPort = await w.webContents.executeJavaScript(` navigator.serial.getPorts().then(async(ports) => { const portInfo = await ports[0].getInfo(); await ports[0].forget(); if (portInfo.usbVendorId && portInfo.usbProductId) { return { vendorId: '' + portInfo.usbVendorId, productId: '' + portInfo.usbProductId } } else { return {}; } }) `); const grantedPorts2 = await w.webContents.executeJavaScript('navigator.serial.getPorts()'); expect(grantedPorts2.length).to.be.lessThan(grantedPorts.length); if (forgottenPort.vendorId && forgottenPort.productId) { expect(forgottenPortFromEvent).to.include(forgottenPort); } } } }); }); describe('window.getScreenDetails', () => { let w: BrowserWindow; before(async () => { w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); }); after(closeAllWindows); afterEach(() => { session.defaultSession.setPermissionRequestHandler(null); }); const getScreenDetails: any = () => { return w.webContents.executeJavaScript('window.getScreenDetails().then(data => data.screens).catch(err => err.message)', true); }; it('returns screens when a PermissionRequestHandler is not defined', async () => { const screens = await getScreenDetails(); expect(screens).to.not.equal('Read permission denied.'); }); it('returns an error when permission denied', async () => { session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => { if (permission === 'window-management') { callback(false); } else { callback(true); } }); const screens = await getScreenDetails(); expect(screens).to.equal('Permission denied.'); }); it('returns screens when permission is granted', async () => { session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => { if (permission === 'window-management') { callback(true); } else { callback(false); } }); const screens = await getScreenDetails(); expect(screens).to.not.equal('Permission denied.'); }); }); describe('navigator.clipboard.read', () => { let w: BrowserWindow; before(async () => { w = new BrowserWindow(); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); }); const readClipboard: any = () => { return w.webContents.executeJavaScript(` navigator.clipboard.read().then(clipboard => clipboard.toString()).catch(err => err.message); `, true); }; after(closeAllWindows); afterEach(() => { session.defaultSession.setPermissionRequestHandler(null); }); it('returns clipboard contents when a PermissionRequestHandler is not defined', async () => { const clipboard = await readClipboard(); expect(clipboard).to.not.equal('Read permission denied.'); }); it('returns an error when permission denied', async () => { session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => { if (permission === 'clipboard-read') { callback(false); } else { callback(true); } }); const clipboard = await readClipboard(); expect(clipboard).to.equal('Read permission denied.'); }); it('returns clipboard contents when permission is granted', async () => { session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => { if (permission === 'clipboard-read') { callback(true); } else { callback(false); } }); const clipboard = await readClipboard(); expect(clipboard).to.not.equal('Read permission denied.'); }); }); describe('navigator.clipboard.write', () => { let w: BrowserWindow; before(async () => { w = new BrowserWindow(); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); }); const writeClipboard: any = () => { return w.webContents.executeJavaScript(` navigator.clipboard.writeText('Hello World!').catch(err => err.message); `, true); }; after(closeAllWindows); afterEach(() => { session.defaultSession.setPermissionRequestHandler(null); }); it('returns clipboard contents when a PermissionRequestHandler is not defined', async () => { const clipboard = await writeClipboard(); expect(clipboard).to.not.equal('Write permission denied.'); }); it('returns an error when permission denied', async () => { session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => { if (permission === 'clipboard-sanitized-write') { callback(false); } else { callback(true); } }); const clipboard = await writeClipboard(); expect(clipboard).to.equal('Write permission denied.'); }); it('returns clipboard contents when permission is granted', async () => { session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => { if (permission === 'clipboard-sanitized-write') { callback(true); } else { callback(false); } }); const clipboard = await writeClipboard(); expect(clipboard).to.not.equal('Write permission denied.'); }); }); ifdescribe((process.platform !== 'linux' || app.isUnityRunning()))('navigator.setAppBadge/clearAppBadge', () => { let w: BrowserWindow; const expectedBadgeCount = 42; const fireAppBadgeAction: any = (action: string, value: any) => { return w.webContents.executeJavaScript(` navigator.${action}AppBadge(${value}).then(() => 'success').catch(err => err.message)`); }; // For some reason on macOS changing the badge count doesn't happen right away, so wait // until it changes. async function waitForBadgeCount (value: number) { let badgeCount = app.getBadgeCount(); while (badgeCount !== value) { await setTimeout(10); badgeCount = app.getBadgeCount(); } return badgeCount; } describe('in the renderer', () => { before(async () => { w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); }); after(() => { app.badgeCount = 0; closeAllWindows(); }); it('setAppBadge can set a numerical value', async () => { const result = await fireAppBadgeAction('set', expectedBadgeCount); expect(result).to.equal('success'); expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount); }); it('setAppBadge can set an empty(dot) value', async () => { const result = await fireAppBadgeAction('set'); expect(result).to.equal('success'); expect(waitForBadgeCount(0)).to.eventually.equal(0); }); it('clearAppBadge can clear a value', async () => { let result = await fireAppBadgeAction('set', expectedBadgeCount); expect(result).to.equal('success'); expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount); result = await fireAppBadgeAction('clear'); expect(result).to.equal('success'); expect(waitForBadgeCount(0)).to.eventually.equal(0); }); }); describe('in a service worker', () => { beforeEach(async () => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, partition: 'sw-file-scheme-spec', contextIsolation: false } }); }); afterEach(() => { app.badgeCount = 0; closeAllWindows(); }); it('setAppBadge can be called in a ServiceWorker', (done) => { w.webContents.on('ipc-message', (event, channel, message) => { if (channel === 'reload') { w.webContents.reload(); } else if (channel === 'error') { done(message); } else if (channel === 'response') { expect(message).to.equal('SUCCESS setting app badge'); expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount); session.fromPartition('sw-file-scheme-spec').clearStorageData({ storages: ['serviceworkers'] }).then(() => done()); } }); w.webContents.on('render-process-gone', () => done(new Error('WebContents crashed.'))); w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'badge-index.html'), { search: '?setBadge' }); }); it('clearAppBadge can be called in a ServiceWorker', (done) => { w.webContents.on('ipc-message', (event, channel, message) => { if (channel === 'reload') { w.webContents.reload(); } else if (channel === 'setAppBadge') { expect(message).to.equal('SUCCESS setting app badge'); expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount); } else if (channel === 'error') { done(message); } else if (channel === 'response') { expect(message).to.equal('SUCCESS clearing app badge'); expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount); session.fromPartition('sw-file-scheme-spec').clearStorageData({ storages: ['serviceworkers'] }).then(() => done()); } }); w.webContents.on('render-process-gone', () => done(new Error('WebContents crashed.'))); w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'badge-index.html'), { search: '?clearBadge' }); }); }); }); describe('navigator.bluetooth', () => { let w: BrowserWindow; before(async () => { w = new BrowserWindow({ show: false, webPreferences: { enableBlinkFeatures: 'WebBluetooth' } }); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); }); after(closeAllWindows); it('can request bluetooth devices', async () => { const bluetooth = await w.webContents.executeJavaScript(` navigator.bluetooth.requestDevice({ acceptAllDevices: true}).then(device => "Found a device!").catch(err => err.message);`, true); expect(bluetooth).to.be.oneOf(['Found a device!', 'Bluetooth adapter not available.', 'User cancelled the requestDevice() chooser.']); }); }); describe('navigator.hid', () => { let w: BrowserWindow; let server: http.Server; let serverUrl: string; before(async () => { w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); server = http.createServer((req, res) => { res.setHeader('Content-Type', 'text/html'); res.end('<body>'); }); serverUrl = (await listen(server)).url; }); const requestDevices: any = () => { return w.webContents.executeJavaScript(` navigator.hid.requestDevice({filters: []}).then(device => device.toString()).catch(err => err.toString()); `, true); }; after(() => { server.close(); closeAllWindows(); }); afterEach(() => { session.defaultSession.setPermissionCheckHandler(null); session.defaultSession.setDevicePermissionHandler(null); session.defaultSession.removeAllListeners('select-hid-device'); }); it('does not return a device if select-hid-device event is not defined', async () => { w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); const device = await requestDevices(); expect(device).to.equal(''); }); it('does not return a device when permission denied', async () => { let selectFired = false; w.webContents.session.on('select-hid-device', (event, details, callback) => { selectFired = true; callback(); }); session.defaultSession.setPermissionCheckHandler(() => false); const device = await requestDevices(); expect(selectFired).to.be.false(); expect(device).to.equal(''); }); it('returns a device when select-hid-device event is defined', async () => { let haveDevices = false; let selectFired = false; w.webContents.session.on('select-hid-device', (event, details, callback) => { expect(details.frame).to.have.property('frameTreeNodeId').that.is.a('number'); selectFired = true; if (details.deviceList.length > 0) { haveDevices = true; callback(details.deviceList[0].deviceId); } else { callback(); } }); const device = await requestDevices(); expect(selectFired).to.be.true(); if (haveDevices) { expect(device).to.contain('[object HIDDevice]'); } else { expect(device).to.equal(''); } if (haveDevices) { // Verify that navigation will clear device permissions const grantedDevices = await w.webContents.executeJavaScript('navigator.hid.getDevices()'); expect(grantedDevices).to.not.be.empty(); w.loadURL(serverUrl); const [,,,,, frameProcessId, frameRoutingId] = await once(w.webContents, 'did-frame-navigate'); const frame = webFrameMain.fromId(frameProcessId, frameRoutingId); expect(!!frame).to.be.true(); if (frame) { const grantedDevicesOnNewPage = await frame.executeJavaScript('navigator.hid.getDevices()'); expect(grantedDevicesOnNewPage).to.be.empty(); } } }); it('returns a device when DevicePermissionHandler is defined', async () => { let haveDevices = false; let selectFired = false; let gotDevicePerms = false; w.webContents.session.on('select-hid-device', (event, details, callback) => { selectFired = true; if (details.deviceList.length > 0) { const foundDevice = details.deviceList.find((device) => { if (device.name && device.name !== '' && device.serialNumber && device.serialNumber !== '') { haveDevices = true; return true; } }); if (foundDevice) { callback(foundDevice.deviceId); return; } } callback(); }); session.defaultSession.setDevicePermissionHandler(() => { gotDevicePerms = true; return true; }); await w.webContents.executeJavaScript('navigator.hid.getDevices();', true); const device = await requestDevices(); expect(selectFired).to.be.true(); if (haveDevices) { expect(device).to.contain('[object HIDDevice]'); expect(gotDevicePerms).to.be.true(); } else { expect(device).to.equal(''); } }); it('excludes a device when a exclusionFilter is specified', async () => { const exclusionFilters = <any>[]; let haveDevices = false; let checkForExcludedDevice = false; w.webContents.session.on('select-hid-device', (event, details, callback) => { if (details.deviceList.length > 0) { details.deviceList.find((device) => { if (device.name && device.name !== '' && device.serialNumber && device.serialNumber !== '') { if (checkForExcludedDevice) { const compareDevice = { vendorId: device.vendorId, productId: device.productId }; expect(compareDevice).to.not.equal(exclusionFilters[0], 'excluded device should not be returned'); } else { haveDevices = true; exclusionFilters.push({ vendorId: device.vendorId, productId: device.productId }); return true; } } }); } callback(); }); await requestDevices(); if (haveDevices) { // We have devices to exclude, so check if exclusionFilters work checkForExcludedDevice = true; await w.webContents.executeJavaScript(` navigator.hid.requestDevice({filters: [], exclusionFilters: ${JSON.stringify(exclusionFilters)}}).then(device => device.toString()).catch(err => err.toString()); `, true); } }); it('supports device.forget()', async () => { let deletedDeviceFromEvent; let haveDevices = false; w.webContents.session.on('select-hid-device', (event, details, callback) => { if (details.deviceList.length > 0) { haveDevices = true; callback(details.deviceList[0].deviceId); } else { callback(); } }); w.webContents.session.on('hid-device-revoked', (event, details) => { deletedDeviceFromEvent = details.device; }); await requestDevices(); if (haveDevices) { const grantedDevices = await w.webContents.executeJavaScript('navigator.hid.getDevices()'); if (grantedDevices.length > 0) { const deletedDevice = await w.webContents.executeJavaScript(` navigator.hid.getDevices().then(devices => { devices[0].forget(); return { vendorId: devices[0].vendorId, productId: devices[0].productId, name: devices[0].productName } }) `); const grantedDevices2 = await w.webContents.executeJavaScript('navigator.hid.getDevices()'); expect(grantedDevices2.length).to.be.lessThan(grantedDevices.length); if (deletedDevice.name !== '' && deletedDevice.productId && deletedDevice.vendorId) { expect(deletedDeviceFromEvent).to.include(deletedDevice); } } } }); }); describe('navigator.usb', () => { let w: BrowserWindow; let server: http.Server; let serverUrl: string; before(async () => { w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); server = http.createServer((req, res) => { res.setHeader('Content-Type', 'text/html'); res.end('<body>'); }); serverUrl = (await listen(server)).url; }); const requestDevices: any = () => { return w.webContents.executeJavaScript(` navigator.usb.requestDevice({filters: []}).then(device => device.toString()).catch(err => err.toString()); `, true); }; const notFoundError = 'NotFoundError: Failed to execute \'requestDevice\' on \'USB\': No device selected.'; after(() => { server.close(); closeAllWindows(); }); afterEach(() => { session.defaultSession.setPermissionCheckHandler(null); session.defaultSession.setDevicePermissionHandler(null); session.defaultSession.removeAllListeners('select-usb-device'); }); it('does not return a device if select-usb-device event is not defined', async () => { w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); const device = await requestDevices(); expect(device).to.equal(notFoundError); }); it('does not return a device when permission denied', async () => { let selectFired = false; w.webContents.session.on('select-usb-device', (event, details, callback) => { selectFired = true; callback(); }); session.defaultSession.setPermissionCheckHandler(() => false); const device = await requestDevices(); expect(selectFired).to.be.false(); expect(device).to.equal(notFoundError); }); it('returns a device when select-usb-device event is defined', async () => { let haveDevices = false; let selectFired = false; w.webContents.session.on('select-usb-device', (event, details, callback) => { expect(details.frame).to.have.property('frameTreeNodeId').that.is.a('number'); selectFired = true; if (details.deviceList.length > 0) { haveDevices = true; callback(details.deviceList[0].deviceId); } else { callback(); } }); const device = await requestDevices(); expect(selectFired).to.be.true(); if (haveDevices) { expect(device).to.contain('[object USBDevice]'); } else { expect(device).to.equal(notFoundError); } if (haveDevices) { // Verify that navigation will clear device permissions const grantedDevices = await w.webContents.executeJavaScript('navigator.usb.getDevices()'); expect(grantedDevices).to.not.be.empty(); w.loadURL(serverUrl); const [,,,,, frameProcessId, frameRoutingId] = await once(w.webContents, 'did-frame-navigate'); const frame = webFrameMain.fromId(frameProcessId, frameRoutingId); expect(!!frame).to.be.true(); if (frame) { const grantedDevicesOnNewPage = await frame.executeJavaScript('navigator.usb.getDevices()'); expect(grantedDevicesOnNewPage).to.be.empty(); } } }); it('returns a device when DevicePermissionHandler is defined', async () => { let haveDevices = false; let selectFired = false; let gotDevicePerms = false; w.webContents.session.on('select-usb-device', (event, details, callback) => { selectFired = true; if (details.deviceList.length > 0) { const foundDevice = details.deviceList.find((device) => { if (device.productName && device.productName !== '' && device.serialNumber && device.serialNumber !== '') { haveDevices = true; return true; } }); if (foundDevice) { callback(foundDevice.deviceId); return; } } callback(); }); session.defaultSession.setDevicePermissionHandler(() => { gotDevicePerms = true; return true; }); await w.webContents.executeJavaScript('navigator.usb.getDevices();', true); const device = await requestDevices(); expect(selectFired).to.be.true(); if (haveDevices) { expect(device).to.contain('[object USBDevice]'); expect(gotDevicePerms).to.be.true(); } else { expect(device).to.equal(notFoundError); } }); it('supports device.forget()', async () => { let deletedDeviceFromEvent; let haveDevices = false; w.webContents.session.on('select-usb-device', (event, details, callback) => { if (details.deviceList.length > 0) { haveDevices = true; callback(details.deviceList[0].deviceId); } else { callback(); } }); w.webContents.session.on('usb-device-revoked', (event, details) => { deletedDeviceFromEvent = details.device; }); await requestDevices(); if (haveDevices) { const grantedDevices = await w.webContents.executeJavaScript('navigator.usb.getDevices()'); if (grantedDevices.length > 0) { const deletedDevice: Electron.USBDevice = await w.webContents.executeJavaScript(` navigator.usb.getDevices().then(devices => { devices[0].forget(); return { vendorId: devices[0].vendorId, productId: devices[0].productId, productName: devices[0].productName } }) `); const grantedDevices2 = await w.webContents.executeJavaScript('navigator.usb.getDevices()'); expect(grantedDevices2.length).to.be.lessThan(grantedDevices.length); if (deletedDevice.productName !== '' && deletedDevice.productId && deletedDevice.vendorId) { expect(deletedDeviceFromEvent).to.include(deletedDevice); } } } }); });
closed
electron/electron
https://github.com/electron/electron
39,550
[Bug]: Thumbnail toolbar buttons are removed when Explorer is restarted
### 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 25.4.0 ### What operating system are you using? Windows ### Operating System Version Windows 10 Pro 22H2 (19045.3324) ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior After adding buttons with `BrowserWindow.setThumbarButtons`, thumbnail toolbar buttons persist across explorer restarts. ### Actual Behavior After adding buttons with `BrowserWindow.setThumbarButtons`, thumbnail toolbar buttons are removed when explorer is restarted. After that, you can't add buttons with `BrowserWindow.setThumbarButtons`. ### Testcase Gist URL _No response_ ### Additional Information You can restart Explorer by selecting the Explorer context menu from Task Manager.
https://github.com/electron/electron/issues/39550
https://github.com/electron/electron/pull/39551
95bf9d8adb33bc2aaf988977b18663f9a770ef77
9937a2bbe8dd6cc01ff3dd0ce32268e33c0ec1de
2023-08-17T07:07:04Z
c++
2023-08-21T00:43:49Z
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 <dwmapi.h> #include <wrl/client.h> #endif #include <memory> #include <utility> #include <vector> #include "base/containers/contains.h" #include "base/memory/raw_ptr.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/ui/inspectable_web_contents.h" #include "shell/browser/ui/views/inspectable_web_contents_view_views.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/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 "shell/common/platform_util.h" #include "ui/views/widget/desktop_aura/desktop_native_widget_aura.h" #include "ui/views/window/native_frame_view.h" #if defined(USE_OZONE) #include "shell/browser/ui/views/global_menu_bar_x11.h" #include "shell/browser/ui/x/event_disabler.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" #include "ui/ozone/public/ozone_platform.h" #endif #elif BUILDFLAG(IS_WIN) #include "base/win/win_util.h" #include "base/win/windows_version.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" #include "ui/gfx/win/msg_util.h" #endif namespace electron { #if BUILDFLAG(IS_WIN) DWM_SYSTEMBACKDROP_TYPE GetBackdropFromString(const std::string& material) { if (material == "none") { return DWMSBT_NONE; } else if (material == "acrylic") { return DWMSBT_TRANSIENTWINDOW; } else if (material == "mica") { return DWMSBT_MAINWINDOW; } else if (material == "tabbed") { return DWMSBT_TABBEDWINDOW; } return DWMSBT_AUTO; } // 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; } // Chromium uses a buggy implementation that converts content rect to window // rect when calculating min/max size, we should use the same implementation // when passing min/max size so we can get correct results. gfx::Size WindowSizeToContentSizeBuggy(HWND hwnd, const gfx::Size& size) { // Calculate the size of window frame, using same code with the // HWNDMessageHandler::OnGetMinMaxInfo method. // The pitfall is, when window is minimized the calculated window frame size // will be different from other states. RECT client_rect, rect; GetClientRect(hwnd, &client_rect); GetWindowRect(hwnd, &rect); CR_DEFLATE_RECT(&rect, &client_rect); // Convert DIP size to pixel size, do calculation and then return DIP size. gfx::Rect screen_rect = DIPToScreenRect(hwnd, gfx::Rect(size)); gfx::Size screen_client_size(screen_rect.width() - (rect.right - rect.left), screen_rect.height() - (rect.bottom - rect.top)); return ScreenToDIPRect(hwnd, gfx::Rect(screen_client_size)).size(); } #endif #if defined(USE_OZONE) bool CreateGlobalMenuBar() { return ui::OzonePlatform::GetInstance() ->GetPlatformProperties() .supports_global_application_menus; } #endif #if defined(USE_OZONE_PLATFORM_X11) bool IsX11() { return ui::OzonePlatform::GetInstance() ->GetPlatformProperties() .electron_can_call_x11; } #endif class NativeWindowClientView : public views::ClientView { public: NativeWindowClientView(views::Widget* widget, views::View* root_view, NativeWindowViews* window) : views::ClientView{widget, root_view}, window_{raw_ref<NativeWindowViews>::from_ptr(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: const raw_ref<NativeWindowViews> window_; }; } // namespace NativeWindowViews::NativeWindowViews(const gin_helper::Dictionary& options, NativeWindow* parent) : NativeWindow(options, parent) { 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; // Set Wayland application ID. params.wayland_app_id = platform_util::GetXdgAppId(); 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 BUILDFLAG(IS_LINUX) // 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); } if (parent) SetParentWindow(parent); #endif #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { // 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; // 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_) frame_style |= WS_THICKFRAME; if (minimizable_) frame_style |= WS_MINIMIZEBOX; if (maximizable_) frame_style |= WS_MAXIMIZEBOX; // We should not show a frame for transparent window. if (!thick_frame_) frame_style &= ~(WS_THICKFRAME | 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_OZONE_PLATFORM_X11) if (IsX11()) { 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_OZONE) if (global_menu_bar_) global_menu_bar_->OnWindowMapped(); #endif #if defined(USE_OZONE_PLATFORM_X11) // On X11, setting Z order before showing the window doesn't take effect, // so we have to call it again. if (IsX11()) widget()->SetZOrderLevel(widget()->GetZOrderLevel()); #endif } void NativeWindowViews::ShowInactive() { widget()->ShowInactive(); NotifyWindowShow(); #if defined(USE_OZONE) 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_OZONE) 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() { #if BUILDFLAG(IS_WIN) // widget()->IsVisible() calls ::IsWindowVisible, which returns non-zero if a // window or any of its parent windows are visible. We want to only check the // current window. bool visible = ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_VISIBLE; // WS_VISIBLE is true even if a window is miminized - explicitly check that. return visible && !IsMinimized(); #else return widget()->IsVisible(); #endif } bool NativeWindowViews::IsEnabled() { #if BUILDFLAG(IS_WIN) return ::IsWindowEnabled(GetAcceleratedWidget()); #elif BUILDFLAG(IS_LINUX) #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) 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_OZONE_PLATFORM_X11) if (IsX11()) { 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()); NotifyWindowShow(); } } #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() && !IsMinimized()) { // 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) { menu_bar_visible_before_fullscreen_ = IsMenuBarVisible(); SetMenuBarVisibility(false); } else { SetMenuBarVisibility(!IsMenuBarAutoHide() && menu_bar_visible_before_fullscreen_); menu_bar_visible_before_fullscreen_ = false; } #endif } bool NativeWindowViews::IsFullscreen() const { return widget()->IsFullscreen(); } void NativeWindowViews::SetBounds(const gfx::Rect& bounds, bool animate) { #if BUILDFLAG(IS_WIN) if (is_moving_ || is_resizing_) { pending_bounds_change_ = bounds; } #endif #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() { #if BUILDFLAG(IS_WIN) if (IsMaximized() && transparent()) return restore_bounds_; #endif 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; } #if BUILDFLAG(IS_WIN) // This override does almost the same with its parent, except that it uses // the WindowSizeToContentSizeBuggy method to convert window size to content // size. See the comment of the method for the reason behind this. extensions::SizeConstraints NativeWindowViews::GetContentSizeConstraints() const { if (content_size_constraints_) return *content_size_constraints_; if (!size_constraints_) return extensions::SizeConstraints(); extensions::SizeConstraints constraints; if (size_constraints_->HasMaximumSize()) { constraints.set_maximum_size(WindowSizeToContentSizeBuggy( GetAcceleratedWidget(), size_constraints_->GetMaximumSize())); } if (size_constraints_->HasMinimumSize()) { constraints.set_minimum_size(WindowSizeToContentSizeBuggy( GetAcceleratedWidget(), size_constraints_->GetMinimumSize())); } return constraints; } #endif 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_OZONE_PLATFORM_X11) if (IsX11()) { 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_OZONE_PLATFORM_X11) if (IsX11()) 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); if (IsWindowControlsOverlayEnabled()) { auto* frame_view = static_cast<WinFrameView*>(widget()->non_client_view()->frame_view()); frame_view->caption_button_container()->UpdateButtons(); } #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); if (IsWindowControlsOverlayEnabled()) { auto* frame_view = static_cast<WinFrameView*>(widget()->non_client_view()->frame_view()); frame_view->caption_button_container()->UpdateButtons(); } #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); } if (IsWindowControlsOverlayEnabled()) { auto* frame_view = static_cast<WinFrameView*>(widget()->non_client_view()->frame_view()); frame_view->caption_button_container()->UpdateButtons(); } #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()); } #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 = std::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_OZONE_PLATFORM_X11) if (IsX11()) { 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_OZONE) // 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 (CreateGlobalMenuBar() && 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_OZONE_PLATFORM_X11) if (IsX11()) 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::SetBackgroundMaterial(const std::string& material) { #if BUILDFLAG(IS_WIN) // DWMWA_USE_HOSTBACKDROPBRUSH is only supported on Windows 11 22H2 and up. if (base::win::GetVersion() < base::win::Version::WIN11_22H2) return; DWM_SYSTEMBACKDROP_TYPE backdrop_type = GetBackdropFromString(material); HRESULT result = DwmSetWindowAttribute(GetAcceleratedWidget(), DWMWA_SYSTEMBACKDROP_TYPE, &backdrop_type, sizeof(backdrop_type)); if (FAILED(result)) LOG(WARNING) << "Failed to set background material to " << material; #endif } void NativeWindowViews::SetVisibleOnAllWorkspaces( bool visible, bool visibleOnFullScreen, bool skipTransformProcessType) { widget()->SetVisibleOnAllWorkspaces(visible); } bool NativeWindowViews::IsVisibleOnAllWorkspaces() { #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { // 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 base::Contains(wm_states, sticky_atom); } #endif return false; } 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; } #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 blurred. 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_; } bool NativeWindowViews::ShouldDescendIntoChildForEventHandling( gfx::NativeView child, const gfx::Point& location) { return NonClientHitTest(location) == HTNOWHERE; } views::ClientView* NativeWindowViews::CreateClientView(views::Widget* widget) { return new NativeWindowClientView{widget, GetContentsView(), 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
39,550
[Bug]: Thumbnail toolbar buttons are removed when Explorer is restarted
### 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 25.4.0 ### What operating system are you using? Windows ### Operating System Version Windows 10 Pro 22H2 (19045.3324) ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior After adding buttons with `BrowserWindow.setThumbarButtons`, thumbnail toolbar buttons persist across explorer restarts. ### Actual Behavior After adding buttons with `BrowserWindow.setThumbarButtons`, thumbnail toolbar buttons are removed when explorer is restarted. After that, you can't add buttons with `BrowserWindow.setThumbarButtons`. ### Testcase Gist URL _No response_ ### Additional Information You can restart Explorer by selecting the Explorer context menu from Task Manager.
https://github.com/electron/electron/issues/39550
https://github.com/electron/electron/pull/39551
95bf9d8adb33bc2aaf988977b18663f9a770ef77
9937a2bbe8dd6cc01ff3dd0ce32268e33c0ec1de
2023-08-17T07:07:04Z
c++
2023-08-21T00:43:49Z
shell/browser/native_window_views.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_NATIVE_WINDOW_VIEWS_H_ #define ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_VIEWS_H_ #include "shell/browser/native_window.h" #include <memory> #include <set> #include <string> #include "base/memory/raw_ptr.h" #include "shell/browser/ui/views/root_view.h" #include "ui/views/controls/webview/unhandled_keyboard_event_handler.h" #include "ui/views/widget/widget_observer.h" #if defined(USE_OZONE) #include "ui/ozone/buildflags.h" #if BUILDFLAG(OZONE_PLATFORM_X11) #define USE_OZONE_PLATFORM_X11 #endif #endif #if BUILDFLAG(IS_WIN) #include "base/win/scoped_gdi_object.h" #include "shell/browser/ui/win/taskbar_host.h" #endif namespace electron { class GlobalMenuBarX11; class WindowStateWatcher; #if defined(USE_OZONE_PLATFORM_X11) class EventDisabler; #endif #if BUILDFLAG(IS_WIN) gfx::Rect ScreenToDIPRect(HWND hwnd, const gfx::Rect& pixel_bounds); #endif class NativeWindowViews : public NativeWindow, public views::WidgetObserver, public ui::EventHandler { public: NativeWindowViews(const gin_helper::Dictionary& options, NativeWindow* parent); ~NativeWindowViews() override; // NativeWindow: void SetContentView(views::View* view) override; void Close() override; void CloseImmediately() override; void Focus(bool focus) override; bool IsFocused() override; void Show() override; void ShowInactive() override; void Hide() override; bool IsVisible() override; bool IsEnabled() override; void SetEnabled(bool enable) override; void Maximize() override; void Unmaximize() override; bool IsMaximized() override; void Minimize() override; void Restore() override; bool IsMinimized() override; void SetFullScreen(bool fullscreen) override; bool IsFullscreen() const override; void SetBounds(const gfx::Rect& bounds, bool animate) override; gfx::Rect GetBounds() override; gfx::Rect GetContentBounds() override; gfx::Size GetContentSize() override; gfx::Rect GetNormalBounds() override; SkColor GetBackgroundColor() override; void SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints) override; #if BUILDFLAG(IS_WIN) extensions::SizeConstraints GetContentSizeConstraints() const override; #endif void SetResizable(bool resizable) override; bool MoveAbove(const std::string& sourceId) override; void MoveTop() override; bool IsResizable() override; void SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) override; void SetMovable(bool movable) override; bool IsMovable() override; void SetMinimizable(bool minimizable) override; bool IsMinimizable() override; void SetMaximizable(bool maximizable) override; bool IsMaximizable() override; void SetFullScreenable(bool fullscreenable) override; bool IsFullScreenable() override; void SetClosable(bool closable) override; bool IsClosable() override; void SetAlwaysOnTop(ui::ZOrderLevel z_order, const std::string& level, int relativeLevel) override; ui::ZOrderLevel GetZOrderLevel() override; void Center() override; void Invalidate() override; void SetTitle(const std::string& title) override; std::string GetTitle() override; void FlashFrame(bool flash) override; void SetSkipTaskbar(bool skip) override; void SetExcludedFromShownWindowsMenu(bool excluded) override; bool IsExcludedFromShownWindowsMenu() override; void SetSimpleFullScreen(bool simple_fullscreen) override; bool IsSimpleFullScreen() override; void SetKiosk(bool kiosk) override; bool IsKiosk() override; bool IsTabletMode() const override; void SetBackgroundColor(SkColor color) override; void SetHasShadow(bool has_shadow) override; bool HasShadow() override; void SetOpacity(const double opacity) override; double GetOpacity() override; void SetIgnoreMouseEvents(bool ignore, bool forward) override; void SetContentProtection(bool enable) override; void SetFocusable(bool focusable) override; bool IsFocusable() override; void SetMenu(ElectronMenuModel* menu_model) override; void AddBrowserView(NativeBrowserView* browser_view) override; void RemoveBrowserView(NativeBrowserView* browser_view) override; void SetTopBrowserView(NativeBrowserView* browser_view) override; void SetParentWindow(NativeWindow* parent) override; gfx::NativeView GetNativeView() const override; gfx::NativeWindow GetNativeWindow() const override; void SetOverlayIcon(const gfx::Image& overlay, const std::string& description) override; void SetProgressBar(double progress, const ProgressState state) override; void SetAutoHideMenuBar(bool auto_hide) override; bool IsMenuBarAutoHide() override; void SetMenuBarVisibility(bool visible) override; bool IsMenuBarVisible() override; void SetBackgroundMaterial(const std::string& type) override; void SetVisibleOnAllWorkspaces(bool visible, bool visibleOnFullScreen, bool skipTransformProcessType) override; bool IsVisibleOnAllWorkspaces() override; void SetGTKDarkThemeEnabled(bool use_dark_theme) override; content::DesktopMediaID GetDesktopMediaID() const override; gfx::AcceleratedWidget GetAcceleratedWidget() const override; NativeWindowHandle GetNativeWindowHandle() const override; gfx::Rect ContentBoundsToWindowBounds(const gfx::Rect& bounds) const override; gfx::Rect WindowBoundsToContentBounds(const gfx::Rect& bounds) const override; void IncrementChildModals(); void DecrementChildModals(); #if BUILDFLAG(IS_WIN) // Catch-all message handling and filtering. Called before // HWNDMessageHandler's built-in handling, which may pre-empt some // expectations in Views/Aura if messages are consumed. Returns true if the // message was consumed by the delegate and should not be processed further // by the HWNDMessageHandler. In this case, |result| is returned. |result| is // not modified otherwise. bool PreHandleMSG(UINT message, WPARAM w_param, LPARAM l_param, LRESULT* result); void SetIcon(HICON small_icon, HICON app_icon); #elif BUILDFLAG(IS_LINUX) void SetIcon(const gfx::ImageSkia& icon); #endif #if BUILDFLAG(IS_WIN) TaskbarHost& taskbar_host() { return taskbar_host_; } #endif #if BUILDFLAG(IS_WIN) bool IsWindowControlsOverlayEnabled() const { return (title_bar_style_ == NativeWindowViews::TitleBarStyle::kHidden) && titlebar_overlay_; } SkColor overlay_button_color() const { return overlay_button_color_; } void set_overlay_button_color(SkColor color) { overlay_button_color_ = color; } SkColor overlay_symbol_color() const { return overlay_symbol_color_; } void set_overlay_symbol_color(SkColor color) { overlay_symbol_color_ = color; } #endif private: // views::WidgetObserver: void OnWidgetActivationChanged(views::Widget* widget, bool active) override; void OnWidgetBoundsChanged(views::Widget* widget, const gfx::Rect& bounds) override; void OnWidgetDestroying(views::Widget* widget) override; void OnWidgetDestroyed(views::Widget* widget) override; // views::WidgetDelegate: views::View* GetInitiallyFocusedView() override; bool CanMaximize() const override; bool CanMinimize() const override; std::u16string GetWindowTitle() const override; views::View* GetContentsView() override; bool ShouldDescendIntoChildForEventHandling( gfx::NativeView child, const gfx::Point& location) override; views::ClientView* CreateClientView(views::Widget* widget) override; std::unique_ptr<views::NonClientFrameView> CreateNonClientFrameView( views::Widget* widget) override; void OnWidgetMove() override; #if BUILDFLAG(IS_WIN) bool ExecuteWindowsCommand(int command_id) override; #endif #if BUILDFLAG(IS_WIN) void HandleSizeEvent(WPARAM w_param, LPARAM l_param); void ResetWindowControls(); void SetForwardMouseMessages(bool forward); static LRESULT CALLBACK SubclassProc(HWND hwnd, UINT msg, WPARAM w_param, LPARAM l_param, UINT_PTR subclass_id, DWORD_PTR ref_data); static LRESULT CALLBACK MouseHookProc(int n_code, WPARAM w_param, LPARAM l_param); #endif // Enable/disable: bool ShouldBeEnabled(); void SetEnabledInternal(bool enabled); // NativeWindow: void HandleKeyboardEvent( content::WebContents*, const content::NativeWebKeyboardEvent& event) override; // ui::EventHandler: void OnMouseEvent(ui::MouseEvent* event) override; // Returns the restore state for the window. ui::WindowShowState GetRestoredState(); // Maintain window placement. void MoveBehindTaskBarIfNeeded(); RootView root_view_{this}; // The view should be focused by default. raw_ptr<views::View> focused_view_ = nullptr; // The "resizable" flag on Linux is implemented by setting size constraints, // we need to make sure size constraints are restored when window becomes // resizable again. This is also used on Windows, to keep taskbar resize // events from resizing the window. extensions::SizeConstraints old_size_constraints_; #if defined(USE_OZONE) std::unique_ptr<GlobalMenuBarX11> global_menu_bar_; #endif #if defined(USE_OZONE_PLATFORM_X11) // To disable the mouse events. std::unique_ptr<EventDisabler> event_disabler_; #endif #if BUILDFLAG(IS_WIN) ui::WindowShowState last_window_state_; gfx::Rect last_normal_placement_bounds_; // In charge of running taskbar related APIs. TaskbarHost taskbar_host_; // Memoized version of a11y check bool checked_for_a11y_support_ = false; // Whether to show the WS_THICKFRAME style. bool thick_frame_ = true; // The bounds of window before maximize/fullscreen. gfx::Rect restore_bounds_; // The icons of window and taskbar. base::win::ScopedHICON window_icon_; base::win::ScopedHICON app_icon_; // The set of windows currently forwarding mouse messages. static std::set<NativeWindowViews*> forwarding_windows_; static HHOOK mouse_hook_; bool forwarding_mouse_messages_ = false; HWND legacy_window_ = NULL; bool layered_ = false; // Set to true if the window is always on top and behind the task bar. bool behind_task_bar_ = false; // Whether we want to set window placement without side effect. bool is_setting_window_placement_ = false; // Whether the window is currently being resized. bool is_resizing_ = false; // Whether the window is currently being moved. bool is_moving_ = false; absl::optional<gfx::Rect> pending_bounds_change_; // The color to use as the theme and symbol colors respectively for Window // Controls Overlay if enabled on Windows. SkColor overlay_button_color_; SkColor overlay_symbol_color_; #endif // Handles unhandled keyboard messages coming back from the renderer process. views::UnhandledKeyboardEventHandler keyboard_event_handler_; // Whether the menubar is visible before the window enters fullscreen bool menu_bar_visible_before_fullscreen_ = false; // Whether the window should be enabled based on user calls to SetEnabled() bool is_enabled_ = true; // How many modal children this window has; // used to determine enabled state unsigned int num_modal_children_ = 0; bool use_content_size_ = false; bool movable_ = true; bool resizable_ = true; bool maximizable_ = true; bool minimizable_ = true; bool fullscreenable_ = true; std::string title_; gfx::Size widget_size_; double opacity_ = 1.0; bool widget_destroyed_ = false; }; } // namespace electron #endif // ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_VIEWS_H_
closed
electron/electron
https://github.com/electron/electron
39,550
[Bug]: Thumbnail toolbar buttons are removed when Explorer is restarted
### 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 25.4.0 ### What operating system are you using? Windows ### Operating System Version Windows 10 Pro 22H2 (19045.3324) ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior After adding buttons with `BrowserWindow.setThumbarButtons`, thumbnail toolbar buttons persist across explorer restarts. ### Actual Behavior After adding buttons with `BrowserWindow.setThumbarButtons`, thumbnail toolbar buttons are removed when explorer is restarted. After that, you can't add buttons with `BrowserWindow.setThumbarButtons`. ### Testcase Gist URL _No response_ ### Additional Information You can restart Explorer by selecting the Explorer context menu from Task Manager.
https://github.com/electron/electron/issues/39550
https://github.com/electron/electron/pull/39551
95bf9d8adb33bc2aaf988977b18663f9a770ef77
9937a2bbe8dd6cc01ff3dd0ce32268e33c0ec1de
2023-08-17T07:07:04Z
c++
2023-08-21T00:43:49Z
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/browser/ui/views/win_frame_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()); NotifyWindowShow(); } } 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)); pending_bounds_change_.reset(); 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; } // If the user dragged or moved the window during one or more // calls to window.setBounds(), we want to apply the most recent // one once they are done with the move or resize operation. if (pending_bounds_change_.has_value()) { SetBounds(pending_bounds_change_.value(), false /* animate */); pending_bounds_change_.reset(); } 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)); pending_bounds_change_.reset(); 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) { if (last_window_state_ == ui::SHOW_STATE_MINIMIZED) NotifyWindowRestore(); last_window_state_ = ui::SHOW_STATE_MAXIMIZED; NotifyWindowMaximize(); ResetWindowControls(); } 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; } ResetWindowControls(); break; } } } void NativeWindowViews::ResetWindowControls() { // If a given window was minimized and has since been // unminimized (restored/maximized), ensure the WCO buttons // are reset to their default unpressed state. auto* ncv = widget()->non_client_view(); if (IsWindowControlsOverlayEnabled() && ncv) { auto* frame_view = static_cast<WinFrameView*>(ncv->frame_view()); frame_view->caption_button_container()->ResetWindowControls(); } } 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
39,550
[Bug]: Thumbnail toolbar buttons are removed when Explorer is restarted
### 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 25.4.0 ### What operating system are you using? Windows ### Operating System Version Windows 10 Pro 22H2 (19045.3324) ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior After adding buttons with `BrowserWindow.setThumbarButtons`, thumbnail toolbar buttons persist across explorer restarts. ### Actual Behavior After adding buttons with `BrowserWindow.setThumbarButtons`, thumbnail toolbar buttons are removed when explorer is restarted. After that, you can't add buttons with `BrowserWindow.setThumbarButtons`. ### Testcase Gist URL _No response_ ### Additional Information You can restart Explorer by selecting the Explorer context menu from Task Manager.
https://github.com/electron/electron/issues/39550
https://github.com/electron/electron/pull/39551
95bf9d8adb33bc2aaf988977b18663f9a770ef77
9937a2bbe8dd6cc01ff3dd0ce32268e33c0ec1de
2023-08-17T07:07:04Z
c++
2023-08-21T00:43:49Z
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 <dwmapi.h> #include <wrl/client.h> #endif #include <memory> #include <utility> #include <vector> #include "base/containers/contains.h" #include "base/memory/raw_ptr.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/ui/inspectable_web_contents.h" #include "shell/browser/ui/views/inspectable_web_contents_view_views.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/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 "shell/common/platform_util.h" #include "ui/views/widget/desktop_aura/desktop_native_widget_aura.h" #include "ui/views/window/native_frame_view.h" #if defined(USE_OZONE) #include "shell/browser/ui/views/global_menu_bar_x11.h" #include "shell/browser/ui/x/event_disabler.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" #include "ui/ozone/public/ozone_platform.h" #endif #elif BUILDFLAG(IS_WIN) #include "base/win/win_util.h" #include "base/win/windows_version.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" #include "ui/gfx/win/msg_util.h" #endif namespace electron { #if BUILDFLAG(IS_WIN) DWM_SYSTEMBACKDROP_TYPE GetBackdropFromString(const std::string& material) { if (material == "none") { return DWMSBT_NONE; } else if (material == "acrylic") { return DWMSBT_TRANSIENTWINDOW; } else if (material == "mica") { return DWMSBT_MAINWINDOW; } else if (material == "tabbed") { return DWMSBT_TABBEDWINDOW; } return DWMSBT_AUTO; } // 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; } // Chromium uses a buggy implementation that converts content rect to window // rect when calculating min/max size, we should use the same implementation // when passing min/max size so we can get correct results. gfx::Size WindowSizeToContentSizeBuggy(HWND hwnd, const gfx::Size& size) { // Calculate the size of window frame, using same code with the // HWNDMessageHandler::OnGetMinMaxInfo method. // The pitfall is, when window is minimized the calculated window frame size // will be different from other states. RECT client_rect, rect; GetClientRect(hwnd, &client_rect); GetWindowRect(hwnd, &rect); CR_DEFLATE_RECT(&rect, &client_rect); // Convert DIP size to pixel size, do calculation and then return DIP size. gfx::Rect screen_rect = DIPToScreenRect(hwnd, gfx::Rect(size)); gfx::Size screen_client_size(screen_rect.width() - (rect.right - rect.left), screen_rect.height() - (rect.bottom - rect.top)); return ScreenToDIPRect(hwnd, gfx::Rect(screen_client_size)).size(); } #endif #if defined(USE_OZONE) bool CreateGlobalMenuBar() { return ui::OzonePlatform::GetInstance() ->GetPlatformProperties() .supports_global_application_menus; } #endif #if defined(USE_OZONE_PLATFORM_X11) bool IsX11() { return ui::OzonePlatform::GetInstance() ->GetPlatformProperties() .electron_can_call_x11; } #endif class NativeWindowClientView : public views::ClientView { public: NativeWindowClientView(views::Widget* widget, views::View* root_view, NativeWindowViews* window) : views::ClientView{widget, root_view}, window_{raw_ref<NativeWindowViews>::from_ptr(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: const raw_ref<NativeWindowViews> window_; }; } // namespace NativeWindowViews::NativeWindowViews(const gin_helper::Dictionary& options, NativeWindow* parent) : NativeWindow(options, parent) { 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; // Set Wayland application ID. params.wayland_app_id = platform_util::GetXdgAppId(); 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 BUILDFLAG(IS_LINUX) // 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); } if (parent) SetParentWindow(parent); #endif #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { // 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; // 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_) frame_style |= WS_THICKFRAME; if (minimizable_) frame_style |= WS_MINIMIZEBOX; if (maximizable_) frame_style |= WS_MAXIMIZEBOX; // We should not show a frame for transparent window. if (!thick_frame_) frame_style &= ~(WS_THICKFRAME | 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_OZONE_PLATFORM_X11) if (IsX11()) { 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_OZONE) if (global_menu_bar_) global_menu_bar_->OnWindowMapped(); #endif #if defined(USE_OZONE_PLATFORM_X11) // On X11, setting Z order before showing the window doesn't take effect, // so we have to call it again. if (IsX11()) widget()->SetZOrderLevel(widget()->GetZOrderLevel()); #endif } void NativeWindowViews::ShowInactive() { widget()->ShowInactive(); NotifyWindowShow(); #if defined(USE_OZONE) 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_OZONE) 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() { #if BUILDFLAG(IS_WIN) // widget()->IsVisible() calls ::IsWindowVisible, which returns non-zero if a // window or any of its parent windows are visible. We want to only check the // current window. bool visible = ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_VISIBLE; // WS_VISIBLE is true even if a window is miminized - explicitly check that. return visible && !IsMinimized(); #else return widget()->IsVisible(); #endif } bool NativeWindowViews::IsEnabled() { #if BUILDFLAG(IS_WIN) return ::IsWindowEnabled(GetAcceleratedWidget()); #elif BUILDFLAG(IS_LINUX) #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) 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_OZONE_PLATFORM_X11) if (IsX11()) { 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()); NotifyWindowShow(); } } #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() && !IsMinimized()) { // 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) { menu_bar_visible_before_fullscreen_ = IsMenuBarVisible(); SetMenuBarVisibility(false); } else { SetMenuBarVisibility(!IsMenuBarAutoHide() && menu_bar_visible_before_fullscreen_); menu_bar_visible_before_fullscreen_ = false; } #endif } bool NativeWindowViews::IsFullscreen() const { return widget()->IsFullscreen(); } void NativeWindowViews::SetBounds(const gfx::Rect& bounds, bool animate) { #if BUILDFLAG(IS_WIN) if (is_moving_ || is_resizing_) { pending_bounds_change_ = bounds; } #endif #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() { #if BUILDFLAG(IS_WIN) if (IsMaximized() && transparent()) return restore_bounds_; #endif 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; } #if BUILDFLAG(IS_WIN) // This override does almost the same with its parent, except that it uses // the WindowSizeToContentSizeBuggy method to convert window size to content // size. See the comment of the method for the reason behind this. extensions::SizeConstraints NativeWindowViews::GetContentSizeConstraints() const { if (content_size_constraints_) return *content_size_constraints_; if (!size_constraints_) return extensions::SizeConstraints(); extensions::SizeConstraints constraints; if (size_constraints_->HasMaximumSize()) { constraints.set_maximum_size(WindowSizeToContentSizeBuggy( GetAcceleratedWidget(), size_constraints_->GetMaximumSize())); } if (size_constraints_->HasMinimumSize()) { constraints.set_minimum_size(WindowSizeToContentSizeBuggy( GetAcceleratedWidget(), size_constraints_->GetMinimumSize())); } return constraints; } #endif 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_OZONE_PLATFORM_X11) if (IsX11()) { 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_OZONE_PLATFORM_X11) if (IsX11()) 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); if (IsWindowControlsOverlayEnabled()) { auto* frame_view = static_cast<WinFrameView*>(widget()->non_client_view()->frame_view()); frame_view->caption_button_container()->UpdateButtons(); } #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); if (IsWindowControlsOverlayEnabled()) { auto* frame_view = static_cast<WinFrameView*>(widget()->non_client_view()->frame_view()); frame_view->caption_button_container()->UpdateButtons(); } #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); } if (IsWindowControlsOverlayEnabled()) { auto* frame_view = static_cast<WinFrameView*>(widget()->non_client_view()->frame_view()); frame_view->caption_button_container()->UpdateButtons(); } #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()); } #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 = std::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_OZONE_PLATFORM_X11) if (IsX11()) { 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_OZONE) // 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 (CreateGlobalMenuBar() && 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_OZONE_PLATFORM_X11) if (IsX11()) 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::SetBackgroundMaterial(const std::string& material) { #if BUILDFLAG(IS_WIN) // DWMWA_USE_HOSTBACKDROPBRUSH is only supported on Windows 11 22H2 and up. if (base::win::GetVersion() < base::win::Version::WIN11_22H2) return; DWM_SYSTEMBACKDROP_TYPE backdrop_type = GetBackdropFromString(material); HRESULT result = DwmSetWindowAttribute(GetAcceleratedWidget(), DWMWA_SYSTEMBACKDROP_TYPE, &backdrop_type, sizeof(backdrop_type)); if (FAILED(result)) LOG(WARNING) << "Failed to set background material to " << material; #endif } void NativeWindowViews::SetVisibleOnAllWorkspaces( bool visible, bool visibleOnFullScreen, bool skipTransformProcessType) { widget()->SetVisibleOnAllWorkspaces(visible); } bool NativeWindowViews::IsVisibleOnAllWorkspaces() { #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { // 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 base::Contains(wm_states, sticky_atom); } #endif return false; } 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; } #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 blurred. 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_; } bool NativeWindowViews::ShouldDescendIntoChildForEventHandling( gfx::NativeView child, const gfx::Point& location) { return NonClientHitTest(location) == HTNOWHERE; } views::ClientView* NativeWindowViews::CreateClientView(views::Widget* widget) { return new NativeWindowClientView{widget, GetContentsView(), 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
39,550
[Bug]: Thumbnail toolbar buttons are removed when Explorer is restarted
### 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 25.4.0 ### What operating system are you using? Windows ### Operating System Version Windows 10 Pro 22H2 (19045.3324) ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior After adding buttons with `BrowserWindow.setThumbarButtons`, thumbnail toolbar buttons persist across explorer restarts. ### Actual Behavior After adding buttons with `BrowserWindow.setThumbarButtons`, thumbnail toolbar buttons are removed when explorer is restarted. After that, you can't add buttons with `BrowserWindow.setThumbarButtons`. ### Testcase Gist URL _No response_ ### Additional Information You can restart Explorer by selecting the Explorer context menu from Task Manager.
https://github.com/electron/electron/issues/39550
https://github.com/electron/electron/pull/39551
95bf9d8adb33bc2aaf988977b18663f9a770ef77
9937a2bbe8dd6cc01ff3dd0ce32268e33c0ec1de
2023-08-17T07:07:04Z
c++
2023-08-21T00:43:49Z
shell/browser/native_window_views.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_NATIVE_WINDOW_VIEWS_H_ #define ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_VIEWS_H_ #include "shell/browser/native_window.h" #include <memory> #include <set> #include <string> #include "base/memory/raw_ptr.h" #include "shell/browser/ui/views/root_view.h" #include "ui/views/controls/webview/unhandled_keyboard_event_handler.h" #include "ui/views/widget/widget_observer.h" #if defined(USE_OZONE) #include "ui/ozone/buildflags.h" #if BUILDFLAG(OZONE_PLATFORM_X11) #define USE_OZONE_PLATFORM_X11 #endif #endif #if BUILDFLAG(IS_WIN) #include "base/win/scoped_gdi_object.h" #include "shell/browser/ui/win/taskbar_host.h" #endif namespace electron { class GlobalMenuBarX11; class WindowStateWatcher; #if defined(USE_OZONE_PLATFORM_X11) class EventDisabler; #endif #if BUILDFLAG(IS_WIN) gfx::Rect ScreenToDIPRect(HWND hwnd, const gfx::Rect& pixel_bounds); #endif class NativeWindowViews : public NativeWindow, public views::WidgetObserver, public ui::EventHandler { public: NativeWindowViews(const gin_helper::Dictionary& options, NativeWindow* parent); ~NativeWindowViews() override; // NativeWindow: void SetContentView(views::View* view) override; void Close() override; void CloseImmediately() override; void Focus(bool focus) override; bool IsFocused() override; void Show() override; void ShowInactive() override; void Hide() override; bool IsVisible() override; bool IsEnabled() override; void SetEnabled(bool enable) override; void Maximize() override; void Unmaximize() override; bool IsMaximized() override; void Minimize() override; void Restore() override; bool IsMinimized() override; void SetFullScreen(bool fullscreen) override; bool IsFullscreen() const override; void SetBounds(const gfx::Rect& bounds, bool animate) override; gfx::Rect GetBounds() override; gfx::Rect GetContentBounds() override; gfx::Size GetContentSize() override; gfx::Rect GetNormalBounds() override; SkColor GetBackgroundColor() override; void SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints) override; #if BUILDFLAG(IS_WIN) extensions::SizeConstraints GetContentSizeConstraints() const override; #endif void SetResizable(bool resizable) override; bool MoveAbove(const std::string& sourceId) override; void MoveTop() override; bool IsResizable() override; void SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) override; void SetMovable(bool movable) override; bool IsMovable() override; void SetMinimizable(bool minimizable) override; bool IsMinimizable() override; void SetMaximizable(bool maximizable) override; bool IsMaximizable() override; void SetFullScreenable(bool fullscreenable) override; bool IsFullScreenable() override; void SetClosable(bool closable) override; bool IsClosable() override; void SetAlwaysOnTop(ui::ZOrderLevel z_order, const std::string& level, int relativeLevel) override; ui::ZOrderLevel GetZOrderLevel() override; void Center() override; void Invalidate() override; void SetTitle(const std::string& title) override; std::string GetTitle() override; void FlashFrame(bool flash) override; void SetSkipTaskbar(bool skip) override; void SetExcludedFromShownWindowsMenu(bool excluded) override; bool IsExcludedFromShownWindowsMenu() override; void SetSimpleFullScreen(bool simple_fullscreen) override; bool IsSimpleFullScreen() override; void SetKiosk(bool kiosk) override; bool IsKiosk() override; bool IsTabletMode() const override; void SetBackgroundColor(SkColor color) override; void SetHasShadow(bool has_shadow) override; bool HasShadow() override; void SetOpacity(const double opacity) override; double GetOpacity() override; void SetIgnoreMouseEvents(bool ignore, bool forward) override; void SetContentProtection(bool enable) override; void SetFocusable(bool focusable) override; bool IsFocusable() override; void SetMenu(ElectronMenuModel* menu_model) override; void AddBrowserView(NativeBrowserView* browser_view) override; void RemoveBrowserView(NativeBrowserView* browser_view) override; void SetTopBrowserView(NativeBrowserView* browser_view) override; void SetParentWindow(NativeWindow* parent) override; gfx::NativeView GetNativeView() const override; gfx::NativeWindow GetNativeWindow() const override; void SetOverlayIcon(const gfx::Image& overlay, const std::string& description) override; void SetProgressBar(double progress, const ProgressState state) override; void SetAutoHideMenuBar(bool auto_hide) override; bool IsMenuBarAutoHide() override; void SetMenuBarVisibility(bool visible) override; bool IsMenuBarVisible() override; void SetBackgroundMaterial(const std::string& type) override; void SetVisibleOnAllWorkspaces(bool visible, bool visibleOnFullScreen, bool skipTransformProcessType) override; bool IsVisibleOnAllWorkspaces() override; void SetGTKDarkThemeEnabled(bool use_dark_theme) override; content::DesktopMediaID GetDesktopMediaID() const override; gfx::AcceleratedWidget GetAcceleratedWidget() const override; NativeWindowHandle GetNativeWindowHandle() const override; gfx::Rect ContentBoundsToWindowBounds(const gfx::Rect& bounds) const override; gfx::Rect WindowBoundsToContentBounds(const gfx::Rect& bounds) const override; void IncrementChildModals(); void DecrementChildModals(); #if BUILDFLAG(IS_WIN) // Catch-all message handling and filtering. Called before // HWNDMessageHandler's built-in handling, which may pre-empt some // expectations in Views/Aura if messages are consumed. Returns true if the // message was consumed by the delegate and should not be processed further // by the HWNDMessageHandler. In this case, |result| is returned. |result| is // not modified otherwise. bool PreHandleMSG(UINT message, WPARAM w_param, LPARAM l_param, LRESULT* result); void SetIcon(HICON small_icon, HICON app_icon); #elif BUILDFLAG(IS_LINUX) void SetIcon(const gfx::ImageSkia& icon); #endif #if BUILDFLAG(IS_WIN) TaskbarHost& taskbar_host() { return taskbar_host_; } #endif #if BUILDFLAG(IS_WIN) bool IsWindowControlsOverlayEnabled() const { return (title_bar_style_ == NativeWindowViews::TitleBarStyle::kHidden) && titlebar_overlay_; } SkColor overlay_button_color() const { return overlay_button_color_; } void set_overlay_button_color(SkColor color) { overlay_button_color_ = color; } SkColor overlay_symbol_color() const { return overlay_symbol_color_; } void set_overlay_symbol_color(SkColor color) { overlay_symbol_color_ = color; } #endif private: // views::WidgetObserver: void OnWidgetActivationChanged(views::Widget* widget, bool active) override; void OnWidgetBoundsChanged(views::Widget* widget, const gfx::Rect& bounds) override; void OnWidgetDestroying(views::Widget* widget) override; void OnWidgetDestroyed(views::Widget* widget) override; // views::WidgetDelegate: views::View* GetInitiallyFocusedView() override; bool CanMaximize() const override; bool CanMinimize() const override; std::u16string GetWindowTitle() const override; views::View* GetContentsView() override; bool ShouldDescendIntoChildForEventHandling( gfx::NativeView child, const gfx::Point& location) override; views::ClientView* CreateClientView(views::Widget* widget) override; std::unique_ptr<views::NonClientFrameView> CreateNonClientFrameView( views::Widget* widget) override; void OnWidgetMove() override; #if BUILDFLAG(IS_WIN) bool ExecuteWindowsCommand(int command_id) override; #endif #if BUILDFLAG(IS_WIN) void HandleSizeEvent(WPARAM w_param, LPARAM l_param); void ResetWindowControls(); void SetForwardMouseMessages(bool forward); static LRESULT CALLBACK SubclassProc(HWND hwnd, UINT msg, WPARAM w_param, LPARAM l_param, UINT_PTR subclass_id, DWORD_PTR ref_data); static LRESULT CALLBACK MouseHookProc(int n_code, WPARAM w_param, LPARAM l_param); #endif // Enable/disable: bool ShouldBeEnabled(); void SetEnabledInternal(bool enabled); // NativeWindow: void HandleKeyboardEvent( content::WebContents*, const content::NativeWebKeyboardEvent& event) override; // ui::EventHandler: void OnMouseEvent(ui::MouseEvent* event) override; // Returns the restore state for the window. ui::WindowShowState GetRestoredState(); // Maintain window placement. void MoveBehindTaskBarIfNeeded(); RootView root_view_{this}; // The view should be focused by default. raw_ptr<views::View> focused_view_ = nullptr; // The "resizable" flag on Linux is implemented by setting size constraints, // we need to make sure size constraints are restored when window becomes // resizable again. This is also used on Windows, to keep taskbar resize // events from resizing the window. extensions::SizeConstraints old_size_constraints_; #if defined(USE_OZONE) std::unique_ptr<GlobalMenuBarX11> global_menu_bar_; #endif #if defined(USE_OZONE_PLATFORM_X11) // To disable the mouse events. std::unique_ptr<EventDisabler> event_disabler_; #endif #if BUILDFLAG(IS_WIN) ui::WindowShowState last_window_state_; gfx::Rect last_normal_placement_bounds_; // In charge of running taskbar related APIs. TaskbarHost taskbar_host_; // Memoized version of a11y check bool checked_for_a11y_support_ = false; // Whether to show the WS_THICKFRAME style. bool thick_frame_ = true; // The bounds of window before maximize/fullscreen. gfx::Rect restore_bounds_; // The icons of window and taskbar. base::win::ScopedHICON window_icon_; base::win::ScopedHICON app_icon_; // The set of windows currently forwarding mouse messages. static std::set<NativeWindowViews*> forwarding_windows_; static HHOOK mouse_hook_; bool forwarding_mouse_messages_ = false; HWND legacy_window_ = NULL; bool layered_ = false; // Set to true if the window is always on top and behind the task bar. bool behind_task_bar_ = false; // Whether we want to set window placement without side effect. bool is_setting_window_placement_ = false; // Whether the window is currently being resized. bool is_resizing_ = false; // Whether the window is currently being moved. bool is_moving_ = false; absl::optional<gfx::Rect> pending_bounds_change_; // The color to use as the theme and symbol colors respectively for Window // Controls Overlay if enabled on Windows. SkColor overlay_button_color_; SkColor overlay_symbol_color_; #endif // Handles unhandled keyboard messages coming back from the renderer process. views::UnhandledKeyboardEventHandler keyboard_event_handler_; // Whether the menubar is visible before the window enters fullscreen bool menu_bar_visible_before_fullscreen_ = false; // Whether the window should be enabled based on user calls to SetEnabled() bool is_enabled_ = true; // How many modal children this window has; // used to determine enabled state unsigned int num_modal_children_ = 0; bool use_content_size_ = false; bool movable_ = true; bool resizable_ = true; bool maximizable_ = true; bool minimizable_ = true; bool fullscreenable_ = true; std::string title_; gfx::Size widget_size_; double opacity_ = 1.0; bool widget_destroyed_ = false; }; } // namespace electron #endif // ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_VIEWS_H_
closed
electron/electron
https://github.com/electron/electron
39,550
[Bug]: Thumbnail toolbar buttons are removed when Explorer is restarted
### 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 25.4.0 ### What operating system are you using? Windows ### Operating System Version Windows 10 Pro 22H2 (19045.3324) ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior After adding buttons with `BrowserWindow.setThumbarButtons`, thumbnail toolbar buttons persist across explorer restarts. ### Actual Behavior After adding buttons with `BrowserWindow.setThumbarButtons`, thumbnail toolbar buttons are removed when explorer is restarted. After that, you can't add buttons with `BrowserWindow.setThumbarButtons`. ### Testcase Gist URL _No response_ ### Additional Information You can restart Explorer by selecting the Explorer context menu from Task Manager.
https://github.com/electron/electron/issues/39550
https://github.com/electron/electron/pull/39551
95bf9d8adb33bc2aaf988977b18663f9a770ef77
9937a2bbe8dd6cc01ff3dd0ce32268e33c0ec1de
2023-08-17T07:07:04Z
c++
2023-08-21T00:43:49Z
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/browser/ui/views/win_frame_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()); NotifyWindowShow(); } } 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)); pending_bounds_change_.reset(); 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; } // If the user dragged or moved the window during one or more // calls to window.setBounds(), we want to apply the most recent // one once they are done with the move or resize operation. if (pending_bounds_change_.has_value()) { SetBounds(pending_bounds_change_.value(), false /* animate */); pending_bounds_change_.reset(); } 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)); pending_bounds_change_.reset(); 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) { if (last_window_state_ == ui::SHOW_STATE_MINIMIZED) NotifyWindowRestore(); last_window_state_ = ui::SHOW_STATE_MAXIMIZED; NotifyWindowMaximize(); ResetWindowControls(); } 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; } ResetWindowControls(); break; } } } void NativeWindowViews::ResetWindowControls() { // If a given window was minimized and has since been // unminimized (restored/maximized), ensure the WCO buttons // are reset to their default unpressed state. auto* ncv = widget()->non_client_view(); if (IsWindowControlsOverlayEnabled() && ncv) { auto* frame_view = static_cast<WinFrameView*>(ncv->frame_view()); frame_view->caption_button_container()->ResetWindowControls(); } } 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
38,161
[Feature Request]: Allow commonjs2 scripts as sandboxed preload scripts
### 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. ### Problem Description When calling a preload script in sandboxed mode, `module` is not defined. This makes code that assigns `module.exports` crash with an error like "ReferenceError: module is not defined". This is made even more confusing since electron also emits an error "Unable to load preload script" which implies that the script was not found, and not just partly executed. This is a problem because many commonjs modules assign the `module.exports` property, as per [Node's documentation](https://nodejs.org/api/modules.html#the-module-object): > The `module.exports` object is created by the `Module` system. Sometimes this is not acceptable; many want their module to be an instance of some class. To do this, assign the desired export object to `module.exports`. Problematic commonjs scripts are created by: - `webpack` in ['commonjs2' mode](https://webpack.js.org/configuration/output/#type-commonjs2), which is the recommended format (see, e.g. Quasar https://github.com/quasarframework/quasar/issues/11759) - `esbuild` - `parcel` It seems that `rollup`, `swc`, and `typescript` do not reassign `module.exports` and so are not affected. ### Proposed Solution - Pass a `module` object with a mutable `exports` property to the [preload wrapper](https://github.com/electron/electron/blob/a8c0ed890f61664156886356ecb6ab9f73c69cf1/lib/sandboxed_renderer/init.ts#L105-L107). ### Alternatives Considered - Load the preload script as an ESM module - Use a module loader (e.g. an actual call to `require`) instead of interpolating the preload script into an `eval` call. ### Additional Information I'm not sure if this should be regarded as a feature request or a bug. It's quite surprising behavior and probably not intentional, so I'm leaning toward bug.
https://github.com/electron/electron/issues/38161
https://github.com/electron/electron/pull/39484
90865fa97d577105987d23db017c0332029228f6
3102a257af400e8b9bdddf4295d901007c65a2d6
2023-05-03T07:01:40Z
c++
2023-08-22T04:43:08Z
lib/sandboxed_renderer/init.ts
import * as events from 'events'; import { IPC_MESSAGES } from '@electron/internal/common/ipc-messages'; import type * as ipcRendererUtilsModule from '@electron/internal/renderer/ipc-renderer-internal-utils'; import type * as ipcRendererInternalModule from '@electron/internal/renderer/ipc-renderer-internal'; declare const binding: { get: (name: string) => any; process: NodeJS.Process; createPreloadScript: (src: string) => Function }; const { EventEmitter } = events; process._linkedBinding = binding.get; const v8Util = process._linkedBinding('electron_common_v8_util'); // Expose Buffer shim as a hidden value. This is used by C++ code to // deserialize Buffer instances sent from browser process. v8Util.setHiddenValue(global, 'Buffer', Buffer); // The process object created by webpack is not an event emitter, fix it so // the API is more compatible with non-sandboxed renderers. for (const prop of Object.keys(EventEmitter.prototype) as (keyof typeof process)[]) { if (Object.hasOwn(process, prop)) { delete process[prop]; } } Object.setPrototypeOf(process, EventEmitter.prototype); const { ipcRendererInternal } = require('@electron/internal/renderer/ipc-renderer-internal') as typeof ipcRendererInternalModule; const ipcRendererUtils = require('@electron/internal/renderer/ipc-renderer-internal-utils') as typeof ipcRendererUtilsModule; const { preloadScripts, process: processProps } = ipcRendererUtils.invokeSync<{ preloadScripts: { preloadPath: string; preloadSrc: string | null; preloadError: null | Error; }[]; process: NodeJS.Process; }>(IPC_MESSAGES.BROWSER_SANDBOX_LOAD); const electron = require('electron'); const loadedModules = new Map<string, any>([ ['electron', electron], ['electron/common', electron], ['electron/renderer', electron], ['events', events], ['node:events', events] ]); const loadableModules = new Map<string, Function>([ ['timers', () => require('timers')], ['node:timers', () => require('timers')], ['url', () => require('url')], ['node:url', () => require('url')] ]); // Pass different process object to the preload script. const preloadProcess: NodeJS.Process = new EventEmitter() as any; // InvokeEmitProcessEvent in ElectronSandboxedRendererClient will look for this v8Util.setHiddenValue(global, 'emit-process-event', (event: string) => { (process as events.EventEmitter).emit(event); (preloadProcess as events.EventEmitter).emit(event); }); Object.assign(preloadProcess, binding.process); Object.assign(preloadProcess, processProps); Object.assign(process, binding.process); Object.assign(process, processProps); process.getProcessMemoryInfo = preloadProcess.getProcessMemoryInfo = () => { return ipcRendererInternal.invoke<Electron.ProcessMemoryInfo>(IPC_MESSAGES.BROWSER_GET_PROCESS_MEMORY_INFO); }; Object.defineProperty(preloadProcess, 'noDeprecation', { get () { return process.noDeprecation; }, set (value) { process.noDeprecation = value; } }); // This is the `require` function that will be visible to the preload script function preloadRequire (module: string) { if (loadedModules.has(module)) { return loadedModules.get(module); } if (loadableModules.has(module)) { const loadedModule = loadableModules.get(module)!(); loadedModules.set(module, loadedModule); return loadedModule; } throw new Error(`module not found: ${module}`); } // Process command line arguments. const { hasSwitch } = process._linkedBinding('electron_common_command_line'); // Similar to nodes --expose-internals flag, this exposes _linkedBinding so // that tests can call it to get access to some test only bindings if (hasSwitch('unsafely-expose-electron-internals-for-testing')) { preloadProcess._linkedBinding = process._linkedBinding; } // Common renderer initialization require('@electron/internal/renderer/common-init'); // Wrap the script into a function executed in global scope. It won't have // access to the current scope, so we'll expose a few objects as arguments: // // - `require`: The `preloadRequire` function // - `process`: The `preloadProcess` object // - `Buffer`: Shim of `Buffer` implementation // - `global`: The window object, which is aliased to `global` by webpack. function runPreloadScript (preloadSrc: string) { const preloadWrapperSrc = `(function(require, process, Buffer, global, setImmediate, clearImmediate, exports) { ${preloadSrc} })`; // eval in window scope const preloadFn = binding.createPreloadScript(preloadWrapperSrc); const { setImmediate, clearImmediate } = require('timers'); preloadFn(preloadRequire, preloadProcess, Buffer, global, setImmediate, clearImmediate, {}); } for (const { preloadPath, preloadSrc, preloadError } of preloadScripts) { try { if (preloadSrc) { runPreloadScript(preloadSrc); } else if (preloadError) { throw preloadError; } } catch (error) { console.error(`Unable to load preload script: ${preloadPath}`); console.error(error); ipcRendererInternal.send(IPC_MESSAGES.BROWSER_PRELOAD_ERROR, preloadPath, error); } }
closed
electron/electron
https://github.com/electron/electron
38,161
[Feature Request]: Allow commonjs2 scripts as sandboxed preload scripts
### 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. ### Problem Description When calling a preload script in sandboxed mode, `module` is not defined. This makes code that assigns `module.exports` crash with an error like "ReferenceError: module is not defined". This is made even more confusing since electron also emits an error "Unable to load preload script" which implies that the script was not found, and not just partly executed. This is a problem because many commonjs modules assign the `module.exports` property, as per [Node's documentation](https://nodejs.org/api/modules.html#the-module-object): > The `module.exports` object is created by the `Module` system. Sometimes this is not acceptable; many want their module to be an instance of some class. To do this, assign the desired export object to `module.exports`. Problematic commonjs scripts are created by: - `webpack` in ['commonjs2' mode](https://webpack.js.org/configuration/output/#type-commonjs2), which is the recommended format (see, e.g. Quasar https://github.com/quasarframework/quasar/issues/11759) - `esbuild` - `parcel` It seems that `rollup`, `swc`, and `typescript` do not reassign `module.exports` and so are not affected. ### Proposed Solution - Pass a `module` object with a mutable `exports` property to the [preload wrapper](https://github.com/electron/electron/blob/a8c0ed890f61664156886356ecb6ab9f73c69cf1/lib/sandboxed_renderer/init.ts#L105-L107). ### Alternatives Considered - Load the preload script as an ESM module - Use a module loader (e.g. an actual call to `require`) instead of interpolating the preload script into an `eval` call. ### Additional Information I'm not sure if this should be regarded as a feature request or a bug. It's quite surprising behavior and probably not intentional, so I'm leaning toward bug.
https://github.com/electron/electron/issues/38161
https://github.com/electron/electron/pull/39484
90865fa97d577105987d23db017c0332029228f6
3102a257af400e8b9bdddf4295d901007c65a2d6
2023-05-03T07:01:40Z
c++
2023-08-22T04:43:08Z
spec/chromium-spec.ts
import { expect } from 'chai'; import { BrowserWindow, WebContents, webFrameMain, session, ipcMain, app, protocol, webContents } from 'electron/main'; import { closeAllWindows } from './lib/window-helpers'; import * as https from 'node:https'; import * as http from 'node:http'; import * as path from 'node:path'; import * as fs from 'node:fs'; import * as url from 'node:url'; import * as ChildProcess from 'node:child_process'; import { EventEmitter, once } from 'node:events'; import { promisify } from 'node:util'; import { ifit, ifdescribe, defer, itremote, listen } from './lib/spec-helpers'; import { PipeTransport } from './pipe-transport'; import * as ws from 'ws'; import { setTimeout } from 'node:timers/promises'; const features = process._linkedBinding('electron_common_features'); const fixturesPath = path.resolve(__dirname, 'fixtures'); const certPath = path.join(fixturesPath, 'certificates'); describe('reporting api', () => { it('sends a report for an intervention', async () => { const reporting = new EventEmitter(); // The Reporting API only works on https with valid certs. To dodge having // to set up a trusted certificate, hack the validator. session.defaultSession.setCertificateVerifyProc((req, cb) => { cb(0); }); const options = { key: fs.readFileSync(path.join(certPath, 'server.key')), cert: fs.readFileSync(path.join(certPath, 'server.pem')), ca: [ fs.readFileSync(path.join(certPath, 'rootCA.pem')), fs.readFileSync(path.join(certPath, 'intermediateCA.pem')) ], requestCert: true, rejectUnauthorized: false }; const server = https.createServer(options, (req, res) => { if (req.url?.endsWith('report')) { let data = ''; req.on('data', (d) => { data += d.toString('utf-8'); }); req.on('end', () => { reporting.emit('report', JSON.parse(data)); }); } const { port } = server.address() as any; res.setHeader('Reporting-Endpoints', `default="https://localhost:${port}/report"`); res.setHeader('Content-Type', 'text/html'); res.end('<script>window.navigator.vibrate(1)</script>'); }); await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve)); const bw = new BrowserWindow({ show: false }); try { const reportGenerated = once(reporting, 'report'); await bw.loadURL(`https://localhost:${(server.address() as any).port}/a`); const [reports] = await reportGenerated; expect(reports).to.be.an('array').with.lengthOf(1); const { type, url, body } = reports[0]; expect(type).to.equal('intervention'); expect(url).to.equal(url); expect(body.id).to.equal('NavigatorVibrate'); expect(body.message).to.match(/Blocked call to navigator.vibrate because user hasn't tapped on the frame or any embedded frame yet/); } finally { bw.destroy(); server.close(); } }); }); describe('window.postMessage', () => { afterEach(async () => { await closeAllWindows(); }); it('sets the source and origin correctly', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadURL(`file://${fixturesPath}/pages/window-open-postMessage-driver.html`); const [, message] = await once(ipcMain, 'complete'); expect(message.data).to.equal('testing'); expect(message.origin).to.equal('file://'); expect(message.sourceEqualsOpener).to.equal(true); expect(message.eventOrigin).to.equal('file://'); }); }); describe('focus handling', () => { let webviewContents: WebContents; let w: BrowserWindow; beforeEach(async () => { w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true, webviewTag: true, contextIsolation: false } }); const webviewReady = once(w.webContents, 'did-attach-webview') as Promise<[any, WebContents]>; await w.loadFile(path.join(fixturesPath, 'pages', 'tab-focus-loop-elements.html')); const [, wvContents] = await webviewReady; webviewContents = wvContents; await once(webviewContents, 'did-finish-load'); w.focus(); }); afterEach(() => { webviewContents = null as unknown as WebContents; w.destroy(); w = null as unknown as BrowserWindow; }); const expectFocusChange = async () => { const [, focusedElementId] = await once(ipcMain, 'focus-changed'); return focusedElementId; }; describe('a TAB press', () => { const tabPressEvent: any = { type: 'keyDown', keyCode: 'Tab' }; it('moves focus to the next focusable item', async () => { let focusChange = expectFocusChange(); w.webContents.sendInputEvent(tabPressEvent); let focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-element-1', `should start focused in element-1, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); w.webContents.sendInputEvent(tabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-element-2', `focus should've moved to element-2, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); w.webContents.sendInputEvent(tabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-wv-element-1', `focus should've moved to the webview's element-1, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); webviewContents.sendInputEvent(tabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-wv-element-2', `focus should've moved to the webview's element-2, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); webviewContents.sendInputEvent(tabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-element-3', `focus should've moved to element-3, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); w.webContents.sendInputEvent(tabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-element-1', `focus should've looped back to element-1, it's instead in ${focusedElementId}`); }); }); describe('a SHIFT + TAB press', () => { const shiftTabPressEvent: any = { type: 'keyDown', modifiers: ['Shift'], keyCode: 'Tab' }; it('moves focus to the previous focusable item', async () => { let focusChange = expectFocusChange(); w.webContents.sendInputEvent(shiftTabPressEvent); let focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-element-3', `should start focused in element-3, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); w.webContents.sendInputEvent(shiftTabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-wv-element-2', `focus should've moved to the webview's element-2, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); webviewContents.sendInputEvent(shiftTabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-wv-element-1', `focus should've moved to the webview's element-1, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); webviewContents.sendInputEvent(shiftTabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-element-2', `focus should've moved to element-2, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); w.webContents.sendInputEvent(shiftTabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-element-1', `focus should've moved to element-1, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); w.webContents.sendInputEvent(shiftTabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-element-3', `focus should've looped back to element-3, it's instead in ${focusedElementId}`); }); }); }); describe('web security', () => { afterEach(closeAllWindows); let server: http.Server; let serverUrl: string; before(async () => { server = http.createServer((req, res) => { res.setHeader('Content-Type', 'text/html'); res.end('<body>'); }); serverUrl = (await listen(server)).url; }); after(() => { server.close(); }); it('engages CORB when web security is not disabled', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: true, nodeIntegration: true, contextIsolation: false } }); const p = once(ipcMain, 'success'); await w.loadURL(`data:text/html,<script> const s = document.createElement('script') s.src = "${serverUrl}" // The script will load successfully but its body will be emptied out // by CORB, so we don't expect a syntax error. s.onload = () => { require('electron').ipcRenderer.send('success') } document.documentElement.appendChild(s) </script>`); await p; }); it('bypasses CORB when web security is disabled', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: false, nodeIntegration: true, contextIsolation: false } }); const p = once(ipcMain, 'success'); await w.loadURL(`data:text/html, <script> window.onerror = (e) => { require('electron').ipcRenderer.send('success', e) } </script> <script src="${serverUrl}"></script>`); await p; }); it('engages CORS when web security is not disabled', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: true, nodeIntegration: true, contextIsolation: false } }); const p = once(ipcMain, 'response'); await w.loadURL(`data:text/html,<script> (async function() { try { await fetch('${serverUrl}'); require('electron').ipcRenderer.send('response', 'passed'); } catch { require('electron').ipcRenderer.send('response', 'failed'); } })(); </script>`); const [, response] = await p; expect(response).to.equal('failed'); }); it('bypasses CORS when web security is disabled', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: false, nodeIntegration: true, contextIsolation: false } }); const p = once(ipcMain, 'response'); await w.loadURL(`data:text/html,<script> (async function() { try { await fetch('${serverUrl}'); require('electron').ipcRenderer.send('response', 'passed'); } catch { require('electron').ipcRenderer.send('response', 'failed'); } })(); </script>`); const [, response] = await p; expect(response).to.equal('passed'); }); describe('accessing file://', () => { async function loadFile (w: BrowserWindow) { const thisFile = url.format({ pathname: __filename.replace(/\\/g, '/'), protocol: 'file', slashes: true }); await w.loadURL(`data:text/html,<script> function loadFile() { return new Promise((resolve) => { fetch('${thisFile}').then( () => resolve('loaded'), () => resolve('failed') ) }); } </script>`); return await w.webContents.executeJavaScript('loadFile()'); } it('is forbidden when web security is enabled', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: true } }); const result = await loadFile(w); expect(result).to.equal('failed'); }); it('is allowed when web security is disabled', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: false } }); const result = await loadFile(w); expect(result).to.equal('loaded'); }); }); describe('wasm-eval csp', () => { async function loadWasm (csp: string) { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, enableBlinkFeatures: 'WebAssemblyCSP' } }); await w.loadURL(`data:text/html,<head> <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-inline' ${csp}"> </head> <script> function loadWasm() { const wasmBin = new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0]) return new Promise((resolve) => { WebAssembly.instantiate(wasmBin).then(() => { resolve('loaded') }).catch((error) => { resolve(error.message) }) }); } </script>`); return await w.webContents.executeJavaScript('loadWasm()'); } it('wasm codegen is disallowed by default', async () => { const r = await loadWasm(''); expect(r).to.equal('WebAssembly.instantiate(): Refused to compile or instantiate WebAssembly module because \'unsafe-eval\' is not an allowed source of script in the following Content Security Policy directive: "script-src \'self\' \'unsafe-inline\'"'); }); it('wasm codegen is allowed with "wasm-unsafe-eval" csp', async () => { const r = await loadWasm("'wasm-unsafe-eval'"); expect(r).to.equal('loaded'); }); }); describe('csp', () => { for (const sandbox of [true, false]) { describe(`when sandbox: ${sandbox}`, () => { for (const contextIsolation of [true, false]) { describe(`when contextIsolation: ${contextIsolation}`, () => { it('prevents eval from running in an inline script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox, contextIsolation } }); w.loadURL(`data:text/html,<head> <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-inline'"> </head> <script> try { // We use console.log here because it is easier than making a // preload script, and the behavior under test changes when // contextIsolation: false console.log(eval('true')) } catch (e) { console.log(e.message) } </script>`); const [,, message] = await once(w.webContents, 'console-message'); expect(message).to.match(/Refused to evaluate a string/); }); it('does not prevent eval from running in an inline script when there is no csp', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox, contextIsolation } }); w.loadURL(`data:text/html, <script> try { // We use console.log here because it is easier than making a // preload script, and the behavior under test changes when // contextIsolation: false console.log(eval('true')) } catch (e) { console.log(e.message) } </script>`); const [,, message] = await once(w.webContents, 'console-message'); expect(message).to.equal('true'); }); it('prevents eval from running in executeJavaScript', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox, contextIsolation } }); w.loadURL('data:text/html,<head><meta http-equiv="Content-Security-Policy" content="default-src \'self\'; script-src \'self\' \'unsafe-inline\'"></meta></head>'); await expect(w.webContents.executeJavaScript('eval("true")')).to.be.rejected(); }); it('does not prevent eval from running in executeJavaScript when there is no csp', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox, contextIsolation } }); w.loadURL('data:text/html,'); expect(await w.webContents.executeJavaScript('eval("true")')).to.be.true(); }); }); } }); } }); it('does not crash when multiple WebContent are created with web security disabled', () => { const options = { show: false, webPreferences: { webSecurity: false } }; const w1 = new BrowserWindow(options); w1.loadURL(serverUrl); const w2 = new BrowserWindow(options); w2.loadURL(serverUrl); }); }); describe('command line switches', () => { let appProcess: ChildProcess.ChildProcessWithoutNullStreams | undefined; afterEach(() => { if (appProcess && !appProcess.killed) { appProcess.kill(); appProcess = undefined; } }); describe('--lang switch', () => { const currentLocale = app.getLocale(); const currentSystemLocale = app.getSystemLocale(); const currentPreferredLanguages = JSON.stringify(app.getPreferredSystemLanguages()); const testLocale = async (locale: string, result: string, printEnv: boolean = false) => { const appPath = path.join(fixturesPath, 'api', 'locale-check'); const args = [appPath, `--set-lang=${locale}`]; if (printEnv) { args.push('--print-env'); } appProcess = ChildProcess.spawn(process.execPath, args); let output = ''; appProcess.stdout.on('data', (data) => { output += data; }); let stderr = ''; appProcess.stderr.on('data', (data) => { stderr += data; }); const [code, signal] = await once(appProcess, 'exit'); if (code !== 0) { throw new Error(`Process exited with code "${code}" signal "${signal}" output "${output}" stderr "${stderr}"`); } output = output.replace(/(\r\n|\n|\r)/gm, ''); expect(output).to.equal(result); }; it('should set the locale', async () => testLocale('fr', `fr|${currentSystemLocale}|${currentPreferredLanguages}`)); it('should set the locale with country code', async () => testLocale('zh-CN', `zh-CN|${currentSystemLocale}|${currentPreferredLanguages}`)); it('should not set an invalid locale', async () => testLocale('asdfkl', `${currentLocale}|${currentSystemLocale}|${currentPreferredLanguages}`)); const lcAll = String(process.env.LC_ALL); ifit(process.platform === 'linux')('current process has a valid LC_ALL env', async () => { // The LC_ALL env should not be set to DOM locale string. expect(lcAll).to.not.equal(app.getLocale()); }); ifit(process.platform === 'linux')('should not change LC_ALL', async () => testLocale('fr', lcAll, true)); ifit(process.platform === 'linux')('should not change LC_ALL when setting invalid locale', async () => testLocale('asdfkl', lcAll, true)); ifit(process.platform === 'linux')('should not change LC_ALL when --lang is not set', async () => testLocale('', lcAll, true)); }); describe('--remote-debugging-pipe switch', () => { it('should expose CDP via pipe', async () => { const electronPath = process.execPath; appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-pipe'], { stdio: ['inherit', 'inherit', 'inherit', 'pipe', 'pipe'] }) as ChildProcess.ChildProcessWithoutNullStreams; const stdio = appProcess.stdio as unknown as [NodeJS.ReadableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.ReadableStream]; const pipe = new PipeTransport(stdio[3], stdio[4]); const versionPromise = new Promise(resolve => { pipe.onmessage = resolve; }); pipe.send({ id: 1, method: 'Browser.getVersion', params: {} }); const message = (await versionPromise) as any; expect(message.id).to.equal(1); expect(message.result.product).to.contain('Chrome'); expect(message.result.userAgent).to.contain('Electron'); }); it('should override --remote-debugging-port switch', async () => { const electronPath = process.execPath; appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-pipe', '--remote-debugging-port=0'], { stdio: ['inherit', 'inherit', 'pipe', 'pipe', 'pipe'] }) as ChildProcess.ChildProcessWithoutNullStreams; let stderr = ''; appProcess.stderr.on('data', (data: string) => { stderr += data; }); const stdio = appProcess.stdio as unknown as [NodeJS.ReadableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.ReadableStream]; const pipe = new PipeTransport(stdio[3], stdio[4]); const versionPromise = new Promise(resolve => { pipe.onmessage = resolve; }); pipe.send({ id: 1, method: 'Browser.getVersion', params: {} }); const message = (await versionPromise) as any; expect(message.id).to.equal(1); expect(stderr).to.not.include('DevTools listening on'); }); it('should shut down Electron upon Browser.close CDP command', async () => { const electronPath = process.execPath; appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-pipe'], { stdio: ['inherit', 'inherit', 'inherit', 'pipe', 'pipe'] }) as ChildProcess.ChildProcessWithoutNullStreams; const stdio = appProcess.stdio as unknown as [NodeJS.ReadableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.ReadableStream]; const pipe = new PipeTransport(stdio[3], stdio[4]); pipe.send({ id: 1, method: 'Browser.close', params: {} }); await once(appProcess, 'exit'); }); }); describe('--remote-debugging-port switch', () => { it('should display the discovery page', (done) => { const electronPath = process.execPath; let output = ''; appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-port=']); appProcess.stdout.on('data', (data) => { console.log(data); }); appProcess.stderr.on('data', (data) => { console.log(data); output += data; const m = /DevTools listening on ws:\/\/127.0.0.1:(\d+)\//.exec(output); if (m) { appProcess!.stderr.removeAllListeners('data'); const port = m[1]; http.get(`http://127.0.0.1:${port}`, (res) => { try { expect(res.statusCode).to.eql(200); expect(parseInt(res.headers['content-length']!)).to.be.greaterThan(0); done(); } catch (e) { done(e); } finally { res.destroy(); } }); } }); }); }); }); describe('chromium features', () => { afterEach(closeAllWindows); describe('accessing key names also used as Node.js module names', () => { it('does not crash', (done) => { const w = new BrowserWindow({ show: false }); w.webContents.once('did-finish-load', () => { done(); }); w.webContents.once('render-process-gone', () => done(new Error('WebContents crashed.'))); w.loadFile(path.join(fixturesPath, 'pages', 'external-string.html')); }); }); describe('first party sets', () => { const fps = [ 'https://fps-member1.glitch.me', 'https://fps-member2.glitch.me', 'https://fps-member3.glitch.me' ]; it('loads first party sets', async () => { const appPath = path.join(fixturesPath, 'api', 'first-party-sets', 'base'); const fpsProcess = ChildProcess.spawn(process.execPath, [appPath]); let output = ''; fpsProcess.stdout.on('data', data => { output += data; }); await once(fpsProcess, 'exit'); expect(output).to.include(fps.join(',')); }); it('loads sets from the command line', async () => { const appPath = path.join(fixturesPath, 'api', 'first-party-sets', 'command-line'); const args = [appPath, `--use-first-party-set=${fps}`]; const fpsProcess = ChildProcess.spawn(process.execPath, args); let output = ''; fpsProcess.stdout.on('data', data => { output += data; }); await once(fpsProcess, 'exit'); expect(output).to.include(fps.join(',')); }); }); describe('loading jquery', () => { it('does not crash', (done) => { const w = new BrowserWindow({ show: false }); w.webContents.once('did-finish-load', () => { done(); }); w.webContents.once('render-process-gone', () => done(new Error('WebContents crashed.'))); w.loadFile(path.join(__dirname, 'fixtures', 'pages', 'jquery.html')); }); }); describe('navigator.languages', () => { it('should return the system locale only', async () => { const appLocale = app.getLocale(); const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const languages = await w.webContents.executeJavaScript('navigator.languages'); expect(languages.length).to.be.greaterThan(0); expect(languages).to.contain(appLocale); }); }); describe('navigator.serviceWorker', () => { it('should register for file scheme', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, partition: 'sw-file-scheme-spec', contextIsolation: false } }); w.webContents.on('ipc-message', (event, channel, message) => { if (channel === 'reload') { w.webContents.reload(); } else if (channel === 'error') { done(message); } else if (channel === 'response') { expect(message).to.equal('Hello from serviceWorker!'); session.fromPartition('sw-file-scheme-spec').clearStorageData({ storages: ['serviceworkers'] }).then(() => done()); } }); w.webContents.on('render-process-gone', () => done(new Error('WebContents crashed.'))); w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'index.html')); }); it('should register for intercepted file scheme', (done) => { const customSession = session.fromPartition('intercept-file'); customSession.protocol.interceptBufferProtocol('file', (request, callback) => { let file = url.parse(request.url).pathname!; if (file[0] === '/' && process.platform === 'win32') file = file.slice(1); const content = fs.readFileSync(path.normalize(file)); const ext = path.extname(file); let type = 'text/html'; if (ext === '.js') type = 'application/javascript'; callback({ data: content, mimeType: type } as any); }); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, session: customSession, contextIsolation: false } }); w.webContents.on('ipc-message', (event, channel, message) => { if (channel === 'reload') { w.webContents.reload(); } else if (channel === 'error') { done(`unexpected error : ${message}`); } else if (channel === 'response') { expect(message).to.equal('Hello from serviceWorker!'); customSession.clearStorageData({ storages: ['serviceworkers'] }).then(() => { customSession.protocol.uninterceptProtocol('file'); done(); }); } }); w.webContents.on('render-process-gone', () => done(new Error('WebContents crashed.'))); w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'index.html')); }); it('should register for custom scheme', (done) => { const customSession = session.fromPartition('custom-scheme'); customSession.protocol.registerFileProtocol(serviceWorkerScheme, (request, callback) => { let file = url.parse(request.url).pathname!; if (file[0] === '/' && process.platform === 'win32') file = file.slice(1); callback({ path: path.normalize(file) } as any); }); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, session: customSession, contextIsolation: false } }); w.webContents.on('ipc-message', (event, channel, message) => { if (channel === 'reload') { w.webContents.reload(); } else if (channel === 'error') { done(`unexpected error : ${message}`); } else if (channel === 'response') { expect(message).to.equal('Hello from serviceWorker!'); customSession.clearStorageData({ storages: ['serviceworkers'] }).then(() => { customSession.protocol.uninterceptProtocol(serviceWorkerScheme); done(); }); } }); w.webContents.on('render-process-gone', () => done(new Error('WebContents crashed.'))); w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'custom-scheme-index.html')); }); it('should not allow nodeIntegrationInWorker', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, nodeIntegrationInWorker: true, partition: 'sw-file-scheme-worker-spec', contextIsolation: false } }); await w.loadURL(`file://${fixturesPath}/pages/service-worker/empty.html`); const data = await w.webContents.executeJavaScript(` navigator.serviceWorker.register('worker-no-node.js', { scope: './' }).then(() => navigator.serviceWorker.ready) new Promise((resolve) => { navigator.serviceWorker.onmessage = event => resolve(event.data); }); `); expect(data).to.equal('undefined undefined undefined undefined'); }); }); describe('navigator.geolocation', () => { ifit(features.isFakeLocationProviderEnabled())('returns error when permission is denied', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, partition: 'geolocation-spec', contextIsolation: false } }); const message = once(w.webContents, 'ipc-message'); w.webContents.session.setPermissionRequestHandler((wc, permission, callback) => { if (permission === 'geolocation') { callback(false); } else { callback(true); } }); w.loadFile(path.join(fixturesPath, 'pages', 'geolocation', 'index.html')); const [, channel] = await message; expect(channel).to.equal('success', 'unexpected response from geolocation api'); }); ifit(!features.isFakeLocationProviderEnabled())('returns position when permission is granted', async () => { const w = new BrowserWindow({ show: false, webPreferences: { partition: 'geolocation-spec' } }); w.webContents.session.setPermissionRequestHandler((_wc, _permission, callback) => { callback(true); }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const position = await w.webContents.executeJavaScript(`new Promise((resolve, reject) => navigator.geolocation.getCurrentPosition( x => resolve({coords: x.coords, timestamp: x.timestamp}), err => reject(new Error(err.message))))`); expect(position).to.have.property('coords'); expect(position).to.have.property('timestamp'); }); }); describe('web workers', () => { let appProcess: ChildProcess.ChildProcessWithoutNullStreams | undefined; afterEach(() => { if (appProcess && !appProcess.killed) { appProcess.kill(); appProcess = undefined; } }); it('Worker with nodeIntegrationInWorker has access to self.module.paths', async () => { const appPath = path.join(__dirname, 'fixtures', 'apps', 'self-module-paths'); appProcess = ChildProcess.spawn(process.execPath, [appPath]); const [code] = await once(appProcess, 'exit'); expect(code).to.equal(0); }); it('Worker can work', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const data = await w.webContents.executeJavaScript(` const worker = new Worker('../workers/worker.js'); const message = 'ping'; const eventPromise = new Promise((resolve) => { worker.onmessage = resolve; }); worker.postMessage(message); eventPromise.then(t => t.data) `); expect(data).to.equal('ping'); }); it('Worker has no node integration by default', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const data = await w.webContents.executeJavaScript(` const worker = new Worker('../workers/worker_node.js'); new Promise((resolve) => { worker.onmessage = e => resolve(e.data); }) `); expect(data).to.equal('undefined undefined undefined undefined'); }); it('Worker has node integration with nodeIntegrationInWorker', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, nodeIntegrationInWorker: true, contextIsolation: false } }); w.loadURL(`file://${fixturesPath}/pages/worker.html`); const [, data] = await once(ipcMain, 'worker-result'); expect(data).to.equal('object function object function'); }); describe('SharedWorker', () => { it('can work', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const data = await w.webContents.executeJavaScript(` const worker = new SharedWorker('../workers/shared_worker.js'); const message = 'ping'; const eventPromise = new Promise((resolve) => { worker.port.onmessage = e => resolve(e.data); }); worker.port.postMessage(message); eventPromise `); expect(data).to.equal('ping'); }); it('has no node integration by default', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const data = await w.webContents.executeJavaScript(` const worker = new SharedWorker('../workers/shared_worker_node.js'); new Promise((resolve) => { worker.port.onmessage = e => resolve(e.data); }) `); expect(data).to.equal('undefined undefined undefined undefined'); }); it('does not have node integration with nodeIntegrationInWorker', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, nodeIntegrationInWorker: true, contextIsolation: false } }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const data = await w.webContents.executeJavaScript(` const worker = new SharedWorker('../workers/shared_worker_node.js'); new Promise((resolve) => { worker.port.onmessage = e => resolve(e.data); }) `); expect(data).to.equal('undefined undefined undefined undefined'); }); }); }); describe('form submit', () => { let server: http.Server; let serverUrl: string; before(async () => { server = http.createServer((req, res) => { let body = ''; req.on('data', (chunk) => { body += chunk; }); res.setHeader('Content-Type', 'application/json'); req.on('end', () => { res.end(`body:${body}`); }); }); serverUrl = (await listen(server)).url; }); after(async () => { server.close(); await closeAllWindows(); }); [true, false].forEach((isSandboxEnabled) => describe(`sandbox=${isSandboxEnabled}`, () => { it('posts data in the same window', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: isSandboxEnabled } }); await w.loadFile(path.join(fixturesPath, 'pages', 'form-with-data.html')); const loadPromise = once(w.webContents, 'did-finish-load'); w.webContents.executeJavaScript(` const form = document.querySelector('form') form.action = '${serverUrl}'; form.submit(); `); await loadPromise; const res = await w.webContents.executeJavaScript('document.body.innerText'); expect(res).to.equal('body:greeting=hello'); }); it('posts data to a new window with target=_blank', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: isSandboxEnabled } }); await w.loadFile(path.join(fixturesPath, 'pages', 'form-with-data.html')); const windowCreatedPromise = once(app, 'browser-window-created') as Promise<[any, BrowserWindow]>; w.webContents.executeJavaScript(` const form = document.querySelector('form') form.action = '${serverUrl}'; form.target = '_blank'; form.submit(); `); const [, newWin] = await windowCreatedPromise; const res = await newWin.webContents.executeJavaScript('document.body.innerText'); expect(res).to.equal('body:greeting=hello'); }); }) ); }); describe('window.open', () => { for (const show of [true, false]) { it(`shows the child regardless of parent visibility when parent {show=${show}}`, async () => { const w = new BrowserWindow({ show }); // toggle visibility if (show) { w.hide(); } else { w.show(); } defer(() => { w.close(); }); const promise = once(app, 'browser-window-created') as Promise<[any, BrowserWindow]>; w.loadFile(path.join(fixturesPath, 'pages', 'window-open.html')); const [, newWindow] = await promise; expect(newWindow.isVisible()).to.equal(true); }); } // FIXME(zcbenz): This test is making the spec runner hang on exit on Windows. ifit(process.platform !== 'win32')('disables node integration when it is disabled on the parent window', async () => { const windowUrl = url.pathToFileURL(path.join(fixturesPath, 'pages', 'window-opener-no-node-integration.html')); windowUrl.searchParams.set('p', `${fixturesPath}/pages/window-opener-node.html`); const w = new BrowserWindow({ show: false }); w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); const { eventData } = await w.webContents.executeJavaScript(`(async () => { const message = new Promise(resolve => window.addEventListener('message', resolve, {once: true})); const b = window.open(${JSON.stringify(windowUrl)}, '', 'show=false') const e = await message b.close(); return { eventData: e.data } })()`); expect(eventData.isProcessGlobalUndefined).to.be.true(); }); it('disables node integration when it is disabled on the parent window for chrome devtools URLs', async () => { // NB. webSecurity is disabled because native window.open() is not // allowed to load devtools:// URLs. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webSecurity: false } }); w.loadURL('about:blank'); w.webContents.executeJavaScript(` { b = window.open('devtools://devtools/bundled/inspector.html', '', 'nodeIntegration=no,show=no'); null } `); const [, contents] = await once(app, 'web-contents-created') as [any, WebContents]; const typeofProcessGlobal = await contents.executeJavaScript('typeof process'); expect(typeofProcessGlobal).to.equal('undefined'); }); it('can disable node integration when it is enabled on the parent window', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); w.loadURL('about:blank'); w.webContents.executeJavaScript(` { b = window.open('about:blank', '', 'nodeIntegration=no,show=no'); null } `); const [, contents] = await once(app, 'web-contents-created') as [any, WebContents]; const typeofProcessGlobal = await contents.executeJavaScript('typeof process'); expect(typeofProcessGlobal).to.equal('undefined'); }); // TODO(jkleinsc) fix this flaky test on WOA ifit(process.platform !== 'win32' || process.arch !== 'arm64')('disables JavaScript when it is disabled on the parent window', async () => { const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true } }); w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); const windowUrl = require('node:url').format({ pathname: `${fixturesPath}/pages/window-no-javascript.html`, protocol: 'file', slashes: true }); w.webContents.executeJavaScript(` { b = window.open(${JSON.stringify(windowUrl)}, '', 'javascript=no,show=no'); null } `); const [, contents] = await once(app, 'web-contents-created') as [any, WebContents]; await once(contents, 'did-finish-load'); // Click link on page contents.sendInputEvent({ type: 'mouseDown', clickCount: 1, x: 1, y: 1 }); contents.sendInputEvent({ type: 'mouseUp', clickCount: 1, x: 1, y: 1 }); const [, window] = await once(app, 'browser-window-created') as [any, BrowserWindow]; const preferences = window.webContents.getLastWebPreferences(); expect(preferences!.javascript).to.be.false(); }); it('defines a window.location getter', async () => { let targetURL: string; if (process.platform === 'win32') { targetURL = `file:///${fixturesPath.replace(/\\/g, '/')}/pages/base-page.html`; } else { targetURL = `file://${fixturesPath}/pages/base-page.html`; } const w = new BrowserWindow({ show: false }); w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); w.webContents.executeJavaScript(`{ b = window.open(${JSON.stringify(targetURL)}); null }`); const [, window] = await once(app, 'browser-window-created') as [any, BrowserWindow]; await once(window.webContents, 'did-finish-load'); expect(await w.webContents.executeJavaScript('b.location.href')).to.equal(targetURL); }); it('defines a window.location setter', async () => { const w = new BrowserWindow({ show: false }); w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); w.webContents.executeJavaScript('{ b = window.open("about:blank"); null }'); const [, { webContents }] = await once(app, 'browser-window-created') as [any, BrowserWindow]; await once(webContents, 'did-finish-load'); // When it loads, redirect w.webContents.executeJavaScript(`{ b.location = ${JSON.stringify(`file://${fixturesPath}/pages/base-page.html`)}; null }`); await once(webContents, 'did-finish-load'); }); it('defines a window.location.href setter', async () => { const w = new BrowserWindow({ show: false }); w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); w.webContents.executeJavaScript('{ b = window.open("about:blank"); null }'); const [, { webContents }] = await once(app, 'browser-window-created') as [any, BrowserWindow]; await once(webContents, 'did-finish-load'); // When it loads, redirect w.webContents.executeJavaScript(`{ b.location.href = ${JSON.stringify(`file://${fixturesPath}/pages/base-page.html`)}; null }`); await once(webContents, 'did-finish-load'); }); it('open a blank page when no URL is specified', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.executeJavaScript('{ b = window.open(); null }'); const [, { webContents }] = await once(app, 'browser-window-created') as [any, BrowserWindow]; await once(webContents, 'did-finish-load'); expect(await w.webContents.executeJavaScript('b.location.href')).to.equal('about:blank'); }); it('open a blank page when an empty URL is specified', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.executeJavaScript('{ b = window.open(\'\'); null }'); const [, { webContents }] = await once(app, 'browser-window-created') as [any, BrowserWindow]; await once(webContents, 'did-finish-load'); expect(await w.webContents.executeJavaScript('b.location.href')).to.equal('about:blank'); }); it('does not throw an exception when the frameName is a built-in object property', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.executeJavaScript('{ b = window.open(\'\', \'__proto__\'); null }'); const frameName = await new Promise((resolve) => { w.webContents.setWindowOpenHandler(details => { setImmediate(() => resolve(details.frameName)); return { action: 'allow' }; }); }); expect(frameName).to.equal('__proto__'); }); it('works when used in conjunction with the vm module', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); await w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); const { contextObject } = await w.webContents.executeJavaScript(`(async () => { const vm = require('node:vm'); const contextObject = { count: 1, type: 'gecko' }; window.open(''); vm.runInNewContext('count += 1; type = "chameleon";', contextObject); return { contextObject }; })()`); expect(contextObject).to.deep.equal({ count: 2, type: 'chameleon' }); }); // FIXME(nornagon): I'm not sure this ... ever was correct? xit('inherit options of parent window', async () => { const w = new BrowserWindow({ show: false, width: 123, height: 456 }); w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); const url = `file://${fixturesPath}/pages/window-open-size.html`; const { width, height, eventData } = await w.webContents.executeJavaScript(`(async () => { const message = new Promise(resolve => window.addEventListener('message', resolve, {once: true})); const b = window.open(${JSON.stringify(url)}, '', 'show=false') const e = await message b.close(); const width = outerWidth; const height = outerHeight; return { width, height, eventData: e.data } })()`); expect(eventData).to.equal(`size: ${width} ${height}`); expect(eventData).to.equal('size: 123 456'); }); it('does not override child options', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); const windowUrl = `file://${fixturesPath}/pages/window-open-size.html`; const { eventData } = await w.webContents.executeJavaScript(`(async () => { const message = new Promise(resolve => window.addEventListener('message', resolve, {once: true})); const b = window.open(${JSON.stringify(windowUrl)}, '', 'show=no,width=350,height=450') const e = await message b.close(); return { eventData: e.data } })()`); expect(eventData).to.equal('size: 350 450'); }); it('loads preload script after setting opener to null', async () => { const w = new BrowserWindow({ show: false }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: path.join(fixturesPath, 'module', 'preload.js') } } })); w.loadURL('about:blank'); w.webContents.executeJavaScript('window.child = window.open(); child.opener = null'); const [, { webContents }] = await once(app, 'browser-window-created'); const [,, message] = await once(webContents, 'console-message'); expect(message).to.equal('{"require":"function","module":"undefined","process":"object","Buffer":"function"}'); }); it('disables the <webview> tag when it is disabled on the parent window', async () => { const windowUrl = url.pathToFileURL(path.join(fixturesPath, 'pages', 'window-opener-no-webview-tag.html')); windowUrl.searchParams.set('p', `${fixturesPath}/pages/window-opener-webview.html`); const w = new BrowserWindow({ show: false }); w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); const { eventData } = await w.webContents.executeJavaScript(`(async () => { const message = new Promise(resolve => window.addEventListener('message', resolve, {once: true})); const b = window.open(${JSON.stringify(windowUrl)}, '', 'webviewTag=no,contextIsolation=no,nodeIntegration=yes,show=no') const e = await message b.close(); return { eventData: e.data } })()`); expect(eventData.isWebViewGlobalUndefined).to.be.true(); }); it('throws an exception when the arguments cannot be converted to strings', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); await expect( w.webContents.executeJavaScript('window.open(\'\', { toString: null })') ).to.eventually.be.rejected(); await expect( w.webContents.executeJavaScript('window.open(\'\', \'\', { toString: 3 })') ).to.eventually.be.rejected(); }); it('does not throw an exception when the features include webPreferences', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); await expect( w.webContents.executeJavaScript('window.open(\'\', \'\', \'show=no,webPreferences=\'); null') ).to.eventually.be.fulfilled(); }); }); describe('window.opener', () => { it('is null for main window', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixturesPath, 'pages', 'window-opener.html')); const [, channel, opener] = await once(w.webContents, 'ipc-message'); expect(channel).to.equal('opener'); expect(opener).to.equal(null); }); it('is not null for window opened by window.open', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); const windowUrl = `file://${fixturesPath}/pages/window-opener.html`; const eventData = await w.webContents.executeJavaScript(` const b = window.open(${JSON.stringify(windowUrl)}, '', 'show=no'); new Promise(resolve => window.addEventListener('message', resolve, {once: true})).then(e => e.data); `); expect(eventData).to.equal('object'); }); }); describe('window.opener.postMessage', () => { it('sets source and origin correctly', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); const windowUrl = `file://${fixturesPath}/pages/window-opener-postMessage.html`; const { sourceIsChild, origin } = await w.webContents.executeJavaScript(` const b = window.open(${JSON.stringify(windowUrl)}, '', 'show=no'); new Promise(resolve => window.addEventListener('message', resolve, {once: true})).then(e => ({ sourceIsChild: e.source === b, origin: e.origin })); `); expect(sourceIsChild).to.be.true(); expect(origin).to.equal('file://'); }); it('supports windows opened from a <webview>', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } }); w.loadURL('about:blank'); const childWindowUrl = url.pathToFileURL(path.join(fixturesPath, 'pages', 'webview-opener-postMessage.html')); childWindowUrl.searchParams.set('p', `${fixturesPath}/pages/window-opener-postMessage.html`); const message = await w.webContents.executeJavaScript(` const webview = new WebView(); webview.allowpopups = true; webview.setAttribute('webpreferences', 'contextIsolation=no'); webview.src = ${JSON.stringify(childWindowUrl)} const consoleMessage = new Promise(resolve => webview.addEventListener('console-message', resolve, {once: true})); document.body.appendChild(webview); consoleMessage.then(e => e.message) `); expect(message).to.equal('message'); }); describe('targetOrigin argument', () => { let serverURL: string; let server: any; beforeEach(async () => { server = http.createServer((req, res) => { res.writeHead(200); const filePath = path.join(fixturesPath, 'pages', 'window-opener-targetOrigin.html'); res.end(fs.readFileSync(filePath, 'utf8')); }); serverURL = (await listen(server)).url; }); afterEach(() => { server.close(); }); it('delivers messages that match the origin', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); const data = await w.webContents.executeJavaScript(` window.open(${JSON.stringify(serverURL)}, '', 'show=no,contextIsolation=no,nodeIntegration=yes'); new Promise(resolve => window.addEventListener('message', resolve, {once: true})).then(e => e.data) `); expect(data).to.equal('deliver'); }); }); }); describe('IdleDetection', () => { afterEach(closeAllWindows); afterEach(() => { session.defaultSession.setPermissionCheckHandler(null); session.defaultSession.setPermissionRequestHandler(null); }); it('can grant a permission request', async () => { session.defaultSession.setPermissionRequestHandler( (_wc, permission, callback) => { callback(permission === 'idle-detection'); } ); const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'button.html')); const permission = await w.webContents.executeJavaScript(` new Promise((resolve, reject) => { const button = document.getElementById('button'); button.addEventListener("click", async () => { const permission = await IdleDetector.requestPermission(); resolve(permission); }); button.click(); }); `, true); expect(permission).to.eq('granted'); }); it('can deny a permission request', async () => { session.defaultSession.setPermissionRequestHandler( (_wc, permission, callback) => { callback(permission !== 'idle-detection'); } ); const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'button.html')); const permission = await w.webContents.executeJavaScript(` new Promise((resolve, reject) => { const button = document.getElementById('button'); button.addEventListener("click", async () => { const permission = await IdleDetector.requestPermission(); resolve(permission); }); button.click(); }); `, true); expect(permission).to.eq('denied'); }); it('can allow the IdleDetector to start', async () => { session.defaultSession.setPermissionCheckHandler((wc, permission) => { return permission === 'idle-detection'; }); const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); const result = await w.webContents.executeJavaScript(` const detector = new IdleDetector({ threshold: 60000 }); detector.start().then(() => { return 'success'; }).catch(e => e.message); `, true); expect(result).to.eq('success'); }); it('can prevent the IdleDetector from starting', async () => { session.defaultSession.setPermissionCheckHandler((wc, permission) => { return permission !== 'idle-detection'; }); const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); const result = await w.webContents.executeJavaScript(` const detector = new IdleDetector({ threshold: 60000 }); detector.start().then(() => { console.log('success') }).catch(e => e.message); `, true); expect(result).to.eq('Idle detection permission denied'); }); }); describe('navigator.mediaDevices', () => { afterEach(closeAllWindows); afterEach(() => { session.defaultSession.setPermissionCheckHandler(null); session.defaultSession.setPermissionRequestHandler(null); }); it('can return labels of enumerated devices', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); const labels = await w.webContents.executeJavaScript('navigator.mediaDevices.enumerateDevices().then(ds => ds.map(d => d.label))'); expect(labels.some((l: any) => l)).to.be.true(); }); it('does not return labels of enumerated devices when permission denied', async () => { session.defaultSession.setPermissionCheckHandler(() => false); const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); const labels = await w.webContents.executeJavaScript('navigator.mediaDevices.enumerateDevices().then(ds => ds.map(d => d.label))'); expect(labels.some((l: any) => l)).to.be.false(); }); it('returns the same device ids across reloads', async () => { const ses = session.fromPartition('persist:media-device-id'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, session: ses, contextIsolation: false } }); w.loadFile(path.join(fixturesPath, 'pages', 'media-id-reset.html')); const [, firstDeviceIds] = await once(ipcMain, 'deviceIds'); w.webContents.reload(); const [, secondDeviceIds] = await once(ipcMain, 'deviceIds'); expect(firstDeviceIds).to.deep.equal(secondDeviceIds); }); it('can return new device id when cookie storage is cleared', async () => { const ses = session.fromPartition('persist:media-device-id'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, session: ses, contextIsolation: false } }); w.loadFile(path.join(fixturesPath, 'pages', 'media-id-reset.html')); const [, firstDeviceIds] = await once(ipcMain, 'deviceIds'); await ses.clearStorageData({ storages: ['cookies'] }); w.webContents.reload(); const [, secondDeviceIds] = await once(ipcMain, 'deviceIds'); expect(firstDeviceIds).to.not.deep.equal(secondDeviceIds); }); it('provides a securityOrigin to the request handler', async () => { session.defaultSession.setPermissionRequestHandler( (wc, permission, callback, details) => { if (details.securityOrigin !== undefined) { callback(true); } else { callback(false); } } ); const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); const labels = await w.webContents.executeJavaScript(`navigator.mediaDevices.getUserMedia({ video: { mandatory: { chromeMediaSource: "desktop", minWidth: 1280, maxWidth: 1280, minHeight: 720, maxHeight: 720 } } }).then((stream) => stream.getVideoTracks())`); expect(labels.some((l: any) => l)).to.be.true(); }); it('fails with "not supported" for getDisplayMedia', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); const { ok, err } = await w.webContents.executeJavaScript('navigator.mediaDevices.getDisplayMedia({video: true}).then(s => ({ok: true}), e => ({ok: false, err: e.message}))', true); expect(ok).to.be.false(); expect(err).to.equal('Not supported'); }); }); describe('window.opener access', () => { const scheme = 'app'; const fileUrl = `file://${fixturesPath}/pages/window-opener-location.html`; const httpUrl1 = `${scheme}://origin1`; const httpUrl2 = `${scheme}://origin2`; const fileBlank = `file://${fixturesPath}/pages/blank.html`; const httpBlank = `${scheme}://origin1/blank`; const table = [ { parent: fileBlank, child: httpUrl1, nodeIntegration: false, openerAccessible: false }, { parent: fileBlank, child: httpUrl1, nodeIntegration: true, openerAccessible: false }, // {parent: httpBlank, child: fileUrl, nodeIntegration: false, openerAccessible: false}, // can't window.open() // {parent: httpBlank, child: fileUrl, nodeIntegration: true, openerAccessible: false}, // can't window.open() // NB. this is different from Chrome's behavior, which isolates file: urls from each other { parent: fileBlank, child: fileUrl, nodeIntegration: false, openerAccessible: true }, { parent: fileBlank, child: fileUrl, nodeIntegration: true, openerAccessible: true }, { parent: httpBlank, child: httpUrl1, nodeIntegration: false, openerAccessible: true }, { parent: httpBlank, child: httpUrl1, nodeIntegration: true, openerAccessible: true }, { parent: httpBlank, child: httpUrl2, nodeIntegration: false, openerAccessible: false }, { parent: httpBlank, child: httpUrl2, nodeIntegration: true, openerAccessible: false } ]; const s = (url: string) => url.startsWith('file') ? 'file://...' : url; before(() => { protocol.registerFileProtocol(scheme, (request, callback) => { if (request.url.includes('blank')) { callback(`${fixturesPath}/pages/blank.html`); } else { callback(`${fixturesPath}/pages/window-opener-location.html`); } }); }); after(() => { protocol.unregisterProtocol(scheme); }); afterEach(closeAllWindows); describe('when opened from main window', () => { for (const { parent, child, nodeIntegration, openerAccessible } of table) { for (const sandboxPopup of [false, true]) { const description = `when parent=${s(parent)} opens child=${s(child)} with nodeIntegration=${nodeIntegration} sandboxPopup=${sandboxPopup}, child should ${openerAccessible ? '' : 'not '}be able to access opener`; it(description, async () => { const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { sandbox: sandboxPopup } } })); await w.loadURL(parent); const childOpenerLocation = await w.webContents.executeJavaScript(`new Promise(resolve => { window.addEventListener('message', function f(e) { resolve(e.data) }) window.open(${JSON.stringify(child)}, "", "show=no,nodeIntegration=${nodeIntegration ? 'yes' : 'no'}") })`); if (openerAccessible) { expect(childOpenerLocation).to.be.a('string'); } else { expect(childOpenerLocation).to.be.null(); } }); } } }); describe('when opened from <webview>', () => { for (const { parent, child, nodeIntegration, openerAccessible } of table) { const description = `when parent=${s(parent)} opens child=${s(child)} with nodeIntegration=${nodeIntegration}, child should ${openerAccessible ? '' : 'not '}be able to access opener`; it(description, async () => { // This test involves three contexts: // 1. The root BrowserWindow in which the test is run, // 2. A <webview> belonging to the root window, // 3. A window opened by calling window.open() from within the <webview>. // We are testing whether context (3) can access context (2) under various conditions. // This is context (1), the base window for the test. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webviewTag: true, contextIsolation: false } }); await w.loadURL('about:blank'); const parentCode = `new Promise((resolve) => { // This is context (3), a child window of the WebView. const child = window.open(${JSON.stringify(child)}, "", "show=no,contextIsolation=no,nodeIntegration=yes") window.addEventListener("message", e => { resolve(e.data) }) })`; const childOpenerLocation = await w.webContents.executeJavaScript(`new Promise((resolve, reject) => { // This is context (2), a WebView which will call window.open() const webview = new WebView() webview.setAttribute('nodeintegration', '${nodeIntegration ? 'on' : 'off'}') webview.setAttribute('webpreferences', 'contextIsolation=no') webview.setAttribute('allowpopups', 'on') webview.src = ${JSON.stringify(parent + '?p=' + encodeURIComponent(child))} webview.addEventListener('dom-ready', async () => { webview.executeJavaScript(${JSON.stringify(parentCode)}).then(resolve, reject) }) document.body.appendChild(webview) })`); if (openerAccessible) { expect(childOpenerLocation).to.be.a('string'); } else { expect(childOpenerLocation).to.be.null(); } }); } }); }); describe('storage', () => { describe('custom non standard schemes', () => { const protocolName = 'storage'; let contents: WebContents; before(() => { protocol.registerFileProtocol(protocolName, (request, callback) => { const parsedUrl = url.parse(request.url); let filename; switch (parsedUrl.pathname) { case '/localStorage' : filename = 'local_storage.html'; break; case '/sessionStorage' : filename = 'session_storage.html'; break; case '/WebSQL' : filename = 'web_sql.html'; break; case '/indexedDB' : filename = 'indexed_db.html'; break; case '/cookie' : filename = 'cookie.html'; break; default : filename = ''; } callback({ path: `${fixturesPath}/pages/storage/${filename}` }); }); }); after(() => { protocol.unregisterProtocol(protocolName); }); beforeEach(() => { contents = (webContents as typeof ElectronInternal.WebContents).create({ nodeIntegration: true, contextIsolation: false }); }); afterEach(() => { contents.destroy(); contents = null as any; }); it('cannot access localStorage', async () => { const response = once(ipcMain, 'local-storage-response'); contents.loadURL(protocolName + '://host/localStorage'); const [, error] = await response; expect(error).to.equal('Failed to read the \'localStorage\' property from \'Window\': Access is denied for this document.'); }); it('cannot access sessionStorage', async () => { const response = once(ipcMain, 'session-storage-response'); contents.loadURL(`${protocolName}://host/sessionStorage`); const [, error] = await response; expect(error).to.equal('Failed to read the \'sessionStorage\' property from \'Window\': Access is denied for this document.'); }); it('cannot access WebSQL database', async () => { const response = once(ipcMain, 'web-sql-response'); contents.loadURL(`${protocolName}://host/WebSQL`); const [, error] = await response; expect(error).to.equal('Failed to execute \'openDatabase\' on \'Window\': Access to the WebDatabase API is denied in this context.'); }); it('cannot access indexedDB', async () => { const response = once(ipcMain, 'indexed-db-response'); contents.loadURL(`${protocolName}://host/indexedDB`); const [, error] = await response; expect(error).to.equal('Failed to execute \'open\' on \'IDBFactory\': access to the Indexed Database API is denied in this context.'); }); it('cannot access cookie', async () => { const response = once(ipcMain, 'cookie-response'); contents.loadURL(`${protocolName}://host/cookie`); const [, error] = await response; expect(error).to.equal('Failed to set the \'cookie\' property on \'Document\': Access is denied for this document.'); }); }); describe('can be accessed', () => { let server: http.Server; let serverUrl: string; let serverCrossSiteUrl: string; before(async () => { server = http.createServer((req, res) => { const respond = () => { if (req.url === '/redirect-cross-site') { res.setHeader('Location', `${serverCrossSiteUrl}/redirected`); res.statusCode = 302; res.end(); } else if (req.url === '/redirected') { res.end('<html><script>window.localStorage</script></html>'); } else { res.end(); } }; setTimeout().then(respond); }); serverUrl = (await listen(server)).url; serverCrossSiteUrl = serverUrl.replace('127.0.0.1', 'localhost'); }); after(() => { server.close(); server = null as any; }); afterEach(closeAllWindows); const testLocalStorageAfterXSiteRedirect = (testTitle: string, extraPreferences = {}) => { it(testTitle, async () => { const w = new BrowserWindow({ show: false, ...extraPreferences }); let redirected = false; w.webContents.on('render-process-gone', () => { expect.fail('renderer crashed / was killed'); }); w.webContents.on('did-redirect-navigation', (event, url) => { expect(url).to.equal(`${serverCrossSiteUrl}/redirected`); redirected = true; }); await w.loadURL(`${serverUrl}/redirect-cross-site`); expect(redirected).to.be.true('didnt redirect'); }); }; testLocalStorageAfterXSiteRedirect('after a cross-site redirect'); testLocalStorageAfterXSiteRedirect('after a cross-site redirect in sandbox mode', { sandbox: true }); }); describe('enableWebSQL webpreference', () => { const origin = `${standardScheme}://fake-host`; const filePath = path.join(fixturesPath, 'pages', 'storage', 'web_sql.html'); const sqlPartition = 'web-sql-preference-test'; const sqlSession = session.fromPartition(sqlPartition); const securityError = 'An attempt was made to break through the security policy of the user agent.'; let contents: WebContents, w: BrowserWindow; before(() => { sqlSession.protocol.registerFileProtocol(standardScheme, (request, callback) => { callback({ path: filePath }); }); }); after(() => { sqlSession.protocol.unregisterProtocol(standardScheme); }); afterEach(async () => { if (contents) { contents.destroy(); contents = null as any; } await closeAllWindows(); (w as any) = null; }); it('default value allows websql', async () => { contents = (webContents as typeof ElectronInternal.WebContents).create({ session: sqlSession, nodeIntegration: true, contextIsolation: false }); contents.loadURL(origin); const [, error] = await once(ipcMain, 'web-sql-response'); expect(error).to.be.null(); }); it('when set to false can disallow websql', async () => { contents = (webContents as typeof ElectronInternal.WebContents).create({ session: sqlSession, nodeIntegration: true, enableWebSQL: false, contextIsolation: false }); contents.loadURL(origin); const [, error] = await once(ipcMain, 'web-sql-response'); expect(error).to.equal(securityError); }); it('when set to false does not disable indexedDB', async () => { contents = (webContents as typeof ElectronInternal.WebContents).create({ session: sqlSession, nodeIntegration: true, enableWebSQL: false, contextIsolation: false }); contents.loadURL(origin); const [, error] = await once(ipcMain, 'web-sql-response'); expect(error).to.equal(securityError); const dbName = 'random'; const result = await contents.executeJavaScript(` new Promise((resolve, reject) => { try { let req = window.indexedDB.open('${dbName}'); req.onsuccess = (event) => { let db = req.result; resolve(db.name); } req.onerror = (event) => { resolve(event.target.code); } } catch (e) { resolve(e.message); } }); `); expect(result).to.equal(dbName); }); it('child webContents can override when the embedder has allowed websql', async () => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webviewTag: true, session: sqlSession, contextIsolation: false } }); w.webContents.loadURL(origin); const [, error] = await once(ipcMain, 'web-sql-response'); expect(error).to.be.null(); const webviewResult = once(ipcMain, 'web-sql-response'); await w.webContents.executeJavaScript(` new Promise((resolve, reject) => { const webview = new WebView(); webview.setAttribute('src', '${origin}'); webview.setAttribute('webpreferences', 'enableWebSQL=0,contextIsolation=no'); webview.setAttribute('partition', '${sqlPartition}'); webview.setAttribute('nodeIntegration', 'on'); document.body.appendChild(webview); webview.addEventListener('dom-ready', () => resolve()); }); `); const [, childError] = await webviewResult; expect(childError).to.equal(securityError); }); it('child webContents cannot override when the embedder has disallowed websql', async () => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, enableWebSQL: false, webviewTag: true, session: sqlSession, contextIsolation: false } }); w.webContents.loadURL('data:text/html,<html></html>'); const webviewResult = once(ipcMain, 'web-sql-response'); await w.webContents.executeJavaScript(` new Promise((resolve, reject) => { const webview = new WebView(); webview.setAttribute('src', '${origin}'); webview.setAttribute('webpreferences', 'enableWebSQL=1,contextIsolation=no'); webview.setAttribute('partition', '${sqlPartition}'); webview.setAttribute('nodeIntegration', 'on'); document.body.appendChild(webview); webview.addEventListener('dom-ready', () => resolve()); }); `); const [, childError] = await webviewResult; expect(childError).to.equal(securityError); }); it('child webContents can use websql when the embedder has allowed websql', async () => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webviewTag: true, session: sqlSession, contextIsolation: false } }); w.webContents.loadURL(origin); const [, error] = await once(ipcMain, 'web-sql-response'); expect(error).to.be.null(); const webviewResult = once(ipcMain, 'web-sql-response'); await w.webContents.executeJavaScript(` new Promise((resolve, reject) => { const webview = new WebView(); webview.setAttribute('src', '${origin}'); webview.setAttribute('webpreferences', 'enableWebSQL=1,contextIsolation=no'); webview.setAttribute('partition', '${sqlPartition}'); webview.setAttribute('nodeIntegration', 'on'); document.body.appendChild(webview); webview.addEventListener('dom-ready', () => resolve()); }); `); const [, childError] = await webviewResult; expect(childError).to.be.null(); }); }); describe('DOM storage quota increase', () => { ['localStorage', 'sessionStorage'].forEach((storageName) => { it(`allows saving at least 40MiB in ${storageName}`, async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); // Although JavaScript strings use UTF-16, the underlying // storage provider may encode strings differently, muddling the // translation between character and byte counts. However, // a string of 40 * 2^20 characters will require at least 40MiB // and presumably no more than 80MiB, a size guaranteed to // to exceed the original 10MiB quota yet stay within the // new 100MiB quota. // Note that both the key name and value affect the total size. const testKeyName = '_electronDOMStorageQuotaIncreasedTest'; const length = 40 * Math.pow(2, 20) - testKeyName.length; await w.webContents.executeJavaScript(` ${storageName}.setItem(${JSON.stringify(testKeyName)}, 'X'.repeat(${length})); `); // Wait at least one turn of the event loop to help avoid false positives // Although not entirely necessary, the previous version of this test case // failed to detect a real problem (perhaps related to DOM storage data caching) // wherein calling `getItem` immediately after `setItem` would appear to work // but then later (e.g. next tick) it would not. await setTimeout(1); try { const storedLength = await w.webContents.executeJavaScript(`${storageName}.getItem(${JSON.stringify(testKeyName)}).length`); expect(storedLength).to.equal(length); } finally { await w.webContents.executeJavaScript(`${storageName}.removeItem(${JSON.stringify(testKeyName)});`); } }); it(`throws when attempting to use more than 128MiB in ${storageName}`, async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); await expect((async () => { const testKeyName = '_electronDOMStorageQuotaStillEnforcedTest'; const length = 128 * Math.pow(2, 20) - testKeyName.length; try { await w.webContents.executeJavaScript(` ${storageName}.setItem(${JSON.stringify(testKeyName)}, 'X'.repeat(${length})); `); } finally { await w.webContents.executeJavaScript(`${storageName}.removeItem(${JSON.stringify(testKeyName)});`); } })()).to.eventually.be.rejected(); }); }); }); describe('persistent storage', () => { it('can be requested', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); const grantedBytes = await w.webContents.executeJavaScript(`new Promise(resolve => { navigator.webkitPersistentStorage.requestQuota(1024 * 1024, resolve); })`); expect(grantedBytes).to.equal(1048576); }); }); }); ifdescribe(features.isPDFViewerEnabled())('PDF Viewer', () => { const pdfSource = url.format({ pathname: path.join(__dirname, 'fixtures', 'cat.pdf').replace(/\\/g, '/'), protocol: 'file', slashes: true }); it('successfully loads a PDF file', async () => { const w = new BrowserWindow({ show: false }); w.loadURL(pdfSource); await once(w.webContents, 'did-finish-load'); }); it('opens when loading a pdf resource as top level navigation', async () => { const w = new BrowserWindow({ show: false }); w.loadURL(pdfSource); const [, contents] = await once(app, 'web-contents-created') as [any, WebContents]; await once(contents, 'did-navigate'); expect(contents.getURL()).to.equal('chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/index.html'); }); it('opens when loading a pdf resource in a iframe', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(__dirname, 'fixtures', 'pages', 'pdf-in-iframe.html')); const [, contents] = await once(app, 'web-contents-created') as [any, WebContents]; await once(contents, 'did-navigate'); expect(contents.getURL()).to.equal('chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/index.html'); }); }); describe('window.history', () => { describe('window.history.pushState', () => { it('should push state after calling history.pushState() from the same url', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); // History should have current page by now. expect((w.webContents as any).length()).to.equal(1); const waitCommit = once(w.webContents, 'navigation-entry-committed'); w.webContents.executeJavaScript('window.history.pushState({}, "")'); await waitCommit; // Initial page + pushed state. expect((w.webContents as any).length()).to.equal(2); }); }); describe('window.history.back', () => { it('should not allow sandboxed iframe to modify main frame state', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('data:text/html,<iframe sandbox="allow-scripts"></iframe>'); await Promise.all([ once(w.webContents, 'navigation-entry-committed'), once(w.webContents, 'did-frame-navigate'), once(w.webContents, 'did-navigate') ]); w.webContents.executeJavaScript('window.history.pushState(1, "")'); await Promise.all([ once(w.webContents, 'navigation-entry-committed'), once(w.webContents, 'did-navigate-in-page') ]); (w.webContents as any).once('navigation-entry-committed', () => { expect.fail('Unexpected navigation-entry-committed'); }); w.webContents.once('did-navigate-in-page', () => { expect.fail('Unexpected did-navigate-in-page'); }); await w.webContents.mainFrame.frames[0].executeJavaScript('window.history.back()'); expect(await w.webContents.executeJavaScript('window.history.state')).to.equal(1); expect((w.webContents as any).getActiveIndex()).to.equal(1); }); }); }); describe('chrome://accessibility', () => { it('loads the page successfully', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('chrome://accessibility'); const pageExists = await w.webContents.executeJavaScript( "window.hasOwnProperty('chrome') && window.chrome.hasOwnProperty('send')" ); expect(pageExists).to.be.true(); }); }); describe('chrome://gpu', () => { it('loads the page successfully', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('chrome://gpu'); const pageExists = await w.webContents.executeJavaScript( "window.hasOwnProperty('chrome') && window.chrome.hasOwnProperty('send')" ); expect(pageExists).to.be.true(); }); }); describe('chrome://media-internals', () => { it('loads the page successfully', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('chrome://media-internals'); const pageExists = await w.webContents.executeJavaScript( "window.hasOwnProperty('chrome') && window.chrome.hasOwnProperty('send')" ); expect(pageExists).to.be.true(); }); }); describe('chrome://webrtc-internals', () => { it('loads the page successfully', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('chrome://webrtc-internals'); const pageExists = await w.webContents.executeJavaScript( "window.hasOwnProperty('chrome') && window.chrome.hasOwnProperty('send')" ); expect(pageExists).to.be.true(); }); }); describe('document.hasFocus', () => { it('has correct value when multiple windows are opened', async () => { const w1 = new BrowserWindow({ show: true }); const w2 = new BrowserWindow({ show: true }); const w3 = new BrowserWindow({ show: false }); await w1.loadFile(path.join(__dirname, 'fixtures', 'blank.html')); await w2.loadFile(path.join(__dirname, 'fixtures', 'blank.html')); await w3.loadFile(path.join(__dirname, 'fixtures', 'blank.html')); expect(webContents.getFocusedWebContents()?.id).to.equal(w2.webContents.id); let focus = false; focus = await w1.webContents.executeJavaScript( 'document.hasFocus()' ); expect(focus).to.be.false(); focus = await w2.webContents.executeJavaScript( 'document.hasFocus()' ); expect(focus).to.be.true(); focus = await w3.webContents.executeJavaScript( 'document.hasFocus()' ); expect(focus).to.be.false(); }); }); // https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation describe('navigator.connection', () => { it('returns the correct value', async () => { const w = new BrowserWindow({ show: false }); w.webContents.session.enableNetworkEmulation({ latency: 500, downloadThroughput: 6400, uploadThroughput: 6400 }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const rtt = await w.webContents.executeJavaScript('navigator.connection.rtt'); expect(rtt).to.be.a('number'); const downlink = await w.webContents.executeJavaScript('navigator.connection.downlink'); expect(downlink).to.be.a('number'); const effectiveTypes = ['slow-2g', '2g', '3g', '4g']; const effectiveType = await w.webContents.executeJavaScript('navigator.connection.effectiveType'); expect(effectiveTypes).to.include(effectiveType); }); }); describe('navigator.userAgentData', () => { // These tests are done on an http server because navigator.userAgentData // requires a secure context. let server: http.Server; let serverUrl: string; before(async () => { server = http.createServer((req, res) => { res.setHeader('Content-Type', 'text/html'); res.end(''); }); serverUrl = (await listen(server)).url; }); after(() => { server.close(); }); describe('is not empty', () => { it('by default', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(serverUrl); const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform'); expect(platform).not.to.be.empty(); }); it('when there is a session-wide UA override', async () => { const ses = session.fromPartition(`${Math.random()}`); ses.setUserAgent('foobar'); const w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await w.loadURL(serverUrl); const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform'); expect(platform).not.to.be.empty(); }); it('when there is a WebContents-specific UA override', async () => { const w = new BrowserWindow({ show: false }); w.webContents.setUserAgent('foo'); await w.loadURL(serverUrl); const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform'); expect(platform).not.to.be.empty(); }); it('when there is a WebContents-specific UA override at load time', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(serverUrl, { userAgent: 'foo' }); const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform'); expect(platform).not.to.be.empty(); }); }); describe('brand list', () => { it('contains chromium', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(serverUrl); const brands = await w.webContents.executeJavaScript('navigator.userAgentData.brands'); expect(brands.map((b: any) => b.brand)).to.include('Chromium'); }); }); }); describe('Badging API', () => { it('does not crash', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); await w.webContents.executeJavaScript('navigator.setAppBadge(42)'); await w.webContents.executeJavaScript('navigator.setAppBadge()'); await w.webContents.executeJavaScript('navigator.clearAppBadge()'); }); }); describe('navigator.webkitGetUserMedia', () => { it('calls its callbacks', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); await w.webContents.executeJavaScript(`new Promise((resolve) => { navigator.webkitGetUserMedia({ audio: true, video: false }, () => resolve(), () => resolve()); })`); }); }); describe('navigator.language', () => { it('should not be empty', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); expect(await w.webContents.executeJavaScript('navigator.language')).to.not.equal(''); }); }); describe('heap snapshot', () => { it('does not crash', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadURL('about:blank'); await w.webContents.executeJavaScript('process._linkedBinding(\'electron_common_v8_util\').takeHeapSnapshot()'); }); }); // This is intentionally disabled on arm macs: https://chromium-review.googlesource.com/c/chromium/src/+/4143761 ifdescribe(process.platform === 'darwin' && process.arch !== 'arm64')('webgl', () => { it('can be gotten as context in canvas', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const canWebglContextBeCreated = await w.webContents.executeJavaScript(` document.createElement('canvas').getContext('webgl') != null; `); expect(canWebglContextBeCreated).to.be.true(); }); }); describe('iframe', () => { it('does not have node integration', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const result = await w.webContents.executeJavaScript(` const iframe = document.createElement('iframe') iframe.src = './set-global.html'; document.body.appendChild(iframe); new Promise(resolve => iframe.onload = e => resolve(iframe.contentWindow.test)) `); expect(result).to.equal('undefined undefined undefined'); }); }); describe('websockets', () => { it('has user agent', async () => { const server = http.createServer(); const { port } = await listen(server); const wss = new ws.Server({ server: server }); const finished = new Promise<string | undefined>((resolve, reject) => { wss.on('error', reject); wss.on('connection', (ws, upgradeReq) => { resolve(upgradeReq.headers['user-agent']); }); }); const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.executeJavaScript(` new WebSocket('ws://127.0.0.1:${port}'); `); expect(await finished).to.include('Electron'); }); }); describe('fetch', () => { it('does not crash', async () => { const server = http.createServer((req, res) => { res.end('test'); }); defer(() => server.close()); const { port } = await listen(server); const w = new BrowserWindow({ show: false }); w.loadURL(`file://${fixturesPath}/pages/blank.html`); const x = await w.webContents.executeJavaScript(` fetch('http://127.0.0.1:${port}').then((res) => res.body.getReader()) .then((reader) => { return reader.read().then((r) => { reader.cancel(); return r.value; }); }) `); expect(x).to.deep.equal(new Uint8Array([116, 101, 115, 116])); }); }); describe('Promise', () => { before(() => { ipcMain.handle('ping', (e, arg) => arg); }); after(() => { ipcMain.removeHandler('ping'); }); itremote('resolves correctly in Node.js calls', async () => { await new Promise<void>((resolve, reject) => { class XElement extends HTMLElement {} customElements.define('x-element', XElement); setImmediate(() => { let called = false; Promise.resolve().then(() => { if (called) resolve(); else reject(new Error('wrong sequence')); }); document.createElement('x-element'); called = true; }); }); }); itremote('resolves correctly in Electron calls', async () => { await new Promise<void>((resolve, reject) => { class YElement extends HTMLElement {} customElements.define('y-element', YElement); require('electron').ipcRenderer.invoke('ping').then(() => { let called = false; Promise.resolve().then(() => { if (called) resolve(); else reject(new Error('wrong sequence')); }); document.createElement('y-element'); called = true; }); }); }); }); describe('synchronous prompts', () => { describe('window.alert(message, title)', () => { itremote('throws an exception when the arguments cannot be converted to strings', () => { expect(() => { window.alert({ toString: null }); }).to.throw('Cannot convert object to primitive value'); }); }); describe('window.confirm(message, title)', () => { itremote('throws an exception when the arguments cannot be converted to strings', () => { expect(() => { (window.confirm as any)({ toString: null }, 'title'); }).to.throw('Cannot convert object to primitive value'); }); }); }); describe('window.history', () => { describe('window.history.go(offset)', () => { itremote('throws an exception when the argument cannot be converted to a string', () => { expect(() => { (window.history.go as any)({ toString: null }); }).to.throw('Cannot convert object to primitive value'); }); }); }); describe('console functions', () => { itremote('should exist', () => { expect(console.log, 'log').to.be.a('function'); expect(console.error, 'error').to.be.a('function'); expect(console.warn, 'warn').to.be.a('function'); expect(console.info, 'info').to.be.a('function'); expect(console.debug, 'debug').to.be.a('function'); expect(console.trace, 'trace').to.be.a('function'); expect(console.time, 'time').to.be.a('function'); expect(console.timeEnd, 'timeEnd').to.be.a('function'); }); }); // FIXME(nornagon): this is broken on CI, it triggers: // [FATAL:speech_synthesis.mojom-shared.h(237)] The outgoing message will // trigger VALIDATION_ERROR_UNEXPECTED_NULL_POINTER at the receiving side // (null text in SpeechSynthesisUtterance struct). describe('SpeechSynthesis', () => { itremote('should emit lifecycle events', async () => { const sentence = `long sentence which will take at least a few seconds to utter so that it's possible to pause and resume before the end`; const utter = new SpeechSynthesisUtterance(sentence); // Create a dummy utterance so that speech synthesis state // is initialized for later calls. speechSynthesis.speak(new SpeechSynthesisUtterance()); speechSynthesis.cancel(); speechSynthesis.speak(utter); // paused state after speak() expect(speechSynthesis.paused).to.be.false(); await new Promise((resolve) => { utter.onstart = resolve; }); // paused state after start event expect(speechSynthesis.paused).to.be.false(); speechSynthesis.pause(); // paused state changes async, right before the pause event expect(speechSynthesis.paused).to.be.false(); await new Promise((resolve) => { utter.onpause = resolve; }); expect(speechSynthesis.paused).to.be.true(); speechSynthesis.resume(); await new Promise((resolve) => { utter.onresume = resolve; }); // paused state after resume event expect(speechSynthesis.paused).to.be.false(); await new Promise((resolve) => { utter.onend = resolve; }); }); }); }); describe('font fallback', () => { async function getRenderedFonts (html: string) { const w = new BrowserWindow({ show: false }); try { await w.loadURL(`data:text/html,${html}`); w.webContents.debugger.attach(); const sendCommand = (method: string, commandParams?: any) => w.webContents.debugger.sendCommand(method, commandParams); const { nodeId } = (await sendCommand('DOM.getDocument')).root.children[0]; await sendCommand('CSS.enable'); const { fonts } = await sendCommand('CSS.getPlatformFontsForNode', { nodeId }); return fonts; } finally { w.close(); } } it('should use Helvetica for sans-serif on Mac, and Arial on Windows and Linux', async () => { const html = '<body style="font-family: sans-serif">test</body>'; const fonts = await getRenderedFonts(html); expect(fonts).to.be.an('array'); expect(fonts).to.have.length(1); if (process.platform === 'win32') { expect(fonts[0].familyName).to.equal('Arial'); } else if (process.platform === 'darwin') { expect(fonts[0].familyName).to.equal('Helvetica'); } else if (process.platform === 'linux') { expect(fonts[0].familyName).to.equal('DejaVu Sans'); } // I think this depends on the distro? We don't specify a default. }); ifit(process.platform !== 'linux')('should fall back to Japanese font for sans-serif Japanese script', async function () { const html = ` <html lang="ja-JP"> <head> <meta charset="utf-8" /> </head> <body style="font-family: sans-serif">test 智史</body> </html> `; const fonts = await getRenderedFonts(html); expect(fonts).to.be.an('array'); expect(fonts).to.have.length(1); if (process.platform === 'win32') { expect(fonts[0].familyName).to.be.oneOf(['Meiryo', 'Yu Gothic']); } else if (process.platform === 'darwin') { expect(fonts[0].familyName).to.equal('Hiragino Kaku Gothic ProN'); } }); }); describe('iframe using HTML fullscreen API while window is OS-fullscreened', () => { const fullscreenChildHtml = promisify(fs.readFile)( path.join(fixturesPath, 'pages', 'fullscreen-oopif.html') ); let w: BrowserWindow; let server: http.Server; let crossSiteUrl: string; beforeEach(async () => { server = http.createServer(async (_req, res) => { res.writeHead(200, { 'Content-Type': 'text/html' }); res.write(await fullscreenChildHtml); res.end(); }); const serverUrl = (await listen(server)).url; crossSiteUrl = serverUrl.replace('127.0.0.1', 'localhost'); w = new BrowserWindow({ show: true, fullscreen: true, webPreferences: { nodeIntegration: true, nodeIntegrationInSubFrames: true, contextIsolation: false } }); }); afterEach(async () => { await closeAllWindows(); (w as any) = null; server.close(); }); ifit(process.platform !== 'darwin')('can fullscreen from out-of-process iframes (non-macOS)', async () => { const fullscreenChange = once(ipcMain, 'fullscreenChange'); const html = `<iframe style="width: 0" frameborder=0 src="${crossSiteUrl}" allowfullscreen></iframe>`; w.loadURL(`data:text/html,${html}`); await fullscreenChange; const fullscreenWidth = await w.webContents.executeJavaScript( "document.querySelector('iframe').offsetWidth" ); expect(fullscreenWidth > 0).to.be.true(); await w.webContents.executeJavaScript( "document.querySelector('iframe').contentWindow.postMessage('exitFullscreen', '*')" ); await setTimeout(500); const width = await w.webContents.executeJavaScript( "document.querySelector('iframe').offsetWidth" ); expect(width).to.equal(0); }); ifit(process.platform === 'darwin')('can fullscreen from out-of-process iframes (macOS)', async () => { await once(w, 'enter-full-screen'); const fullscreenChange = once(ipcMain, 'fullscreenChange'); const html = `<iframe style="width: 0" frameborder=0 src="${crossSiteUrl}" allowfullscreen></iframe>`; w.loadURL(`data:text/html,${html}`); await fullscreenChange; const fullscreenWidth = await w.webContents.executeJavaScript( "document.querySelector('iframe').offsetWidth" ); expect(fullscreenWidth > 0).to.be.true(); await w.webContents.executeJavaScript( "document.querySelector('iframe').contentWindow.postMessage('exitFullscreen', '*')" ); await once(w.webContents, 'leave-html-full-screen'); const width = await w.webContents.executeJavaScript( "document.querySelector('iframe').offsetWidth" ); expect(width).to.equal(0); w.setFullScreen(false); await once(w, 'leave-full-screen'); }); // TODO(jkleinsc) fix this flaky test on WOA ifit(process.platform !== 'win32' || process.arch !== 'arm64')('can fullscreen from in-process iframes', async () => { if (process.platform === 'darwin') await once(w, 'enter-full-screen'); const fullscreenChange = once(ipcMain, 'fullscreenChange'); w.loadFile(path.join(fixturesPath, 'pages', 'fullscreen-ipif.html')); await fullscreenChange; const fullscreenWidth = await w.webContents.executeJavaScript( "document.querySelector('iframe').offsetWidth" ); expect(fullscreenWidth > 0).to.true(); await w.webContents.executeJavaScript('document.exitFullscreen()'); const width = await w.webContents.executeJavaScript( "document.querySelector('iframe').offsetWidth" ); expect(width).to.equal(0); }); }); describe('navigator.serial', () => { let w: BrowserWindow; before(async () => { w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); }); const getPorts: any = () => { return w.webContents.executeJavaScript(` navigator.serial.requestPort().then(port => port.toString()).catch(err => err.toString()); `, true); }; const notFoundError = 'NotFoundError: Failed to execute \'requestPort\' on \'Serial\': No port selected by the user.'; after(closeAllWindows); afterEach(() => { session.defaultSession.setPermissionCheckHandler(null); session.defaultSession.removeAllListeners('select-serial-port'); }); it('does not return a port if select-serial-port event is not defined', async () => { w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); const port = await getPorts(); expect(port).to.equal(notFoundError); }); it('does not return a port when permission denied', async () => { w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => { callback(portList[0].portId); }); session.defaultSession.setPermissionCheckHandler(() => false); const port = await getPorts(); expect(port).to.equal(notFoundError); }); it('does not crash when select-serial-port is called with an invalid port', async () => { w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => { callback('i-do-not-exist'); }); const port = await getPorts(); expect(port).to.equal(notFoundError); }); it('returns a port when select-serial-port event is defined', async () => { let havePorts = false; w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => { if (portList.length > 0) { havePorts = true; callback(portList[0].portId); } else { callback(''); } }); const port = await getPorts(); if (havePorts) { expect(port).to.equal('[object SerialPort]'); } else { expect(port).to.equal(notFoundError); } }); it('navigator.serial.getPorts() returns values', async () => { let havePorts = false; w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => { if (portList.length > 0) { havePorts = true; callback(portList[0].portId); } else { callback(''); } }); await getPorts(); if (havePorts) { const grantedPorts = await w.webContents.executeJavaScript('navigator.serial.getPorts()'); expect(grantedPorts).to.not.be.empty(); } }); it('supports port.forget()', async () => { let forgottenPortFromEvent = {}; let havePorts = false; w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => { if (portList.length > 0) { havePorts = true; callback(portList[0].portId); } else { callback(''); } }); w.webContents.session.on('serial-port-revoked', (event, details) => { forgottenPortFromEvent = details.port; }); await getPorts(); if (havePorts) { const grantedPorts = await w.webContents.executeJavaScript('navigator.serial.getPorts()'); if (grantedPorts.length > 0) { const forgottenPort = await w.webContents.executeJavaScript(` navigator.serial.getPorts().then(async(ports) => { const portInfo = await ports[0].getInfo(); await ports[0].forget(); if (portInfo.usbVendorId && portInfo.usbProductId) { return { vendorId: '' + portInfo.usbVendorId, productId: '' + portInfo.usbProductId } } else { return {}; } }) `); const grantedPorts2 = await w.webContents.executeJavaScript('navigator.serial.getPorts()'); expect(grantedPorts2.length).to.be.lessThan(grantedPorts.length); if (forgottenPort.vendorId && forgottenPort.productId) { expect(forgottenPortFromEvent).to.include(forgottenPort); } } } }); }); describe('window.getScreenDetails', () => { let w: BrowserWindow; before(async () => { w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); }); after(closeAllWindows); afterEach(() => { session.defaultSession.setPermissionRequestHandler(null); }); const getScreenDetails: any = () => { return w.webContents.executeJavaScript('window.getScreenDetails().then(data => data.screens).catch(err => err.message)', true); }; it('returns screens when a PermissionRequestHandler is not defined', async () => { const screens = await getScreenDetails(); expect(screens).to.not.equal('Read permission denied.'); }); it('returns an error when permission denied', async () => { session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => { if (permission === 'window-management') { callback(false); } else { callback(true); } }); const screens = await getScreenDetails(); expect(screens).to.equal('Permission denied.'); }); it('returns screens when permission is granted', async () => { session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => { if (permission === 'window-management') { callback(true); } else { callback(false); } }); const screens = await getScreenDetails(); expect(screens).to.not.equal('Permission denied.'); }); }); describe('navigator.clipboard.read', () => { let w: BrowserWindow; before(async () => { w = new BrowserWindow(); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); }); const readClipboard: any = () => { return w.webContents.executeJavaScript(` navigator.clipboard.read().then(clipboard => clipboard.toString()).catch(err => err.message); `, true); }; after(closeAllWindows); afterEach(() => { session.defaultSession.setPermissionRequestHandler(null); }); it('returns clipboard contents when a PermissionRequestHandler is not defined', async () => { const clipboard = await readClipboard(); expect(clipboard).to.not.equal('Read permission denied.'); }); it('returns an error when permission denied', async () => { session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => { if (permission === 'clipboard-read') { callback(false); } else { callback(true); } }); const clipboard = await readClipboard(); expect(clipboard).to.equal('Read permission denied.'); }); it('returns clipboard contents when permission is granted', async () => { session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => { if (permission === 'clipboard-read') { callback(true); } else { callback(false); } }); const clipboard = await readClipboard(); expect(clipboard).to.not.equal('Read permission denied.'); }); }); describe('navigator.clipboard.write', () => { let w: BrowserWindow; before(async () => { w = new BrowserWindow(); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); }); const writeClipboard: any = () => { return w.webContents.executeJavaScript(` navigator.clipboard.writeText('Hello World!').catch(err => err.message); `, true); }; after(closeAllWindows); afterEach(() => { session.defaultSession.setPermissionRequestHandler(null); }); it('returns clipboard contents when a PermissionRequestHandler is not defined', async () => { const clipboard = await writeClipboard(); expect(clipboard).to.not.equal('Write permission denied.'); }); it('returns an error when permission denied', async () => { session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => { if (permission === 'clipboard-sanitized-write') { callback(false); } else { callback(true); } }); const clipboard = await writeClipboard(); expect(clipboard).to.equal('Write permission denied.'); }); it('returns clipboard contents when permission is granted', async () => { session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => { if (permission === 'clipboard-sanitized-write') { callback(true); } else { callback(false); } }); const clipboard = await writeClipboard(); expect(clipboard).to.not.equal('Write permission denied.'); }); }); ifdescribe((process.platform !== 'linux' || app.isUnityRunning()))('navigator.setAppBadge/clearAppBadge', () => { let w: BrowserWindow; const expectedBadgeCount = 42; const fireAppBadgeAction: any = (action: string, value: any) => { return w.webContents.executeJavaScript(` navigator.${action}AppBadge(${value}).then(() => 'success').catch(err => err.message)`); }; // For some reason on macOS changing the badge count doesn't happen right away, so wait // until it changes. async function waitForBadgeCount (value: number) { let badgeCount = app.getBadgeCount(); while (badgeCount !== value) { await setTimeout(10); badgeCount = app.getBadgeCount(); } return badgeCount; } describe('in the renderer', () => { before(async () => { w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); }); after(() => { app.badgeCount = 0; closeAllWindows(); }); it('setAppBadge can set a numerical value', async () => { const result = await fireAppBadgeAction('set', expectedBadgeCount); expect(result).to.equal('success'); expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount); }); it('setAppBadge can set an empty(dot) value', async () => { const result = await fireAppBadgeAction('set'); expect(result).to.equal('success'); expect(waitForBadgeCount(0)).to.eventually.equal(0); }); it('clearAppBadge can clear a value', async () => { let result = await fireAppBadgeAction('set', expectedBadgeCount); expect(result).to.equal('success'); expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount); result = await fireAppBadgeAction('clear'); expect(result).to.equal('success'); expect(waitForBadgeCount(0)).to.eventually.equal(0); }); }); describe('in a service worker', () => { beforeEach(async () => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, partition: 'sw-file-scheme-spec', contextIsolation: false } }); }); afterEach(() => { app.badgeCount = 0; closeAllWindows(); }); it('setAppBadge can be called in a ServiceWorker', (done) => { w.webContents.on('ipc-message', (event, channel, message) => { if (channel === 'reload') { w.webContents.reload(); } else if (channel === 'error') { done(message); } else if (channel === 'response') { expect(message).to.equal('SUCCESS setting app badge'); expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount); session.fromPartition('sw-file-scheme-spec').clearStorageData({ storages: ['serviceworkers'] }).then(() => done()); } }); w.webContents.on('render-process-gone', () => done(new Error('WebContents crashed.'))); w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'badge-index.html'), { search: '?setBadge' }); }); it('clearAppBadge can be called in a ServiceWorker', (done) => { w.webContents.on('ipc-message', (event, channel, message) => { if (channel === 'reload') { w.webContents.reload(); } else if (channel === 'setAppBadge') { expect(message).to.equal('SUCCESS setting app badge'); expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount); } else if (channel === 'error') { done(message); } else if (channel === 'response') { expect(message).to.equal('SUCCESS clearing app badge'); expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount); session.fromPartition('sw-file-scheme-spec').clearStorageData({ storages: ['serviceworkers'] }).then(() => done()); } }); w.webContents.on('render-process-gone', () => done(new Error('WebContents crashed.'))); w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'badge-index.html'), { search: '?clearBadge' }); }); }); }); describe('navigator.bluetooth', () => { let w: BrowserWindow; before(async () => { w = new BrowserWindow({ show: false, webPreferences: { enableBlinkFeatures: 'WebBluetooth' } }); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); }); after(closeAllWindows); it('can request bluetooth devices', async () => { const bluetooth = await w.webContents.executeJavaScript(` navigator.bluetooth.requestDevice({ acceptAllDevices: true}).then(device => "Found a device!").catch(err => err.message);`, true); expect(bluetooth).to.be.oneOf(['Found a device!', 'Bluetooth adapter not available.', 'User cancelled the requestDevice() chooser.']); }); }); describe('navigator.hid', () => { let w: BrowserWindow; let server: http.Server; let serverUrl: string; before(async () => { w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); server = http.createServer((req, res) => { res.setHeader('Content-Type', 'text/html'); res.end('<body>'); }); serverUrl = (await listen(server)).url; }); const requestDevices: any = () => { return w.webContents.executeJavaScript(` navigator.hid.requestDevice({filters: []}).then(device => device.toString()).catch(err => err.toString()); `, true); }; after(() => { server.close(); closeAllWindows(); }); afterEach(() => { session.defaultSession.setPermissionCheckHandler(null); session.defaultSession.setDevicePermissionHandler(null); session.defaultSession.removeAllListeners('select-hid-device'); }); it('does not return a device if select-hid-device event is not defined', async () => { w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); const device = await requestDevices(); expect(device).to.equal(''); }); it('does not return a device when permission denied', async () => { let selectFired = false; w.webContents.session.on('select-hid-device', (event, details, callback) => { selectFired = true; callback(); }); session.defaultSession.setPermissionCheckHandler(() => false); const device = await requestDevices(); expect(selectFired).to.be.false(); expect(device).to.equal(''); }); it('returns a device when select-hid-device event is defined', async () => { let haveDevices = false; let selectFired = false; w.webContents.session.on('select-hid-device', (event, details, callback) => { expect(details.frame).to.have.property('frameTreeNodeId').that.is.a('number'); selectFired = true; if (details.deviceList.length > 0) { haveDevices = true; callback(details.deviceList[0].deviceId); } else { callback(); } }); const device = await requestDevices(); expect(selectFired).to.be.true(); if (haveDevices) { expect(device).to.contain('[object HIDDevice]'); } else { expect(device).to.equal(''); } if (haveDevices) { // Verify that navigation will clear device permissions const grantedDevices = await w.webContents.executeJavaScript('navigator.hid.getDevices()'); expect(grantedDevices).to.not.be.empty(); w.loadURL(serverUrl); const [,,,,, frameProcessId, frameRoutingId] = await once(w.webContents, 'did-frame-navigate'); const frame = webFrameMain.fromId(frameProcessId, frameRoutingId); expect(!!frame).to.be.true(); if (frame) { const grantedDevicesOnNewPage = await frame.executeJavaScript('navigator.hid.getDevices()'); expect(grantedDevicesOnNewPage).to.be.empty(); } } }); it('returns a device when DevicePermissionHandler is defined', async () => { let haveDevices = false; let selectFired = false; let gotDevicePerms = false; w.webContents.session.on('select-hid-device', (event, details, callback) => { selectFired = true; if (details.deviceList.length > 0) { const foundDevice = details.deviceList.find((device) => { if (device.name && device.name !== '' && device.serialNumber && device.serialNumber !== '') { haveDevices = true; return true; } }); if (foundDevice) { callback(foundDevice.deviceId); return; } } callback(); }); session.defaultSession.setDevicePermissionHandler(() => { gotDevicePerms = true; return true; }); await w.webContents.executeJavaScript('navigator.hid.getDevices();', true); const device = await requestDevices(); expect(selectFired).to.be.true(); if (haveDevices) { expect(device).to.contain('[object HIDDevice]'); expect(gotDevicePerms).to.be.true(); } else { expect(device).to.equal(''); } }); it('excludes a device when a exclusionFilter is specified', async () => { const exclusionFilters = <any>[]; let haveDevices = false; let checkForExcludedDevice = false; w.webContents.session.on('select-hid-device', (event, details, callback) => { if (details.deviceList.length > 0) { details.deviceList.find((device) => { if (device.name && device.name !== '' && device.serialNumber && device.serialNumber !== '') { if (checkForExcludedDevice) { const compareDevice = { vendorId: device.vendorId, productId: device.productId }; expect(compareDevice).to.not.equal(exclusionFilters[0], 'excluded device should not be returned'); } else { haveDevices = true; exclusionFilters.push({ vendorId: device.vendorId, productId: device.productId }); return true; } } }); } callback(); }); await requestDevices(); if (haveDevices) { // We have devices to exclude, so check if exclusionFilters work checkForExcludedDevice = true; await w.webContents.executeJavaScript(` navigator.hid.requestDevice({filters: [], exclusionFilters: ${JSON.stringify(exclusionFilters)}}).then(device => device.toString()).catch(err => err.toString()); `, true); } }); it('supports device.forget()', async () => { let deletedDeviceFromEvent; let haveDevices = false; w.webContents.session.on('select-hid-device', (event, details, callback) => { if (details.deviceList.length > 0) { haveDevices = true; callback(details.deviceList[0].deviceId); } else { callback(); } }); w.webContents.session.on('hid-device-revoked', (event, details) => { deletedDeviceFromEvent = details.device; }); await requestDevices(); if (haveDevices) { const grantedDevices = await w.webContents.executeJavaScript('navigator.hid.getDevices()'); if (grantedDevices.length > 0) { const deletedDevice = await w.webContents.executeJavaScript(` navigator.hid.getDevices().then(devices => { devices[0].forget(); return { vendorId: devices[0].vendorId, productId: devices[0].productId, name: devices[0].productName } }) `); const grantedDevices2 = await w.webContents.executeJavaScript('navigator.hid.getDevices()'); expect(grantedDevices2.length).to.be.lessThan(grantedDevices.length); if (deletedDevice.name !== '' && deletedDevice.productId && deletedDevice.vendorId) { expect(deletedDeviceFromEvent).to.include(deletedDevice); } } } }); }); describe('navigator.usb', () => { let w: BrowserWindow; let server: http.Server; let serverUrl: string; before(async () => { w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); server = http.createServer((req, res) => { res.setHeader('Content-Type', 'text/html'); res.end('<body>'); }); serverUrl = (await listen(server)).url; }); const requestDevices: any = () => { return w.webContents.executeJavaScript(` navigator.usb.requestDevice({filters: []}).then(device => device.toString()).catch(err => err.toString()); `, true); }; const notFoundError = 'NotFoundError: Failed to execute \'requestDevice\' on \'USB\': No device selected.'; after(() => { server.close(); closeAllWindows(); }); afterEach(() => { session.defaultSession.setPermissionCheckHandler(null); session.defaultSession.setDevicePermissionHandler(null); session.defaultSession.removeAllListeners('select-usb-device'); }); it('does not return a device if select-usb-device event is not defined', async () => { w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); const device = await requestDevices(); expect(device).to.equal(notFoundError); }); it('does not return a device when permission denied', async () => { let selectFired = false; w.webContents.session.on('select-usb-device', (event, details, callback) => { selectFired = true; callback(); }); session.defaultSession.setPermissionCheckHandler(() => false); const device = await requestDevices(); expect(selectFired).to.be.false(); expect(device).to.equal(notFoundError); }); it('returns a device when select-usb-device event is defined', async () => { let haveDevices = false; let selectFired = false; w.webContents.session.on('select-usb-device', (event, details, callback) => { expect(details.frame).to.have.property('frameTreeNodeId').that.is.a('number'); selectFired = true; if (details.deviceList.length > 0) { haveDevices = true; callback(details.deviceList[0].deviceId); } else { callback(); } }); const device = await requestDevices(); expect(selectFired).to.be.true(); if (haveDevices) { expect(device).to.contain('[object USBDevice]'); } else { expect(device).to.equal(notFoundError); } if (haveDevices) { // Verify that navigation will clear device permissions const grantedDevices = await w.webContents.executeJavaScript('navigator.usb.getDevices()'); expect(grantedDevices).to.not.be.empty(); w.loadURL(serverUrl); const [,,,,, frameProcessId, frameRoutingId] = await once(w.webContents, 'did-frame-navigate'); const frame = webFrameMain.fromId(frameProcessId, frameRoutingId); expect(!!frame).to.be.true(); if (frame) { const grantedDevicesOnNewPage = await frame.executeJavaScript('navigator.usb.getDevices()'); expect(grantedDevicesOnNewPage).to.be.empty(); } } }); it('returns a device when DevicePermissionHandler is defined', async () => { let haveDevices = false; let selectFired = false; let gotDevicePerms = false; w.webContents.session.on('select-usb-device', (event, details, callback) => { selectFired = true; if (details.deviceList.length > 0) { const foundDevice = details.deviceList.find((device) => { if (device.productName && device.productName !== '' && device.serialNumber && device.serialNumber !== '') { haveDevices = true; return true; } }); if (foundDevice) { callback(foundDevice.deviceId); return; } } callback(); }); session.defaultSession.setDevicePermissionHandler(() => { gotDevicePerms = true; return true; }); await w.webContents.executeJavaScript('navigator.usb.getDevices();', true); const device = await requestDevices(); expect(selectFired).to.be.true(); if (haveDevices) { expect(device).to.contain('[object USBDevice]'); expect(gotDevicePerms).to.be.true(); } else { expect(device).to.equal(notFoundError); } }); it('supports device.forget()', async () => { let deletedDeviceFromEvent; let haveDevices = false; w.webContents.session.on('select-usb-device', (event, details, callback) => { if (details.deviceList.length > 0) { haveDevices = true; callback(details.deviceList[0].deviceId); } else { callback(); } }); w.webContents.session.on('usb-device-revoked', (event, details) => { deletedDeviceFromEvent = details.device; }); await requestDevices(); if (haveDevices) { const grantedDevices = await w.webContents.executeJavaScript('navigator.usb.getDevices()'); if (grantedDevices.length > 0) { const deletedDevice: Electron.USBDevice = await w.webContents.executeJavaScript(` navigator.usb.getDevices().then(devices => { devices[0].forget(); return { vendorId: devices[0].vendorId, productId: devices[0].productId, productName: devices[0].productName } }) `); const grantedDevices2 = await w.webContents.executeJavaScript('navigator.usb.getDevices()'); expect(grantedDevices2.length).to.be.lessThan(grantedDevices.length); if (deletedDevice.productName !== '' && deletedDevice.productId && deletedDevice.vendorId) { expect(deletedDeviceFromEvent).to.include(deletedDevice); } } } }); });
closed
electron/electron
https://github.com/electron/electron
38,161
[Feature Request]: Allow commonjs2 scripts as sandboxed preload scripts
### 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. ### Problem Description When calling a preload script in sandboxed mode, `module` is not defined. This makes code that assigns `module.exports` crash with an error like "ReferenceError: module is not defined". This is made even more confusing since electron also emits an error "Unable to load preload script" which implies that the script was not found, and not just partly executed. This is a problem because many commonjs modules assign the `module.exports` property, as per [Node's documentation](https://nodejs.org/api/modules.html#the-module-object): > The `module.exports` object is created by the `Module` system. Sometimes this is not acceptable; many want their module to be an instance of some class. To do this, assign the desired export object to `module.exports`. Problematic commonjs scripts are created by: - `webpack` in ['commonjs2' mode](https://webpack.js.org/configuration/output/#type-commonjs2), which is the recommended format (see, e.g. Quasar https://github.com/quasarframework/quasar/issues/11759) - `esbuild` - `parcel` It seems that `rollup`, `swc`, and `typescript` do not reassign `module.exports` and so are not affected. ### Proposed Solution - Pass a `module` object with a mutable `exports` property to the [preload wrapper](https://github.com/electron/electron/blob/a8c0ed890f61664156886356ecb6ab9f73c69cf1/lib/sandboxed_renderer/init.ts#L105-L107). ### Alternatives Considered - Load the preload script as an ESM module - Use a module loader (e.g. an actual call to `require`) instead of interpolating the preload script into an `eval` call. ### Additional Information I'm not sure if this should be regarded as a feature request or a bug. It's quite surprising behavior and probably not intentional, so I'm leaning toward bug.
https://github.com/electron/electron/issues/38161
https://github.com/electron/electron/pull/39484
90865fa97d577105987d23db017c0332029228f6
3102a257af400e8b9bdddf4295d901007c65a2d6
2023-05-03T07:01:40Z
c++
2023-08-22T04:43:08Z
spec/fixtures/module/preload.js
const types = { require: typeof require, module: typeof module, process: typeof process, Buffer: typeof Buffer }; console.log(JSON.stringify(types));
closed
electron/electron
https://github.com/electron/electron
38,161
[Feature Request]: Allow commonjs2 scripts as sandboxed preload scripts
### 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. ### Problem Description When calling a preload script in sandboxed mode, `module` is not defined. This makes code that assigns `module.exports` crash with an error like "ReferenceError: module is not defined". This is made even more confusing since electron also emits an error "Unable to load preload script" which implies that the script was not found, and not just partly executed. This is a problem because many commonjs modules assign the `module.exports` property, as per [Node's documentation](https://nodejs.org/api/modules.html#the-module-object): > The `module.exports` object is created by the `Module` system. Sometimes this is not acceptable; many want their module to be an instance of some class. To do this, assign the desired export object to `module.exports`. Problematic commonjs scripts are created by: - `webpack` in ['commonjs2' mode](https://webpack.js.org/configuration/output/#type-commonjs2), which is the recommended format (see, e.g. Quasar https://github.com/quasarframework/quasar/issues/11759) - `esbuild` - `parcel` It seems that `rollup`, `swc`, and `typescript` do not reassign `module.exports` and so are not affected. ### Proposed Solution - Pass a `module` object with a mutable `exports` property to the [preload wrapper](https://github.com/electron/electron/blob/a8c0ed890f61664156886356ecb6ab9f73c69cf1/lib/sandboxed_renderer/init.ts#L105-L107). ### Alternatives Considered - Load the preload script as an ESM module - Use a module loader (e.g. an actual call to `require`) instead of interpolating the preload script into an `eval` call. ### Additional Information I'm not sure if this should be regarded as a feature request or a bug. It's quite surprising behavior and probably not intentional, so I'm leaning toward bug.
https://github.com/electron/electron/issues/38161
https://github.com/electron/electron/pull/39484
90865fa97d577105987d23db017c0332029228f6
3102a257af400e8b9bdddf4295d901007c65a2d6
2023-05-03T07:01:40Z
c++
2023-08-22T04:43:08Z
lib/sandboxed_renderer/init.ts
import * as events from 'events'; import { IPC_MESSAGES } from '@electron/internal/common/ipc-messages'; import type * as ipcRendererUtilsModule from '@electron/internal/renderer/ipc-renderer-internal-utils'; import type * as ipcRendererInternalModule from '@electron/internal/renderer/ipc-renderer-internal'; declare const binding: { get: (name: string) => any; process: NodeJS.Process; createPreloadScript: (src: string) => Function }; const { EventEmitter } = events; process._linkedBinding = binding.get; const v8Util = process._linkedBinding('electron_common_v8_util'); // Expose Buffer shim as a hidden value. This is used by C++ code to // deserialize Buffer instances sent from browser process. v8Util.setHiddenValue(global, 'Buffer', Buffer); // The process object created by webpack is not an event emitter, fix it so // the API is more compatible with non-sandboxed renderers. for (const prop of Object.keys(EventEmitter.prototype) as (keyof typeof process)[]) { if (Object.hasOwn(process, prop)) { delete process[prop]; } } Object.setPrototypeOf(process, EventEmitter.prototype); const { ipcRendererInternal } = require('@electron/internal/renderer/ipc-renderer-internal') as typeof ipcRendererInternalModule; const ipcRendererUtils = require('@electron/internal/renderer/ipc-renderer-internal-utils') as typeof ipcRendererUtilsModule; const { preloadScripts, process: processProps } = ipcRendererUtils.invokeSync<{ preloadScripts: { preloadPath: string; preloadSrc: string | null; preloadError: null | Error; }[]; process: NodeJS.Process; }>(IPC_MESSAGES.BROWSER_SANDBOX_LOAD); const electron = require('electron'); const loadedModules = new Map<string, any>([ ['electron', electron], ['electron/common', electron], ['electron/renderer', electron], ['events', events], ['node:events', events] ]); const loadableModules = new Map<string, Function>([ ['timers', () => require('timers')], ['node:timers', () => require('timers')], ['url', () => require('url')], ['node:url', () => require('url')] ]); // Pass different process object to the preload script. const preloadProcess: NodeJS.Process = new EventEmitter() as any; // InvokeEmitProcessEvent in ElectronSandboxedRendererClient will look for this v8Util.setHiddenValue(global, 'emit-process-event', (event: string) => { (process as events.EventEmitter).emit(event); (preloadProcess as events.EventEmitter).emit(event); }); Object.assign(preloadProcess, binding.process); Object.assign(preloadProcess, processProps); Object.assign(process, binding.process); Object.assign(process, processProps); process.getProcessMemoryInfo = preloadProcess.getProcessMemoryInfo = () => { return ipcRendererInternal.invoke<Electron.ProcessMemoryInfo>(IPC_MESSAGES.BROWSER_GET_PROCESS_MEMORY_INFO); }; Object.defineProperty(preloadProcess, 'noDeprecation', { get () { return process.noDeprecation; }, set (value) { process.noDeprecation = value; } }); // This is the `require` function that will be visible to the preload script function preloadRequire (module: string) { if (loadedModules.has(module)) { return loadedModules.get(module); } if (loadableModules.has(module)) { const loadedModule = loadableModules.get(module)!(); loadedModules.set(module, loadedModule); return loadedModule; } throw new Error(`module not found: ${module}`); } // Process command line arguments. const { hasSwitch } = process._linkedBinding('electron_common_command_line'); // Similar to nodes --expose-internals flag, this exposes _linkedBinding so // that tests can call it to get access to some test only bindings if (hasSwitch('unsafely-expose-electron-internals-for-testing')) { preloadProcess._linkedBinding = process._linkedBinding; } // Common renderer initialization require('@electron/internal/renderer/common-init'); // Wrap the script into a function executed in global scope. It won't have // access to the current scope, so we'll expose a few objects as arguments: // // - `require`: The `preloadRequire` function // - `process`: The `preloadProcess` object // - `Buffer`: Shim of `Buffer` implementation // - `global`: The window object, which is aliased to `global` by webpack. function runPreloadScript (preloadSrc: string) { const preloadWrapperSrc = `(function(require, process, Buffer, global, setImmediate, clearImmediate, exports) { ${preloadSrc} })`; // eval in window scope const preloadFn = binding.createPreloadScript(preloadWrapperSrc); const { setImmediate, clearImmediate } = require('timers'); preloadFn(preloadRequire, preloadProcess, Buffer, global, setImmediate, clearImmediate, {}); } for (const { preloadPath, preloadSrc, preloadError } of preloadScripts) { try { if (preloadSrc) { runPreloadScript(preloadSrc); } else if (preloadError) { throw preloadError; } } catch (error) { console.error(`Unable to load preload script: ${preloadPath}`); console.error(error); ipcRendererInternal.send(IPC_MESSAGES.BROWSER_PRELOAD_ERROR, preloadPath, error); } }
closed
electron/electron
https://github.com/electron/electron
38,161
[Feature Request]: Allow commonjs2 scripts as sandboxed preload scripts
### 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. ### Problem Description When calling a preload script in sandboxed mode, `module` is not defined. This makes code that assigns `module.exports` crash with an error like "ReferenceError: module is not defined". This is made even more confusing since electron also emits an error "Unable to load preload script" which implies that the script was not found, and not just partly executed. This is a problem because many commonjs modules assign the `module.exports` property, as per [Node's documentation](https://nodejs.org/api/modules.html#the-module-object): > The `module.exports` object is created by the `Module` system. Sometimes this is not acceptable; many want their module to be an instance of some class. To do this, assign the desired export object to `module.exports`. Problematic commonjs scripts are created by: - `webpack` in ['commonjs2' mode](https://webpack.js.org/configuration/output/#type-commonjs2), which is the recommended format (see, e.g. Quasar https://github.com/quasarframework/quasar/issues/11759) - `esbuild` - `parcel` It seems that `rollup`, `swc`, and `typescript` do not reassign `module.exports` and so are not affected. ### Proposed Solution - Pass a `module` object with a mutable `exports` property to the [preload wrapper](https://github.com/electron/electron/blob/a8c0ed890f61664156886356ecb6ab9f73c69cf1/lib/sandboxed_renderer/init.ts#L105-L107). ### Alternatives Considered - Load the preload script as an ESM module - Use a module loader (e.g. an actual call to `require`) instead of interpolating the preload script into an `eval` call. ### Additional Information I'm not sure if this should be regarded as a feature request or a bug. It's quite surprising behavior and probably not intentional, so I'm leaning toward bug.
https://github.com/electron/electron/issues/38161
https://github.com/electron/electron/pull/39484
90865fa97d577105987d23db017c0332029228f6
3102a257af400e8b9bdddf4295d901007c65a2d6
2023-05-03T07:01:40Z
c++
2023-08-22T04:43:08Z
spec/chromium-spec.ts
import { expect } from 'chai'; import { BrowserWindow, WebContents, webFrameMain, session, ipcMain, app, protocol, webContents } from 'electron/main'; import { closeAllWindows } from './lib/window-helpers'; import * as https from 'node:https'; import * as http from 'node:http'; import * as path from 'node:path'; import * as fs from 'node:fs'; import * as url from 'node:url'; import * as ChildProcess from 'node:child_process'; import { EventEmitter, once } from 'node:events'; import { promisify } from 'node:util'; import { ifit, ifdescribe, defer, itremote, listen } from './lib/spec-helpers'; import { PipeTransport } from './pipe-transport'; import * as ws from 'ws'; import { setTimeout } from 'node:timers/promises'; const features = process._linkedBinding('electron_common_features'); const fixturesPath = path.resolve(__dirname, 'fixtures'); const certPath = path.join(fixturesPath, 'certificates'); describe('reporting api', () => { it('sends a report for an intervention', async () => { const reporting = new EventEmitter(); // The Reporting API only works on https with valid certs. To dodge having // to set up a trusted certificate, hack the validator. session.defaultSession.setCertificateVerifyProc((req, cb) => { cb(0); }); const options = { key: fs.readFileSync(path.join(certPath, 'server.key')), cert: fs.readFileSync(path.join(certPath, 'server.pem')), ca: [ fs.readFileSync(path.join(certPath, 'rootCA.pem')), fs.readFileSync(path.join(certPath, 'intermediateCA.pem')) ], requestCert: true, rejectUnauthorized: false }; const server = https.createServer(options, (req, res) => { if (req.url?.endsWith('report')) { let data = ''; req.on('data', (d) => { data += d.toString('utf-8'); }); req.on('end', () => { reporting.emit('report', JSON.parse(data)); }); } const { port } = server.address() as any; res.setHeader('Reporting-Endpoints', `default="https://localhost:${port}/report"`); res.setHeader('Content-Type', 'text/html'); res.end('<script>window.navigator.vibrate(1)</script>'); }); await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve)); const bw = new BrowserWindow({ show: false }); try { const reportGenerated = once(reporting, 'report'); await bw.loadURL(`https://localhost:${(server.address() as any).port}/a`); const [reports] = await reportGenerated; expect(reports).to.be.an('array').with.lengthOf(1); const { type, url, body } = reports[0]; expect(type).to.equal('intervention'); expect(url).to.equal(url); expect(body.id).to.equal('NavigatorVibrate'); expect(body.message).to.match(/Blocked call to navigator.vibrate because user hasn't tapped on the frame or any embedded frame yet/); } finally { bw.destroy(); server.close(); } }); }); describe('window.postMessage', () => { afterEach(async () => { await closeAllWindows(); }); it('sets the source and origin correctly', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadURL(`file://${fixturesPath}/pages/window-open-postMessage-driver.html`); const [, message] = await once(ipcMain, 'complete'); expect(message.data).to.equal('testing'); expect(message.origin).to.equal('file://'); expect(message.sourceEqualsOpener).to.equal(true); expect(message.eventOrigin).to.equal('file://'); }); }); describe('focus handling', () => { let webviewContents: WebContents; let w: BrowserWindow; beforeEach(async () => { w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true, webviewTag: true, contextIsolation: false } }); const webviewReady = once(w.webContents, 'did-attach-webview') as Promise<[any, WebContents]>; await w.loadFile(path.join(fixturesPath, 'pages', 'tab-focus-loop-elements.html')); const [, wvContents] = await webviewReady; webviewContents = wvContents; await once(webviewContents, 'did-finish-load'); w.focus(); }); afterEach(() => { webviewContents = null as unknown as WebContents; w.destroy(); w = null as unknown as BrowserWindow; }); const expectFocusChange = async () => { const [, focusedElementId] = await once(ipcMain, 'focus-changed'); return focusedElementId; }; describe('a TAB press', () => { const tabPressEvent: any = { type: 'keyDown', keyCode: 'Tab' }; it('moves focus to the next focusable item', async () => { let focusChange = expectFocusChange(); w.webContents.sendInputEvent(tabPressEvent); let focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-element-1', `should start focused in element-1, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); w.webContents.sendInputEvent(tabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-element-2', `focus should've moved to element-2, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); w.webContents.sendInputEvent(tabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-wv-element-1', `focus should've moved to the webview's element-1, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); webviewContents.sendInputEvent(tabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-wv-element-2', `focus should've moved to the webview's element-2, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); webviewContents.sendInputEvent(tabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-element-3', `focus should've moved to element-3, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); w.webContents.sendInputEvent(tabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-element-1', `focus should've looped back to element-1, it's instead in ${focusedElementId}`); }); }); describe('a SHIFT + TAB press', () => { const shiftTabPressEvent: any = { type: 'keyDown', modifiers: ['Shift'], keyCode: 'Tab' }; it('moves focus to the previous focusable item', async () => { let focusChange = expectFocusChange(); w.webContents.sendInputEvent(shiftTabPressEvent); let focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-element-3', `should start focused in element-3, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); w.webContents.sendInputEvent(shiftTabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-wv-element-2', `focus should've moved to the webview's element-2, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); webviewContents.sendInputEvent(shiftTabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-wv-element-1', `focus should've moved to the webview's element-1, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); webviewContents.sendInputEvent(shiftTabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-element-2', `focus should've moved to element-2, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); w.webContents.sendInputEvent(shiftTabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-element-1', `focus should've moved to element-1, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); w.webContents.sendInputEvent(shiftTabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-element-3', `focus should've looped back to element-3, it's instead in ${focusedElementId}`); }); }); }); describe('web security', () => { afterEach(closeAllWindows); let server: http.Server; let serverUrl: string; before(async () => { server = http.createServer((req, res) => { res.setHeader('Content-Type', 'text/html'); res.end('<body>'); }); serverUrl = (await listen(server)).url; }); after(() => { server.close(); }); it('engages CORB when web security is not disabled', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: true, nodeIntegration: true, contextIsolation: false } }); const p = once(ipcMain, 'success'); await w.loadURL(`data:text/html,<script> const s = document.createElement('script') s.src = "${serverUrl}" // The script will load successfully but its body will be emptied out // by CORB, so we don't expect a syntax error. s.onload = () => { require('electron').ipcRenderer.send('success') } document.documentElement.appendChild(s) </script>`); await p; }); it('bypasses CORB when web security is disabled', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: false, nodeIntegration: true, contextIsolation: false } }); const p = once(ipcMain, 'success'); await w.loadURL(`data:text/html, <script> window.onerror = (e) => { require('electron').ipcRenderer.send('success', e) } </script> <script src="${serverUrl}"></script>`); await p; }); it('engages CORS when web security is not disabled', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: true, nodeIntegration: true, contextIsolation: false } }); const p = once(ipcMain, 'response'); await w.loadURL(`data:text/html,<script> (async function() { try { await fetch('${serverUrl}'); require('electron').ipcRenderer.send('response', 'passed'); } catch { require('electron').ipcRenderer.send('response', 'failed'); } })(); </script>`); const [, response] = await p; expect(response).to.equal('failed'); }); it('bypasses CORS when web security is disabled', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: false, nodeIntegration: true, contextIsolation: false } }); const p = once(ipcMain, 'response'); await w.loadURL(`data:text/html,<script> (async function() { try { await fetch('${serverUrl}'); require('electron').ipcRenderer.send('response', 'passed'); } catch { require('electron').ipcRenderer.send('response', 'failed'); } })(); </script>`); const [, response] = await p; expect(response).to.equal('passed'); }); describe('accessing file://', () => { async function loadFile (w: BrowserWindow) { const thisFile = url.format({ pathname: __filename.replace(/\\/g, '/'), protocol: 'file', slashes: true }); await w.loadURL(`data:text/html,<script> function loadFile() { return new Promise((resolve) => { fetch('${thisFile}').then( () => resolve('loaded'), () => resolve('failed') ) }); } </script>`); return await w.webContents.executeJavaScript('loadFile()'); } it('is forbidden when web security is enabled', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: true } }); const result = await loadFile(w); expect(result).to.equal('failed'); }); it('is allowed when web security is disabled', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: false } }); const result = await loadFile(w); expect(result).to.equal('loaded'); }); }); describe('wasm-eval csp', () => { async function loadWasm (csp: string) { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, enableBlinkFeatures: 'WebAssemblyCSP' } }); await w.loadURL(`data:text/html,<head> <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-inline' ${csp}"> </head> <script> function loadWasm() { const wasmBin = new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0]) return new Promise((resolve) => { WebAssembly.instantiate(wasmBin).then(() => { resolve('loaded') }).catch((error) => { resolve(error.message) }) }); } </script>`); return await w.webContents.executeJavaScript('loadWasm()'); } it('wasm codegen is disallowed by default', async () => { const r = await loadWasm(''); expect(r).to.equal('WebAssembly.instantiate(): Refused to compile or instantiate WebAssembly module because \'unsafe-eval\' is not an allowed source of script in the following Content Security Policy directive: "script-src \'self\' \'unsafe-inline\'"'); }); it('wasm codegen is allowed with "wasm-unsafe-eval" csp', async () => { const r = await loadWasm("'wasm-unsafe-eval'"); expect(r).to.equal('loaded'); }); }); describe('csp', () => { for (const sandbox of [true, false]) { describe(`when sandbox: ${sandbox}`, () => { for (const contextIsolation of [true, false]) { describe(`when contextIsolation: ${contextIsolation}`, () => { it('prevents eval from running in an inline script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox, contextIsolation } }); w.loadURL(`data:text/html,<head> <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-inline'"> </head> <script> try { // We use console.log here because it is easier than making a // preload script, and the behavior under test changes when // contextIsolation: false console.log(eval('true')) } catch (e) { console.log(e.message) } </script>`); const [,, message] = await once(w.webContents, 'console-message'); expect(message).to.match(/Refused to evaluate a string/); }); it('does not prevent eval from running in an inline script when there is no csp', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox, contextIsolation } }); w.loadURL(`data:text/html, <script> try { // We use console.log here because it is easier than making a // preload script, and the behavior under test changes when // contextIsolation: false console.log(eval('true')) } catch (e) { console.log(e.message) } </script>`); const [,, message] = await once(w.webContents, 'console-message'); expect(message).to.equal('true'); }); it('prevents eval from running in executeJavaScript', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox, contextIsolation } }); w.loadURL('data:text/html,<head><meta http-equiv="Content-Security-Policy" content="default-src \'self\'; script-src \'self\' \'unsafe-inline\'"></meta></head>'); await expect(w.webContents.executeJavaScript('eval("true")')).to.be.rejected(); }); it('does not prevent eval from running in executeJavaScript when there is no csp', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox, contextIsolation } }); w.loadURL('data:text/html,'); expect(await w.webContents.executeJavaScript('eval("true")')).to.be.true(); }); }); } }); } }); it('does not crash when multiple WebContent are created with web security disabled', () => { const options = { show: false, webPreferences: { webSecurity: false } }; const w1 = new BrowserWindow(options); w1.loadURL(serverUrl); const w2 = new BrowserWindow(options); w2.loadURL(serverUrl); }); }); describe('command line switches', () => { let appProcess: ChildProcess.ChildProcessWithoutNullStreams | undefined; afterEach(() => { if (appProcess && !appProcess.killed) { appProcess.kill(); appProcess = undefined; } }); describe('--lang switch', () => { const currentLocale = app.getLocale(); const currentSystemLocale = app.getSystemLocale(); const currentPreferredLanguages = JSON.stringify(app.getPreferredSystemLanguages()); const testLocale = async (locale: string, result: string, printEnv: boolean = false) => { const appPath = path.join(fixturesPath, 'api', 'locale-check'); const args = [appPath, `--set-lang=${locale}`]; if (printEnv) { args.push('--print-env'); } appProcess = ChildProcess.spawn(process.execPath, args); let output = ''; appProcess.stdout.on('data', (data) => { output += data; }); let stderr = ''; appProcess.stderr.on('data', (data) => { stderr += data; }); const [code, signal] = await once(appProcess, 'exit'); if (code !== 0) { throw new Error(`Process exited with code "${code}" signal "${signal}" output "${output}" stderr "${stderr}"`); } output = output.replace(/(\r\n|\n|\r)/gm, ''); expect(output).to.equal(result); }; it('should set the locale', async () => testLocale('fr', `fr|${currentSystemLocale}|${currentPreferredLanguages}`)); it('should set the locale with country code', async () => testLocale('zh-CN', `zh-CN|${currentSystemLocale}|${currentPreferredLanguages}`)); it('should not set an invalid locale', async () => testLocale('asdfkl', `${currentLocale}|${currentSystemLocale}|${currentPreferredLanguages}`)); const lcAll = String(process.env.LC_ALL); ifit(process.platform === 'linux')('current process has a valid LC_ALL env', async () => { // The LC_ALL env should not be set to DOM locale string. expect(lcAll).to.not.equal(app.getLocale()); }); ifit(process.platform === 'linux')('should not change LC_ALL', async () => testLocale('fr', lcAll, true)); ifit(process.platform === 'linux')('should not change LC_ALL when setting invalid locale', async () => testLocale('asdfkl', lcAll, true)); ifit(process.platform === 'linux')('should not change LC_ALL when --lang is not set', async () => testLocale('', lcAll, true)); }); describe('--remote-debugging-pipe switch', () => { it('should expose CDP via pipe', async () => { const electronPath = process.execPath; appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-pipe'], { stdio: ['inherit', 'inherit', 'inherit', 'pipe', 'pipe'] }) as ChildProcess.ChildProcessWithoutNullStreams; const stdio = appProcess.stdio as unknown as [NodeJS.ReadableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.ReadableStream]; const pipe = new PipeTransport(stdio[3], stdio[4]); const versionPromise = new Promise(resolve => { pipe.onmessage = resolve; }); pipe.send({ id: 1, method: 'Browser.getVersion', params: {} }); const message = (await versionPromise) as any; expect(message.id).to.equal(1); expect(message.result.product).to.contain('Chrome'); expect(message.result.userAgent).to.contain('Electron'); }); it('should override --remote-debugging-port switch', async () => { const electronPath = process.execPath; appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-pipe', '--remote-debugging-port=0'], { stdio: ['inherit', 'inherit', 'pipe', 'pipe', 'pipe'] }) as ChildProcess.ChildProcessWithoutNullStreams; let stderr = ''; appProcess.stderr.on('data', (data: string) => { stderr += data; }); const stdio = appProcess.stdio as unknown as [NodeJS.ReadableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.ReadableStream]; const pipe = new PipeTransport(stdio[3], stdio[4]); const versionPromise = new Promise(resolve => { pipe.onmessage = resolve; }); pipe.send({ id: 1, method: 'Browser.getVersion', params: {} }); const message = (await versionPromise) as any; expect(message.id).to.equal(1); expect(stderr).to.not.include('DevTools listening on'); }); it('should shut down Electron upon Browser.close CDP command', async () => { const electronPath = process.execPath; appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-pipe'], { stdio: ['inherit', 'inherit', 'inherit', 'pipe', 'pipe'] }) as ChildProcess.ChildProcessWithoutNullStreams; const stdio = appProcess.stdio as unknown as [NodeJS.ReadableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.ReadableStream]; const pipe = new PipeTransport(stdio[3], stdio[4]); pipe.send({ id: 1, method: 'Browser.close', params: {} }); await once(appProcess, 'exit'); }); }); describe('--remote-debugging-port switch', () => { it('should display the discovery page', (done) => { const electronPath = process.execPath; let output = ''; appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-port=']); appProcess.stdout.on('data', (data) => { console.log(data); }); appProcess.stderr.on('data', (data) => { console.log(data); output += data; const m = /DevTools listening on ws:\/\/127.0.0.1:(\d+)\//.exec(output); if (m) { appProcess!.stderr.removeAllListeners('data'); const port = m[1]; http.get(`http://127.0.0.1:${port}`, (res) => { try { expect(res.statusCode).to.eql(200); expect(parseInt(res.headers['content-length']!)).to.be.greaterThan(0); done(); } catch (e) { done(e); } finally { res.destroy(); } }); } }); }); }); }); describe('chromium features', () => { afterEach(closeAllWindows); describe('accessing key names also used as Node.js module names', () => { it('does not crash', (done) => { const w = new BrowserWindow({ show: false }); w.webContents.once('did-finish-load', () => { done(); }); w.webContents.once('render-process-gone', () => done(new Error('WebContents crashed.'))); w.loadFile(path.join(fixturesPath, 'pages', 'external-string.html')); }); }); describe('first party sets', () => { const fps = [ 'https://fps-member1.glitch.me', 'https://fps-member2.glitch.me', 'https://fps-member3.glitch.me' ]; it('loads first party sets', async () => { const appPath = path.join(fixturesPath, 'api', 'first-party-sets', 'base'); const fpsProcess = ChildProcess.spawn(process.execPath, [appPath]); let output = ''; fpsProcess.stdout.on('data', data => { output += data; }); await once(fpsProcess, 'exit'); expect(output).to.include(fps.join(',')); }); it('loads sets from the command line', async () => { const appPath = path.join(fixturesPath, 'api', 'first-party-sets', 'command-line'); const args = [appPath, `--use-first-party-set=${fps}`]; const fpsProcess = ChildProcess.spawn(process.execPath, args); let output = ''; fpsProcess.stdout.on('data', data => { output += data; }); await once(fpsProcess, 'exit'); expect(output).to.include(fps.join(',')); }); }); describe('loading jquery', () => { it('does not crash', (done) => { const w = new BrowserWindow({ show: false }); w.webContents.once('did-finish-load', () => { done(); }); w.webContents.once('render-process-gone', () => done(new Error('WebContents crashed.'))); w.loadFile(path.join(__dirname, 'fixtures', 'pages', 'jquery.html')); }); }); describe('navigator.languages', () => { it('should return the system locale only', async () => { const appLocale = app.getLocale(); const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const languages = await w.webContents.executeJavaScript('navigator.languages'); expect(languages.length).to.be.greaterThan(0); expect(languages).to.contain(appLocale); }); }); describe('navigator.serviceWorker', () => { it('should register for file scheme', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, partition: 'sw-file-scheme-spec', contextIsolation: false } }); w.webContents.on('ipc-message', (event, channel, message) => { if (channel === 'reload') { w.webContents.reload(); } else if (channel === 'error') { done(message); } else if (channel === 'response') { expect(message).to.equal('Hello from serviceWorker!'); session.fromPartition('sw-file-scheme-spec').clearStorageData({ storages: ['serviceworkers'] }).then(() => done()); } }); w.webContents.on('render-process-gone', () => done(new Error('WebContents crashed.'))); w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'index.html')); }); it('should register for intercepted file scheme', (done) => { const customSession = session.fromPartition('intercept-file'); customSession.protocol.interceptBufferProtocol('file', (request, callback) => { let file = url.parse(request.url).pathname!; if (file[0] === '/' && process.platform === 'win32') file = file.slice(1); const content = fs.readFileSync(path.normalize(file)); const ext = path.extname(file); let type = 'text/html'; if (ext === '.js') type = 'application/javascript'; callback({ data: content, mimeType: type } as any); }); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, session: customSession, contextIsolation: false } }); w.webContents.on('ipc-message', (event, channel, message) => { if (channel === 'reload') { w.webContents.reload(); } else if (channel === 'error') { done(`unexpected error : ${message}`); } else if (channel === 'response') { expect(message).to.equal('Hello from serviceWorker!'); customSession.clearStorageData({ storages: ['serviceworkers'] }).then(() => { customSession.protocol.uninterceptProtocol('file'); done(); }); } }); w.webContents.on('render-process-gone', () => done(new Error('WebContents crashed.'))); w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'index.html')); }); it('should register for custom scheme', (done) => { const customSession = session.fromPartition('custom-scheme'); customSession.protocol.registerFileProtocol(serviceWorkerScheme, (request, callback) => { let file = url.parse(request.url).pathname!; if (file[0] === '/' && process.platform === 'win32') file = file.slice(1); callback({ path: path.normalize(file) } as any); }); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, session: customSession, contextIsolation: false } }); w.webContents.on('ipc-message', (event, channel, message) => { if (channel === 'reload') { w.webContents.reload(); } else if (channel === 'error') { done(`unexpected error : ${message}`); } else if (channel === 'response') { expect(message).to.equal('Hello from serviceWorker!'); customSession.clearStorageData({ storages: ['serviceworkers'] }).then(() => { customSession.protocol.uninterceptProtocol(serviceWorkerScheme); done(); }); } }); w.webContents.on('render-process-gone', () => done(new Error('WebContents crashed.'))); w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'custom-scheme-index.html')); }); it('should not allow nodeIntegrationInWorker', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, nodeIntegrationInWorker: true, partition: 'sw-file-scheme-worker-spec', contextIsolation: false } }); await w.loadURL(`file://${fixturesPath}/pages/service-worker/empty.html`); const data = await w.webContents.executeJavaScript(` navigator.serviceWorker.register('worker-no-node.js', { scope: './' }).then(() => navigator.serviceWorker.ready) new Promise((resolve) => { navigator.serviceWorker.onmessage = event => resolve(event.data); }); `); expect(data).to.equal('undefined undefined undefined undefined'); }); }); describe('navigator.geolocation', () => { ifit(features.isFakeLocationProviderEnabled())('returns error when permission is denied', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, partition: 'geolocation-spec', contextIsolation: false } }); const message = once(w.webContents, 'ipc-message'); w.webContents.session.setPermissionRequestHandler((wc, permission, callback) => { if (permission === 'geolocation') { callback(false); } else { callback(true); } }); w.loadFile(path.join(fixturesPath, 'pages', 'geolocation', 'index.html')); const [, channel] = await message; expect(channel).to.equal('success', 'unexpected response from geolocation api'); }); ifit(!features.isFakeLocationProviderEnabled())('returns position when permission is granted', async () => { const w = new BrowserWindow({ show: false, webPreferences: { partition: 'geolocation-spec' } }); w.webContents.session.setPermissionRequestHandler((_wc, _permission, callback) => { callback(true); }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const position = await w.webContents.executeJavaScript(`new Promise((resolve, reject) => navigator.geolocation.getCurrentPosition( x => resolve({coords: x.coords, timestamp: x.timestamp}), err => reject(new Error(err.message))))`); expect(position).to.have.property('coords'); expect(position).to.have.property('timestamp'); }); }); describe('web workers', () => { let appProcess: ChildProcess.ChildProcessWithoutNullStreams | undefined; afterEach(() => { if (appProcess && !appProcess.killed) { appProcess.kill(); appProcess = undefined; } }); it('Worker with nodeIntegrationInWorker has access to self.module.paths', async () => { const appPath = path.join(__dirname, 'fixtures', 'apps', 'self-module-paths'); appProcess = ChildProcess.spawn(process.execPath, [appPath]); const [code] = await once(appProcess, 'exit'); expect(code).to.equal(0); }); it('Worker can work', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const data = await w.webContents.executeJavaScript(` const worker = new Worker('../workers/worker.js'); const message = 'ping'; const eventPromise = new Promise((resolve) => { worker.onmessage = resolve; }); worker.postMessage(message); eventPromise.then(t => t.data) `); expect(data).to.equal('ping'); }); it('Worker has no node integration by default', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const data = await w.webContents.executeJavaScript(` const worker = new Worker('../workers/worker_node.js'); new Promise((resolve) => { worker.onmessage = e => resolve(e.data); }) `); expect(data).to.equal('undefined undefined undefined undefined'); }); it('Worker has node integration with nodeIntegrationInWorker', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, nodeIntegrationInWorker: true, contextIsolation: false } }); w.loadURL(`file://${fixturesPath}/pages/worker.html`); const [, data] = await once(ipcMain, 'worker-result'); expect(data).to.equal('object function object function'); }); describe('SharedWorker', () => { it('can work', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const data = await w.webContents.executeJavaScript(` const worker = new SharedWorker('../workers/shared_worker.js'); const message = 'ping'; const eventPromise = new Promise((resolve) => { worker.port.onmessage = e => resolve(e.data); }); worker.port.postMessage(message); eventPromise `); expect(data).to.equal('ping'); }); it('has no node integration by default', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const data = await w.webContents.executeJavaScript(` const worker = new SharedWorker('../workers/shared_worker_node.js'); new Promise((resolve) => { worker.port.onmessage = e => resolve(e.data); }) `); expect(data).to.equal('undefined undefined undefined undefined'); }); it('does not have node integration with nodeIntegrationInWorker', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, nodeIntegrationInWorker: true, contextIsolation: false } }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const data = await w.webContents.executeJavaScript(` const worker = new SharedWorker('../workers/shared_worker_node.js'); new Promise((resolve) => { worker.port.onmessage = e => resolve(e.data); }) `); expect(data).to.equal('undefined undefined undefined undefined'); }); }); }); describe('form submit', () => { let server: http.Server; let serverUrl: string; before(async () => { server = http.createServer((req, res) => { let body = ''; req.on('data', (chunk) => { body += chunk; }); res.setHeader('Content-Type', 'application/json'); req.on('end', () => { res.end(`body:${body}`); }); }); serverUrl = (await listen(server)).url; }); after(async () => { server.close(); await closeAllWindows(); }); [true, false].forEach((isSandboxEnabled) => describe(`sandbox=${isSandboxEnabled}`, () => { it('posts data in the same window', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: isSandboxEnabled } }); await w.loadFile(path.join(fixturesPath, 'pages', 'form-with-data.html')); const loadPromise = once(w.webContents, 'did-finish-load'); w.webContents.executeJavaScript(` const form = document.querySelector('form') form.action = '${serverUrl}'; form.submit(); `); await loadPromise; const res = await w.webContents.executeJavaScript('document.body.innerText'); expect(res).to.equal('body:greeting=hello'); }); it('posts data to a new window with target=_blank', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: isSandboxEnabled } }); await w.loadFile(path.join(fixturesPath, 'pages', 'form-with-data.html')); const windowCreatedPromise = once(app, 'browser-window-created') as Promise<[any, BrowserWindow]>; w.webContents.executeJavaScript(` const form = document.querySelector('form') form.action = '${serverUrl}'; form.target = '_blank'; form.submit(); `); const [, newWin] = await windowCreatedPromise; const res = await newWin.webContents.executeJavaScript('document.body.innerText'); expect(res).to.equal('body:greeting=hello'); }); }) ); }); describe('window.open', () => { for (const show of [true, false]) { it(`shows the child regardless of parent visibility when parent {show=${show}}`, async () => { const w = new BrowserWindow({ show }); // toggle visibility if (show) { w.hide(); } else { w.show(); } defer(() => { w.close(); }); const promise = once(app, 'browser-window-created') as Promise<[any, BrowserWindow]>; w.loadFile(path.join(fixturesPath, 'pages', 'window-open.html')); const [, newWindow] = await promise; expect(newWindow.isVisible()).to.equal(true); }); } // FIXME(zcbenz): This test is making the spec runner hang on exit on Windows. ifit(process.platform !== 'win32')('disables node integration when it is disabled on the parent window', async () => { const windowUrl = url.pathToFileURL(path.join(fixturesPath, 'pages', 'window-opener-no-node-integration.html')); windowUrl.searchParams.set('p', `${fixturesPath}/pages/window-opener-node.html`); const w = new BrowserWindow({ show: false }); w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); const { eventData } = await w.webContents.executeJavaScript(`(async () => { const message = new Promise(resolve => window.addEventListener('message', resolve, {once: true})); const b = window.open(${JSON.stringify(windowUrl)}, '', 'show=false') const e = await message b.close(); return { eventData: e.data } })()`); expect(eventData.isProcessGlobalUndefined).to.be.true(); }); it('disables node integration when it is disabled on the parent window for chrome devtools URLs', async () => { // NB. webSecurity is disabled because native window.open() is not // allowed to load devtools:// URLs. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webSecurity: false } }); w.loadURL('about:blank'); w.webContents.executeJavaScript(` { b = window.open('devtools://devtools/bundled/inspector.html', '', 'nodeIntegration=no,show=no'); null } `); const [, contents] = await once(app, 'web-contents-created') as [any, WebContents]; const typeofProcessGlobal = await contents.executeJavaScript('typeof process'); expect(typeofProcessGlobal).to.equal('undefined'); }); it('can disable node integration when it is enabled on the parent window', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); w.loadURL('about:blank'); w.webContents.executeJavaScript(` { b = window.open('about:blank', '', 'nodeIntegration=no,show=no'); null } `); const [, contents] = await once(app, 'web-contents-created') as [any, WebContents]; const typeofProcessGlobal = await contents.executeJavaScript('typeof process'); expect(typeofProcessGlobal).to.equal('undefined'); }); // TODO(jkleinsc) fix this flaky test on WOA ifit(process.platform !== 'win32' || process.arch !== 'arm64')('disables JavaScript when it is disabled on the parent window', async () => { const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true } }); w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); const windowUrl = require('node:url').format({ pathname: `${fixturesPath}/pages/window-no-javascript.html`, protocol: 'file', slashes: true }); w.webContents.executeJavaScript(` { b = window.open(${JSON.stringify(windowUrl)}, '', 'javascript=no,show=no'); null } `); const [, contents] = await once(app, 'web-contents-created') as [any, WebContents]; await once(contents, 'did-finish-load'); // Click link on page contents.sendInputEvent({ type: 'mouseDown', clickCount: 1, x: 1, y: 1 }); contents.sendInputEvent({ type: 'mouseUp', clickCount: 1, x: 1, y: 1 }); const [, window] = await once(app, 'browser-window-created') as [any, BrowserWindow]; const preferences = window.webContents.getLastWebPreferences(); expect(preferences!.javascript).to.be.false(); }); it('defines a window.location getter', async () => { let targetURL: string; if (process.platform === 'win32') { targetURL = `file:///${fixturesPath.replace(/\\/g, '/')}/pages/base-page.html`; } else { targetURL = `file://${fixturesPath}/pages/base-page.html`; } const w = new BrowserWindow({ show: false }); w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); w.webContents.executeJavaScript(`{ b = window.open(${JSON.stringify(targetURL)}); null }`); const [, window] = await once(app, 'browser-window-created') as [any, BrowserWindow]; await once(window.webContents, 'did-finish-load'); expect(await w.webContents.executeJavaScript('b.location.href')).to.equal(targetURL); }); it('defines a window.location setter', async () => { const w = new BrowserWindow({ show: false }); w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); w.webContents.executeJavaScript('{ b = window.open("about:blank"); null }'); const [, { webContents }] = await once(app, 'browser-window-created') as [any, BrowserWindow]; await once(webContents, 'did-finish-load'); // When it loads, redirect w.webContents.executeJavaScript(`{ b.location = ${JSON.stringify(`file://${fixturesPath}/pages/base-page.html`)}; null }`); await once(webContents, 'did-finish-load'); }); it('defines a window.location.href setter', async () => { const w = new BrowserWindow({ show: false }); w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); w.webContents.executeJavaScript('{ b = window.open("about:blank"); null }'); const [, { webContents }] = await once(app, 'browser-window-created') as [any, BrowserWindow]; await once(webContents, 'did-finish-load'); // When it loads, redirect w.webContents.executeJavaScript(`{ b.location.href = ${JSON.stringify(`file://${fixturesPath}/pages/base-page.html`)}; null }`); await once(webContents, 'did-finish-load'); }); it('open a blank page when no URL is specified', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.executeJavaScript('{ b = window.open(); null }'); const [, { webContents }] = await once(app, 'browser-window-created') as [any, BrowserWindow]; await once(webContents, 'did-finish-load'); expect(await w.webContents.executeJavaScript('b.location.href')).to.equal('about:blank'); }); it('open a blank page when an empty URL is specified', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.executeJavaScript('{ b = window.open(\'\'); null }'); const [, { webContents }] = await once(app, 'browser-window-created') as [any, BrowserWindow]; await once(webContents, 'did-finish-load'); expect(await w.webContents.executeJavaScript('b.location.href')).to.equal('about:blank'); }); it('does not throw an exception when the frameName is a built-in object property', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.executeJavaScript('{ b = window.open(\'\', \'__proto__\'); null }'); const frameName = await new Promise((resolve) => { w.webContents.setWindowOpenHandler(details => { setImmediate(() => resolve(details.frameName)); return { action: 'allow' }; }); }); expect(frameName).to.equal('__proto__'); }); it('works when used in conjunction with the vm module', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); await w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); const { contextObject } = await w.webContents.executeJavaScript(`(async () => { const vm = require('node:vm'); const contextObject = { count: 1, type: 'gecko' }; window.open(''); vm.runInNewContext('count += 1; type = "chameleon";', contextObject); return { contextObject }; })()`); expect(contextObject).to.deep.equal({ count: 2, type: 'chameleon' }); }); // FIXME(nornagon): I'm not sure this ... ever was correct? xit('inherit options of parent window', async () => { const w = new BrowserWindow({ show: false, width: 123, height: 456 }); w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); const url = `file://${fixturesPath}/pages/window-open-size.html`; const { width, height, eventData } = await w.webContents.executeJavaScript(`(async () => { const message = new Promise(resolve => window.addEventListener('message', resolve, {once: true})); const b = window.open(${JSON.stringify(url)}, '', 'show=false') const e = await message b.close(); const width = outerWidth; const height = outerHeight; return { width, height, eventData: e.data } })()`); expect(eventData).to.equal(`size: ${width} ${height}`); expect(eventData).to.equal('size: 123 456'); }); it('does not override child options', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); const windowUrl = `file://${fixturesPath}/pages/window-open-size.html`; const { eventData } = await w.webContents.executeJavaScript(`(async () => { const message = new Promise(resolve => window.addEventListener('message', resolve, {once: true})); const b = window.open(${JSON.stringify(windowUrl)}, '', 'show=no,width=350,height=450') const e = await message b.close(); return { eventData: e.data } })()`); expect(eventData).to.equal('size: 350 450'); }); it('loads preload script after setting opener to null', async () => { const w = new BrowserWindow({ show: false }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: path.join(fixturesPath, 'module', 'preload.js') } } })); w.loadURL('about:blank'); w.webContents.executeJavaScript('window.child = window.open(); child.opener = null'); const [, { webContents }] = await once(app, 'browser-window-created'); const [,, message] = await once(webContents, 'console-message'); expect(message).to.equal('{"require":"function","module":"undefined","process":"object","Buffer":"function"}'); }); it('disables the <webview> tag when it is disabled on the parent window', async () => { const windowUrl = url.pathToFileURL(path.join(fixturesPath, 'pages', 'window-opener-no-webview-tag.html')); windowUrl.searchParams.set('p', `${fixturesPath}/pages/window-opener-webview.html`); const w = new BrowserWindow({ show: false }); w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); const { eventData } = await w.webContents.executeJavaScript(`(async () => { const message = new Promise(resolve => window.addEventListener('message', resolve, {once: true})); const b = window.open(${JSON.stringify(windowUrl)}, '', 'webviewTag=no,contextIsolation=no,nodeIntegration=yes,show=no') const e = await message b.close(); return { eventData: e.data } })()`); expect(eventData.isWebViewGlobalUndefined).to.be.true(); }); it('throws an exception when the arguments cannot be converted to strings', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); await expect( w.webContents.executeJavaScript('window.open(\'\', { toString: null })') ).to.eventually.be.rejected(); await expect( w.webContents.executeJavaScript('window.open(\'\', \'\', { toString: 3 })') ).to.eventually.be.rejected(); }); it('does not throw an exception when the features include webPreferences', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); await expect( w.webContents.executeJavaScript('window.open(\'\', \'\', \'show=no,webPreferences=\'); null') ).to.eventually.be.fulfilled(); }); }); describe('window.opener', () => { it('is null for main window', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixturesPath, 'pages', 'window-opener.html')); const [, channel, opener] = await once(w.webContents, 'ipc-message'); expect(channel).to.equal('opener'); expect(opener).to.equal(null); }); it('is not null for window opened by window.open', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); const windowUrl = `file://${fixturesPath}/pages/window-opener.html`; const eventData = await w.webContents.executeJavaScript(` const b = window.open(${JSON.stringify(windowUrl)}, '', 'show=no'); new Promise(resolve => window.addEventListener('message', resolve, {once: true})).then(e => e.data); `); expect(eventData).to.equal('object'); }); }); describe('window.opener.postMessage', () => { it('sets source and origin correctly', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); const windowUrl = `file://${fixturesPath}/pages/window-opener-postMessage.html`; const { sourceIsChild, origin } = await w.webContents.executeJavaScript(` const b = window.open(${JSON.stringify(windowUrl)}, '', 'show=no'); new Promise(resolve => window.addEventListener('message', resolve, {once: true})).then(e => ({ sourceIsChild: e.source === b, origin: e.origin })); `); expect(sourceIsChild).to.be.true(); expect(origin).to.equal('file://'); }); it('supports windows opened from a <webview>', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } }); w.loadURL('about:blank'); const childWindowUrl = url.pathToFileURL(path.join(fixturesPath, 'pages', 'webview-opener-postMessage.html')); childWindowUrl.searchParams.set('p', `${fixturesPath}/pages/window-opener-postMessage.html`); const message = await w.webContents.executeJavaScript(` const webview = new WebView(); webview.allowpopups = true; webview.setAttribute('webpreferences', 'contextIsolation=no'); webview.src = ${JSON.stringify(childWindowUrl)} const consoleMessage = new Promise(resolve => webview.addEventListener('console-message', resolve, {once: true})); document.body.appendChild(webview); consoleMessage.then(e => e.message) `); expect(message).to.equal('message'); }); describe('targetOrigin argument', () => { let serverURL: string; let server: any; beforeEach(async () => { server = http.createServer((req, res) => { res.writeHead(200); const filePath = path.join(fixturesPath, 'pages', 'window-opener-targetOrigin.html'); res.end(fs.readFileSync(filePath, 'utf8')); }); serverURL = (await listen(server)).url; }); afterEach(() => { server.close(); }); it('delivers messages that match the origin', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); const data = await w.webContents.executeJavaScript(` window.open(${JSON.stringify(serverURL)}, '', 'show=no,contextIsolation=no,nodeIntegration=yes'); new Promise(resolve => window.addEventListener('message', resolve, {once: true})).then(e => e.data) `); expect(data).to.equal('deliver'); }); }); }); describe('IdleDetection', () => { afterEach(closeAllWindows); afterEach(() => { session.defaultSession.setPermissionCheckHandler(null); session.defaultSession.setPermissionRequestHandler(null); }); it('can grant a permission request', async () => { session.defaultSession.setPermissionRequestHandler( (_wc, permission, callback) => { callback(permission === 'idle-detection'); } ); const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'button.html')); const permission = await w.webContents.executeJavaScript(` new Promise((resolve, reject) => { const button = document.getElementById('button'); button.addEventListener("click", async () => { const permission = await IdleDetector.requestPermission(); resolve(permission); }); button.click(); }); `, true); expect(permission).to.eq('granted'); }); it('can deny a permission request', async () => { session.defaultSession.setPermissionRequestHandler( (_wc, permission, callback) => { callback(permission !== 'idle-detection'); } ); const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'button.html')); const permission = await w.webContents.executeJavaScript(` new Promise((resolve, reject) => { const button = document.getElementById('button'); button.addEventListener("click", async () => { const permission = await IdleDetector.requestPermission(); resolve(permission); }); button.click(); }); `, true); expect(permission).to.eq('denied'); }); it('can allow the IdleDetector to start', async () => { session.defaultSession.setPermissionCheckHandler((wc, permission) => { return permission === 'idle-detection'; }); const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); const result = await w.webContents.executeJavaScript(` const detector = new IdleDetector({ threshold: 60000 }); detector.start().then(() => { return 'success'; }).catch(e => e.message); `, true); expect(result).to.eq('success'); }); it('can prevent the IdleDetector from starting', async () => { session.defaultSession.setPermissionCheckHandler((wc, permission) => { return permission !== 'idle-detection'; }); const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); const result = await w.webContents.executeJavaScript(` const detector = new IdleDetector({ threshold: 60000 }); detector.start().then(() => { console.log('success') }).catch(e => e.message); `, true); expect(result).to.eq('Idle detection permission denied'); }); }); describe('navigator.mediaDevices', () => { afterEach(closeAllWindows); afterEach(() => { session.defaultSession.setPermissionCheckHandler(null); session.defaultSession.setPermissionRequestHandler(null); }); it('can return labels of enumerated devices', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); const labels = await w.webContents.executeJavaScript('navigator.mediaDevices.enumerateDevices().then(ds => ds.map(d => d.label))'); expect(labels.some((l: any) => l)).to.be.true(); }); it('does not return labels of enumerated devices when permission denied', async () => { session.defaultSession.setPermissionCheckHandler(() => false); const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); const labels = await w.webContents.executeJavaScript('navigator.mediaDevices.enumerateDevices().then(ds => ds.map(d => d.label))'); expect(labels.some((l: any) => l)).to.be.false(); }); it('returns the same device ids across reloads', async () => { const ses = session.fromPartition('persist:media-device-id'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, session: ses, contextIsolation: false } }); w.loadFile(path.join(fixturesPath, 'pages', 'media-id-reset.html')); const [, firstDeviceIds] = await once(ipcMain, 'deviceIds'); w.webContents.reload(); const [, secondDeviceIds] = await once(ipcMain, 'deviceIds'); expect(firstDeviceIds).to.deep.equal(secondDeviceIds); }); it('can return new device id when cookie storage is cleared', async () => { const ses = session.fromPartition('persist:media-device-id'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, session: ses, contextIsolation: false } }); w.loadFile(path.join(fixturesPath, 'pages', 'media-id-reset.html')); const [, firstDeviceIds] = await once(ipcMain, 'deviceIds'); await ses.clearStorageData({ storages: ['cookies'] }); w.webContents.reload(); const [, secondDeviceIds] = await once(ipcMain, 'deviceIds'); expect(firstDeviceIds).to.not.deep.equal(secondDeviceIds); }); it('provides a securityOrigin to the request handler', async () => { session.defaultSession.setPermissionRequestHandler( (wc, permission, callback, details) => { if (details.securityOrigin !== undefined) { callback(true); } else { callback(false); } } ); const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); const labels = await w.webContents.executeJavaScript(`navigator.mediaDevices.getUserMedia({ video: { mandatory: { chromeMediaSource: "desktop", minWidth: 1280, maxWidth: 1280, minHeight: 720, maxHeight: 720 } } }).then((stream) => stream.getVideoTracks())`); expect(labels.some((l: any) => l)).to.be.true(); }); it('fails with "not supported" for getDisplayMedia', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); const { ok, err } = await w.webContents.executeJavaScript('navigator.mediaDevices.getDisplayMedia({video: true}).then(s => ({ok: true}), e => ({ok: false, err: e.message}))', true); expect(ok).to.be.false(); expect(err).to.equal('Not supported'); }); }); describe('window.opener access', () => { const scheme = 'app'; const fileUrl = `file://${fixturesPath}/pages/window-opener-location.html`; const httpUrl1 = `${scheme}://origin1`; const httpUrl2 = `${scheme}://origin2`; const fileBlank = `file://${fixturesPath}/pages/blank.html`; const httpBlank = `${scheme}://origin1/blank`; const table = [ { parent: fileBlank, child: httpUrl1, nodeIntegration: false, openerAccessible: false }, { parent: fileBlank, child: httpUrl1, nodeIntegration: true, openerAccessible: false }, // {parent: httpBlank, child: fileUrl, nodeIntegration: false, openerAccessible: false}, // can't window.open() // {parent: httpBlank, child: fileUrl, nodeIntegration: true, openerAccessible: false}, // can't window.open() // NB. this is different from Chrome's behavior, which isolates file: urls from each other { parent: fileBlank, child: fileUrl, nodeIntegration: false, openerAccessible: true }, { parent: fileBlank, child: fileUrl, nodeIntegration: true, openerAccessible: true }, { parent: httpBlank, child: httpUrl1, nodeIntegration: false, openerAccessible: true }, { parent: httpBlank, child: httpUrl1, nodeIntegration: true, openerAccessible: true }, { parent: httpBlank, child: httpUrl2, nodeIntegration: false, openerAccessible: false }, { parent: httpBlank, child: httpUrl2, nodeIntegration: true, openerAccessible: false } ]; const s = (url: string) => url.startsWith('file') ? 'file://...' : url; before(() => { protocol.registerFileProtocol(scheme, (request, callback) => { if (request.url.includes('blank')) { callback(`${fixturesPath}/pages/blank.html`); } else { callback(`${fixturesPath}/pages/window-opener-location.html`); } }); }); after(() => { protocol.unregisterProtocol(scheme); }); afterEach(closeAllWindows); describe('when opened from main window', () => { for (const { parent, child, nodeIntegration, openerAccessible } of table) { for (const sandboxPopup of [false, true]) { const description = `when parent=${s(parent)} opens child=${s(child)} with nodeIntegration=${nodeIntegration} sandboxPopup=${sandboxPopup}, child should ${openerAccessible ? '' : 'not '}be able to access opener`; it(description, async () => { const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { sandbox: sandboxPopup } } })); await w.loadURL(parent); const childOpenerLocation = await w.webContents.executeJavaScript(`new Promise(resolve => { window.addEventListener('message', function f(e) { resolve(e.data) }) window.open(${JSON.stringify(child)}, "", "show=no,nodeIntegration=${nodeIntegration ? 'yes' : 'no'}") })`); if (openerAccessible) { expect(childOpenerLocation).to.be.a('string'); } else { expect(childOpenerLocation).to.be.null(); } }); } } }); describe('when opened from <webview>', () => { for (const { parent, child, nodeIntegration, openerAccessible } of table) { const description = `when parent=${s(parent)} opens child=${s(child)} with nodeIntegration=${nodeIntegration}, child should ${openerAccessible ? '' : 'not '}be able to access opener`; it(description, async () => { // This test involves three contexts: // 1. The root BrowserWindow in which the test is run, // 2. A <webview> belonging to the root window, // 3. A window opened by calling window.open() from within the <webview>. // We are testing whether context (3) can access context (2) under various conditions. // This is context (1), the base window for the test. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webviewTag: true, contextIsolation: false } }); await w.loadURL('about:blank'); const parentCode = `new Promise((resolve) => { // This is context (3), a child window of the WebView. const child = window.open(${JSON.stringify(child)}, "", "show=no,contextIsolation=no,nodeIntegration=yes") window.addEventListener("message", e => { resolve(e.data) }) })`; const childOpenerLocation = await w.webContents.executeJavaScript(`new Promise((resolve, reject) => { // This is context (2), a WebView which will call window.open() const webview = new WebView() webview.setAttribute('nodeintegration', '${nodeIntegration ? 'on' : 'off'}') webview.setAttribute('webpreferences', 'contextIsolation=no') webview.setAttribute('allowpopups', 'on') webview.src = ${JSON.stringify(parent + '?p=' + encodeURIComponent(child))} webview.addEventListener('dom-ready', async () => { webview.executeJavaScript(${JSON.stringify(parentCode)}).then(resolve, reject) }) document.body.appendChild(webview) })`); if (openerAccessible) { expect(childOpenerLocation).to.be.a('string'); } else { expect(childOpenerLocation).to.be.null(); } }); } }); }); describe('storage', () => { describe('custom non standard schemes', () => { const protocolName = 'storage'; let contents: WebContents; before(() => { protocol.registerFileProtocol(protocolName, (request, callback) => { const parsedUrl = url.parse(request.url); let filename; switch (parsedUrl.pathname) { case '/localStorage' : filename = 'local_storage.html'; break; case '/sessionStorage' : filename = 'session_storage.html'; break; case '/WebSQL' : filename = 'web_sql.html'; break; case '/indexedDB' : filename = 'indexed_db.html'; break; case '/cookie' : filename = 'cookie.html'; break; default : filename = ''; } callback({ path: `${fixturesPath}/pages/storage/${filename}` }); }); }); after(() => { protocol.unregisterProtocol(protocolName); }); beforeEach(() => { contents = (webContents as typeof ElectronInternal.WebContents).create({ nodeIntegration: true, contextIsolation: false }); }); afterEach(() => { contents.destroy(); contents = null as any; }); it('cannot access localStorage', async () => { const response = once(ipcMain, 'local-storage-response'); contents.loadURL(protocolName + '://host/localStorage'); const [, error] = await response; expect(error).to.equal('Failed to read the \'localStorage\' property from \'Window\': Access is denied for this document.'); }); it('cannot access sessionStorage', async () => { const response = once(ipcMain, 'session-storage-response'); contents.loadURL(`${protocolName}://host/sessionStorage`); const [, error] = await response; expect(error).to.equal('Failed to read the \'sessionStorage\' property from \'Window\': Access is denied for this document.'); }); it('cannot access WebSQL database', async () => { const response = once(ipcMain, 'web-sql-response'); contents.loadURL(`${protocolName}://host/WebSQL`); const [, error] = await response; expect(error).to.equal('Failed to execute \'openDatabase\' on \'Window\': Access to the WebDatabase API is denied in this context.'); }); it('cannot access indexedDB', async () => { const response = once(ipcMain, 'indexed-db-response'); contents.loadURL(`${protocolName}://host/indexedDB`); const [, error] = await response; expect(error).to.equal('Failed to execute \'open\' on \'IDBFactory\': access to the Indexed Database API is denied in this context.'); }); it('cannot access cookie', async () => { const response = once(ipcMain, 'cookie-response'); contents.loadURL(`${protocolName}://host/cookie`); const [, error] = await response; expect(error).to.equal('Failed to set the \'cookie\' property on \'Document\': Access is denied for this document.'); }); }); describe('can be accessed', () => { let server: http.Server; let serverUrl: string; let serverCrossSiteUrl: string; before(async () => { server = http.createServer((req, res) => { const respond = () => { if (req.url === '/redirect-cross-site') { res.setHeader('Location', `${serverCrossSiteUrl}/redirected`); res.statusCode = 302; res.end(); } else if (req.url === '/redirected') { res.end('<html><script>window.localStorage</script></html>'); } else { res.end(); } }; setTimeout().then(respond); }); serverUrl = (await listen(server)).url; serverCrossSiteUrl = serverUrl.replace('127.0.0.1', 'localhost'); }); after(() => { server.close(); server = null as any; }); afterEach(closeAllWindows); const testLocalStorageAfterXSiteRedirect = (testTitle: string, extraPreferences = {}) => { it(testTitle, async () => { const w = new BrowserWindow({ show: false, ...extraPreferences }); let redirected = false; w.webContents.on('render-process-gone', () => { expect.fail('renderer crashed / was killed'); }); w.webContents.on('did-redirect-navigation', (event, url) => { expect(url).to.equal(`${serverCrossSiteUrl}/redirected`); redirected = true; }); await w.loadURL(`${serverUrl}/redirect-cross-site`); expect(redirected).to.be.true('didnt redirect'); }); }; testLocalStorageAfterXSiteRedirect('after a cross-site redirect'); testLocalStorageAfterXSiteRedirect('after a cross-site redirect in sandbox mode', { sandbox: true }); }); describe('enableWebSQL webpreference', () => { const origin = `${standardScheme}://fake-host`; const filePath = path.join(fixturesPath, 'pages', 'storage', 'web_sql.html'); const sqlPartition = 'web-sql-preference-test'; const sqlSession = session.fromPartition(sqlPartition); const securityError = 'An attempt was made to break through the security policy of the user agent.'; let contents: WebContents, w: BrowserWindow; before(() => { sqlSession.protocol.registerFileProtocol(standardScheme, (request, callback) => { callback({ path: filePath }); }); }); after(() => { sqlSession.protocol.unregisterProtocol(standardScheme); }); afterEach(async () => { if (contents) { contents.destroy(); contents = null as any; } await closeAllWindows(); (w as any) = null; }); it('default value allows websql', async () => { contents = (webContents as typeof ElectronInternal.WebContents).create({ session: sqlSession, nodeIntegration: true, contextIsolation: false }); contents.loadURL(origin); const [, error] = await once(ipcMain, 'web-sql-response'); expect(error).to.be.null(); }); it('when set to false can disallow websql', async () => { contents = (webContents as typeof ElectronInternal.WebContents).create({ session: sqlSession, nodeIntegration: true, enableWebSQL: false, contextIsolation: false }); contents.loadURL(origin); const [, error] = await once(ipcMain, 'web-sql-response'); expect(error).to.equal(securityError); }); it('when set to false does not disable indexedDB', async () => { contents = (webContents as typeof ElectronInternal.WebContents).create({ session: sqlSession, nodeIntegration: true, enableWebSQL: false, contextIsolation: false }); contents.loadURL(origin); const [, error] = await once(ipcMain, 'web-sql-response'); expect(error).to.equal(securityError); const dbName = 'random'; const result = await contents.executeJavaScript(` new Promise((resolve, reject) => { try { let req = window.indexedDB.open('${dbName}'); req.onsuccess = (event) => { let db = req.result; resolve(db.name); } req.onerror = (event) => { resolve(event.target.code); } } catch (e) { resolve(e.message); } }); `); expect(result).to.equal(dbName); }); it('child webContents can override when the embedder has allowed websql', async () => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webviewTag: true, session: sqlSession, contextIsolation: false } }); w.webContents.loadURL(origin); const [, error] = await once(ipcMain, 'web-sql-response'); expect(error).to.be.null(); const webviewResult = once(ipcMain, 'web-sql-response'); await w.webContents.executeJavaScript(` new Promise((resolve, reject) => { const webview = new WebView(); webview.setAttribute('src', '${origin}'); webview.setAttribute('webpreferences', 'enableWebSQL=0,contextIsolation=no'); webview.setAttribute('partition', '${sqlPartition}'); webview.setAttribute('nodeIntegration', 'on'); document.body.appendChild(webview); webview.addEventListener('dom-ready', () => resolve()); }); `); const [, childError] = await webviewResult; expect(childError).to.equal(securityError); }); it('child webContents cannot override when the embedder has disallowed websql', async () => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, enableWebSQL: false, webviewTag: true, session: sqlSession, contextIsolation: false } }); w.webContents.loadURL('data:text/html,<html></html>'); const webviewResult = once(ipcMain, 'web-sql-response'); await w.webContents.executeJavaScript(` new Promise((resolve, reject) => { const webview = new WebView(); webview.setAttribute('src', '${origin}'); webview.setAttribute('webpreferences', 'enableWebSQL=1,contextIsolation=no'); webview.setAttribute('partition', '${sqlPartition}'); webview.setAttribute('nodeIntegration', 'on'); document.body.appendChild(webview); webview.addEventListener('dom-ready', () => resolve()); }); `); const [, childError] = await webviewResult; expect(childError).to.equal(securityError); }); it('child webContents can use websql when the embedder has allowed websql', async () => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webviewTag: true, session: sqlSession, contextIsolation: false } }); w.webContents.loadURL(origin); const [, error] = await once(ipcMain, 'web-sql-response'); expect(error).to.be.null(); const webviewResult = once(ipcMain, 'web-sql-response'); await w.webContents.executeJavaScript(` new Promise((resolve, reject) => { const webview = new WebView(); webview.setAttribute('src', '${origin}'); webview.setAttribute('webpreferences', 'enableWebSQL=1,contextIsolation=no'); webview.setAttribute('partition', '${sqlPartition}'); webview.setAttribute('nodeIntegration', 'on'); document.body.appendChild(webview); webview.addEventListener('dom-ready', () => resolve()); }); `); const [, childError] = await webviewResult; expect(childError).to.be.null(); }); }); describe('DOM storage quota increase', () => { ['localStorage', 'sessionStorage'].forEach((storageName) => { it(`allows saving at least 40MiB in ${storageName}`, async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); // Although JavaScript strings use UTF-16, the underlying // storage provider may encode strings differently, muddling the // translation between character and byte counts. However, // a string of 40 * 2^20 characters will require at least 40MiB // and presumably no more than 80MiB, a size guaranteed to // to exceed the original 10MiB quota yet stay within the // new 100MiB quota. // Note that both the key name and value affect the total size. const testKeyName = '_electronDOMStorageQuotaIncreasedTest'; const length = 40 * Math.pow(2, 20) - testKeyName.length; await w.webContents.executeJavaScript(` ${storageName}.setItem(${JSON.stringify(testKeyName)}, 'X'.repeat(${length})); `); // Wait at least one turn of the event loop to help avoid false positives // Although not entirely necessary, the previous version of this test case // failed to detect a real problem (perhaps related to DOM storage data caching) // wherein calling `getItem` immediately after `setItem` would appear to work // but then later (e.g. next tick) it would not. await setTimeout(1); try { const storedLength = await w.webContents.executeJavaScript(`${storageName}.getItem(${JSON.stringify(testKeyName)}).length`); expect(storedLength).to.equal(length); } finally { await w.webContents.executeJavaScript(`${storageName}.removeItem(${JSON.stringify(testKeyName)});`); } }); it(`throws when attempting to use more than 128MiB in ${storageName}`, async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); await expect((async () => { const testKeyName = '_electronDOMStorageQuotaStillEnforcedTest'; const length = 128 * Math.pow(2, 20) - testKeyName.length; try { await w.webContents.executeJavaScript(` ${storageName}.setItem(${JSON.stringify(testKeyName)}, 'X'.repeat(${length})); `); } finally { await w.webContents.executeJavaScript(`${storageName}.removeItem(${JSON.stringify(testKeyName)});`); } })()).to.eventually.be.rejected(); }); }); }); describe('persistent storage', () => { it('can be requested', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); const grantedBytes = await w.webContents.executeJavaScript(`new Promise(resolve => { navigator.webkitPersistentStorage.requestQuota(1024 * 1024, resolve); })`); expect(grantedBytes).to.equal(1048576); }); }); }); ifdescribe(features.isPDFViewerEnabled())('PDF Viewer', () => { const pdfSource = url.format({ pathname: path.join(__dirname, 'fixtures', 'cat.pdf').replace(/\\/g, '/'), protocol: 'file', slashes: true }); it('successfully loads a PDF file', async () => { const w = new BrowserWindow({ show: false }); w.loadURL(pdfSource); await once(w.webContents, 'did-finish-load'); }); it('opens when loading a pdf resource as top level navigation', async () => { const w = new BrowserWindow({ show: false }); w.loadURL(pdfSource); const [, contents] = await once(app, 'web-contents-created') as [any, WebContents]; await once(contents, 'did-navigate'); expect(contents.getURL()).to.equal('chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/index.html'); }); it('opens when loading a pdf resource in a iframe', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(__dirname, 'fixtures', 'pages', 'pdf-in-iframe.html')); const [, contents] = await once(app, 'web-contents-created') as [any, WebContents]; await once(contents, 'did-navigate'); expect(contents.getURL()).to.equal('chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/index.html'); }); }); describe('window.history', () => { describe('window.history.pushState', () => { it('should push state after calling history.pushState() from the same url', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); // History should have current page by now. expect((w.webContents as any).length()).to.equal(1); const waitCommit = once(w.webContents, 'navigation-entry-committed'); w.webContents.executeJavaScript('window.history.pushState({}, "")'); await waitCommit; // Initial page + pushed state. expect((w.webContents as any).length()).to.equal(2); }); }); describe('window.history.back', () => { it('should not allow sandboxed iframe to modify main frame state', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('data:text/html,<iframe sandbox="allow-scripts"></iframe>'); await Promise.all([ once(w.webContents, 'navigation-entry-committed'), once(w.webContents, 'did-frame-navigate'), once(w.webContents, 'did-navigate') ]); w.webContents.executeJavaScript('window.history.pushState(1, "")'); await Promise.all([ once(w.webContents, 'navigation-entry-committed'), once(w.webContents, 'did-navigate-in-page') ]); (w.webContents as any).once('navigation-entry-committed', () => { expect.fail('Unexpected navigation-entry-committed'); }); w.webContents.once('did-navigate-in-page', () => { expect.fail('Unexpected did-navigate-in-page'); }); await w.webContents.mainFrame.frames[0].executeJavaScript('window.history.back()'); expect(await w.webContents.executeJavaScript('window.history.state')).to.equal(1); expect((w.webContents as any).getActiveIndex()).to.equal(1); }); }); }); describe('chrome://accessibility', () => { it('loads the page successfully', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('chrome://accessibility'); const pageExists = await w.webContents.executeJavaScript( "window.hasOwnProperty('chrome') && window.chrome.hasOwnProperty('send')" ); expect(pageExists).to.be.true(); }); }); describe('chrome://gpu', () => { it('loads the page successfully', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('chrome://gpu'); const pageExists = await w.webContents.executeJavaScript( "window.hasOwnProperty('chrome') && window.chrome.hasOwnProperty('send')" ); expect(pageExists).to.be.true(); }); }); describe('chrome://media-internals', () => { it('loads the page successfully', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('chrome://media-internals'); const pageExists = await w.webContents.executeJavaScript( "window.hasOwnProperty('chrome') && window.chrome.hasOwnProperty('send')" ); expect(pageExists).to.be.true(); }); }); describe('chrome://webrtc-internals', () => { it('loads the page successfully', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('chrome://webrtc-internals'); const pageExists = await w.webContents.executeJavaScript( "window.hasOwnProperty('chrome') && window.chrome.hasOwnProperty('send')" ); expect(pageExists).to.be.true(); }); }); describe('document.hasFocus', () => { it('has correct value when multiple windows are opened', async () => { const w1 = new BrowserWindow({ show: true }); const w2 = new BrowserWindow({ show: true }); const w3 = new BrowserWindow({ show: false }); await w1.loadFile(path.join(__dirname, 'fixtures', 'blank.html')); await w2.loadFile(path.join(__dirname, 'fixtures', 'blank.html')); await w3.loadFile(path.join(__dirname, 'fixtures', 'blank.html')); expect(webContents.getFocusedWebContents()?.id).to.equal(w2.webContents.id); let focus = false; focus = await w1.webContents.executeJavaScript( 'document.hasFocus()' ); expect(focus).to.be.false(); focus = await w2.webContents.executeJavaScript( 'document.hasFocus()' ); expect(focus).to.be.true(); focus = await w3.webContents.executeJavaScript( 'document.hasFocus()' ); expect(focus).to.be.false(); }); }); // https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation describe('navigator.connection', () => { it('returns the correct value', async () => { const w = new BrowserWindow({ show: false }); w.webContents.session.enableNetworkEmulation({ latency: 500, downloadThroughput: 6400, uploadThroughput: 6400 }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const rtt = await w.webContents.executeJavaScript('navigator.connection.rtt'); expect(rtt).to.be.a('number'); const downlink = await w.webContents.executeJavaScript('navigator.connection.downlink'); expect(downlink).to.be.a('number'); const effectiveTypes = ['slow-2g', '2g', '3g', '4g']; const effectiveType = await w.webContents.executeJavaScript('navigator.connection.effectiveType'); expect(effectiveTypes).to.include(effectiveType); }); }); describe('navigator.userAgentData', () => { // These tests are done on an http server because navigator.userAgentData // requires a secure context. let server: http.Server; let serverUrl: string; before(async () => { server = http.createServer((req, res) => { res.setHeader('Content-Type', 'text/html'); res.end(''); }); serverUrl = (await listen(server)).url; }); after(() => { server.close(); }); describe('is not empty', () => { it('by default', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(serverUrl); const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform'); expect(platform).not.to.be.empty(); }); it('when there is a session-wide UA override', async () => { const ses = session.fromPartition(`${Math.random()}`); ses.setUserAgent('foobar'); const w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await w.loadURL(serverUrl); const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform'); expect(platform).not.to.be.empty(); }); it('when there is a WebContents-specific UA override', async () => { const w = new BrowserWindow({ show: false }); w.webContents.setUserAgent('foo'); await w.loadURL(serverUrl); const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform'); expect(platform).not.to.be.empty(); }); it('when there is a WebContents-specific UA override at load time', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(serverUrl, { userAgent: 'foo' }); const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform'); expect(platform).not.to.be.empty(); }); }); describe('brand list', () => { it('contains chromium', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(serverUrl); const brands = await w.webContents.executeJavaScript('navigator.userAgentData.brands'); expect(brands.map((b: any) => b.brand)).to.include('Chromium'); }); }); }); describe('Badging API', () => { it('does not crash', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); await w.webContents.executeJavaScript('navigator.setAppBadge(42)'); await w.webContents.executeJavaScript('navigator.setAppBadge()'); await w.webContents.executeJavaScript('navigator.clearAppBadge()'); }); }); describe('navigator.webkitGetUserMedia', () => { it('calls its callbacks', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); await w.webContents.executeJavaScript(`new Promise((resolve) => { navigator.webkitGetUserMedia({ audio: true, video: false }, () => resolve(), () => resolve()); })`); }); }); describe('navigator.language', () => { it('should not be empty', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); expect(await w.webContents.executeJavaScript('navigator.language')).to.not.equal(''); }); }); describe('heap snapshot', () => { it('does not crash', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadURL('about:blank'); await w.webContents.executeJavaScript('process._linkedBinding(\'electron_common_v8_util\').takeHeapSnapshot()'); }); }); // This is intentionally disabled on arm macs: https://chromium-review.googlesource.com/c/chromium/src/+/4143761 ifdescribe(process.platform === 'darwin' && process.arch !== 'arm64')('webgl', () => { it('can be gotten as context in canvas', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const canWebglContextBeCreated = await w.webContents.executeJavaScript(` document.createElement('canvas').getContext('webgl') != null; `); expect(canWebglContextBeCreated).to.be.true(); }); }); describe('iframe', () => { it('does not have node integration', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const result = await w.webContents.executeJavaScript(` const iframe = document.createElement('iframe') iframe.src = './set-global.html'; document.body.appendChild(iframe); new Promise(resolve => iframe.onload = e => resolve(iframe.contentWindow.test)) `); expect(result).to.equal('undefined undefined undefined'); }); }); describe('websockets', () => { it('has user agent', async () => { const server = http.createServer(); const { port } = await listen(server); const wss = new ws.Server({ server: server }); const finished = new Promise<string | undefined>((resolve, reject) => { wss.on('error', reject); wss.on('connection', (ws, upgradeReq) => { resolve(upgradeReq.headers['user-agent']); }); }); const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.executeJavaScript(` new WebSocket('ws://127.0.0.1:${port}'); `); expect(await finished).to.include('Electron'); }); }); describe('fetch', () => { it('does not crash', async () => { const server = http.createServer((req, res) => { res.end('test'); }); defer(() => server.close()); const { port } = await listen(server); const w = new BrowserWindow({ show: false }); w.loadURL(`file://${fixturesPath}/pages/blank.html`); const x = await w.webContents.executeJavaScript(` fetch('http://127.0.0.1:${port}').then((res) => res.body.getReader()) .then((reader) => { return reader.read().then((r) => { reader.cancel(); return r.value; }); }) `); expect(x).to.deep.equal(new Uint8Array([116, 101, 115, 116])); }); }); describe('Promise', () => { before(() => { ipcMain.handle('ping', (e, arg) => arg); }); after(() => { ipcMain.removeHandler('ping'); }); itremote('resolves correctly in Node.js calls', async () => { await new Promise<void>((resolve, reject) => { class XElement extends HTMLElement {} customElements.define('x-element', XElement); setImmediate(() => { let called = false; Promise.resolve().then(() => { if (called) resolve(); else reject(new Error('wrong sequence')); }); document.createElement('x-element'); called = true; }); }); }); itremote('resolves correctly in Electron calls', async () => { await new Promise<void>((resolve, reject) => { class YElement extends HTMLElement {} customElements.define('y-element', YElement); require('electron').ipcRenderer.invoke('ping').then(() => { let called = false; Promise.resolve().then(() => { if (called) resolve(); else reject(new Error('wrong sequence')); }); document.createElement('y-element'); called = true; }); }); }); }); describe('synchronous prompts', () => { describe('window.alert(message, title)', () => { itremote('throws an exception when the arguments cannot be converted to strings', () => { expect(() => { window.alert({ toString: null }); }).to.throw('Cannot convert object to primitive value'); }); }); describe('window.confirm(message, title)', () => { itremote('throws an exception when the arguments cannot be converted to strings', () => { expect(() => { (window.confirm as any)({ toString: null }, 'title'); }).to.throw('Cannot convert object to primitive value'); }); }); }); describe('window.history', () => { describe('window.history.go(offset)', () => { itremote('throws an exception when the argument cannot be converted to a string', () => { expect(() => { (window.history.go as any)({ toString: null }); }).to.throw('Cannot convert object to primitive value'); }); }); }); describe('console functions', () => { itremote('should exist', () => { expect(console.log, 'log').to.be.a('function'); expect(console.error, 'error').to.be.a('function'); expect(console.warn, 'warn').to.be.a('function'); expect(console.info, 'info').to.be.a('function'); expect(console.debug, 'debug').to.be.a('function'); expect(console.trace, 'trace').to.be.a('function'); expect(console.time, 'time').to.be.a('function'); expect(console.timeEnd, 'timeEnd').to.be.a('function'); }); }); // FIXME(nornagon): this is broken on CI, it triggers: // [FATAL:speech_synthesis.mojom-shared.h(237)] The outgoing message will // trigger VALIDATION_ERROR_UNEXPECTED_NULL_POINTER at the receiving side // (null text in SpeechSynthesisUtterance struct). describe('SpeechSynthesis', () => { itremote('should emit lifecycle events', async () => { const sentence = `long sentence which will take at least a few seconds to utter so that it's possible to pause and resume before the end`; const utter = new SpeechSynthesisUtterance(sentence); // Create a dummy utterance so that speech synthesis state // is initialized for later calls. speechSynthesis.speak(new SpeechSynthesisUtterance()); speechSynthesis.cancel(); speechSynthesis.speak(utter); // paused state after speak() expect(speechSynthesis.paused).to.be.false(); await new Promise((resolve) => { utter.onstart = resolve; }); // paused state after start event expect(speechSynthesis.paused).to.be.false(); speechSynthesis.pause(); // paused state changes async, right before the pause event expect(speechSynthesis.paused).to.be.false(); await new Promise((resolve) => { utter.onpause = resolve; }); expect(speechSynthesis.paused).to.be.true(); speechSynthesis.resume(); await new Promise((resolve) => { utter.onresume = resolve; }); // paused state after resume event expect(speechSynthesis.paused).to.be.false(); await new Promise((resolve) => { utter.onend = resolve; }); }); }); }); describe('font fallback', () => { async function getRenderedFonts (html: string) { const w = new BrowserWindow({ show: false }); try { await w.loadURL(`data:text/html,${html}`); w.webContents.debugger.attach(); const sendCommand = (method: string, commandParams?: any) => w.webContents.debugger.sendCommand(method, commandParams); const { nodeId } = (await sendCommand('DOM.getDocument')).root.children[0]; await sendCommand('CSS.enable'); const { fonts } = await sendCommand('CSS.getPlatformFontsForNode', { nodeId }); return fonts; } finally { w.close(); } } it('should use Helvetica for sans-serif on Mac, and Arial on Windows and Linux', async () => { const html = '<body style="font-family: sans-serif">test</body>'; const fonts = await getRenderedFonts(html); expect(fonts).to.be.an('array'); expect(fonts).to.have.length(1); if (process.platform === 'win32') { expect(fonts[0].familyName).to.equal('Arial'); } else if (process.platform === 'darwin') { expect(fonts[0].familyName).to.equal('Helvetica'); } else if (process.platform === 'linux') { expect(fonts[0].familyName).to.equal('DejaVu Sans'); } // I think this depends on the distro? We don't specify a default. }); ifit(process.platform !== 'linux')('should fall back to Japanese font for sans-serif Japanese script', async function () { const html = ` <html lang="ja-JP"> <head> <meta charset="utf-8" /> </head> <body style="font-family: sans-serif">test 智史</body> </html> `; const fonts = await getRenderedFonts(html); expect(fonts).to.be.an('array'); expect(fonts).to.have.length(1); if (process.platform === 'win32') { expect(fonts[0].familyName).to.be.oneOf(['Meiryo', 'Yu Gothic']); } else if (process.platform === 'darwin') { expect(fonts[0].familyName).to.equal('Hiragino Kaku Gothic ProN'); } }); }); describe('iframe using HTML fullscreen API while window is OS-fullscreened', () => { const fullscreenChildHtml = promisify(fs.readFile)( path.join(fixturesPath, 'pages', 'fullscreen-oopif.html') ); let w: BrowserWindow; let server: http.Server; let crossSiteUrl: string; beforeEach(async () => { server = http.createServer(async (_req, res) => { res.writeHead(200, { 'Content-Type': 'text/html' }); res.write(await fullscreenChildHtml); res.end(); }); const serverUrl = (await listen(server)).url; crossSiteUrl = serverUrl.replace('127.0.0.1', 'localhost'); w = new BrowserWindow({ show: true, fullscreen: true, webPreferences: { nodeIntegration: true, nodeIntegrationInSubFrames: true, contextIsolation: false } }); }); afterEach(async () => { await closeAllWindows(); (w as any) = null; server.close(); }); ifit(process.platform !== 'darwin')('can fullscreen from out-of-process iframes (non-macOS)', async () => { const fullscreenChange = once(ipcMain, 'fullscreenChange'); const html = `<iframe style="width: 0" frameborder=0 src="${crossSiteUrl}" allowfullscreen></iframe>`; w.loadURL(`data:text/html,${html}`); await fullscreenChange; const fullscreenWidth = await w.webContents.executeJavaScript( "document.querySelector('iframe').offsetWidth" ); expect(fullscreenWidth > 0).to.be.true(); await w.webContents.executeJavaScript( "document.querySelector('iframe').contentWindow.postMessage('exitFullscreen', '*')" ); await setTimeout(500); const width = await w.webContents.executeJavaScript( "document.querySelector('iframe').offsetWidth" ); expect(width).to.equal(0); }); ifit(process.platform === 'darwin')('can fullscreen from out-of-process iframes (macOS)', async () => { await once(w, 'enter-full-screen'); const fullscreenChange = once(ipcMain, 'fullscreenChange'); const html = `<iframe style="width: 0" frameborder=0 src="${crossSiteUrl}" allowfullscreen></iframe>`; w.loadURL(`data:text/html,${html}`); await fullscreenChange; const fullscreenWidth = await w.webContents.executeJavaScript( "document.querySelector('iframe').offsetWidth" ); expect(fullscreenWidth > 0).to.be.true(); await w.webContents.executeJavaScript( "document.querySelector('iframe').contentWindow.postMessage('exitFullscreen', '*')" ); await once(w.webContents, 'leave-html-full-screen'); const width = await w.webContents.executeJavaScript( "document.querySelector('iframe').offsetWidth" ); expect(width).to.equal(0); w.setFullScreen(false); await once(w, 'leave-full-screen'); }); // TODO(jkleinsc) fix this flaky test on WOA ifit(process.platform !== 'win32' || process.arch !== 'arm64')('can fullscreen from in-process iframes', async () => { if (process.platform === 'darwin') await once(w, 'enter-full-screen'); const fullscreenChange = once(ipcMain, 'fullscreenChange'); w.loadFile(path.join(fixturesPath, 'pages', 'fullscreen-ipif.html')); await fullscreenChange; const fullscreenWidth = await w.webContents.executeJavaScript( "document.querySelector('iframe').offsetWidth" ); expect(fullscreenWidth > 0).to.true(); await w.webContents.executeJavaScript('document.exitFullscreen()'); const width = await w.webContents.executeJavaScript( "document.querySelector('iframe').offsetWidth" ); expect(width).to.equal(0); }); }); describe('navigator.serial', () => { let w: BrowserWindow; before(async () => { w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); }); const getPorts: any = () => { return w.webContents.executeJavaScript(` navigator.serial.requestPort().then(port => port.toString()).catch(err => err.toString()); `, true); }; const notFoundError = 'NotFoundError: Failed to execute \'requestPort\' on \'Serial\': No port selected by the user.'; after(closeAllWindows); afterEach(() => { session.defaultSession.setPermissionCheckHandler(null); session.defaultSession.removeAllListeners('select-serial-port'); }); it('does not return a port if select-serial-port event is not defined', async () => { w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); const port = await getPorts(); expect(port).to.equal(notFoundError); }); it('does not return a port when permission denied', async () => { w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => { callback(portList[0].portId); }); session.defaultSession.setPermissionCheckHandler(() => false); const port = await getPorts(); expect(port).to.equal(notFoundError); }); it('does not crash when select-serial-port is called with an invalid port', async () => { w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => { callback('i-do-not-exist'); }); const port = await getPorts(); expect(port).to.equal(notFoundError); }); it('returns a port when select-serial-port event is defined', async () => { let havePorts = false; w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => { if (portList.length > 0) { havePorts = true; callback(portList[0].portId); } else { callback(''); } }); const port = await getPorts(); if (havePorts) { expect(port).to.equal('[object SerialPort]'); } else { expect(port).to.equal(notFoundError); } }); it('navigator.serial.getPorts() returns values', async () => { let havePorts = false; w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => { if (portList.length > 0) { havePorts = true; callback(portList[0].portId); } else { callback(''); } }); await getPorts(); if (havePorts) { const grantedPorts = await w.webContents.executeJavaScript('navigator.serial.getPorts()'); expect(grantedPorts).to.not.be.empty(); } }); it('supports port.forget()', async () => { let forgottenPortFromEvent = {}; let havePorts = false; w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => { if (portList.length > 0) { havePorts = true; callback(portList[0].portId); } else { callback(''); } }); w.webContents.session.on('serial-port-revoked', (event, details) => { forgottenPortFromEvent = details.port; }); await getPorts(); if (havePorts) { const grantedPorts = await w.webContents.executeJavaScript('navigator.serial.getPorts()'); if (grantedPorts.length > 0) { const forgottenPort = await w.webContents.executeJavaScript(` navigator.serial.getPorts().then(async(ports) => { const portInfo = await ports[0].getInfo(); await ports[0].forget(); if (portInfo.usbVendorId && portInfo.usbProductId) { return { vendorId: '' + portInfo.usbVendorId, productId: '' + portInfo.usbProductId } } else { return {}; } }) `); const grantedPorts2 = await w.webContents.executeJavaScript('navigator.serial.getPorts()'); expect(grantedPorts2.length).to.be.lessThan(grantedPorts.length); if (forgottenPort.vendorId && forgottenPort.productId) { expect(forgottenPortFromEvent).to.include(forgottenPort); } } } }); }); describe('window.getScreenDetails', () => { let w: BrowserWindow; before(async () => { w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); }); after(closeAllWindows); afterEach(() => { session.defaultSession.setPermissionRequestHandler(null); }); const getScreenDetails: any = () => { return w.webContents.executeJavaScript('window.getScreenDetails().then(data => data.screens).catch(err => err.message)', true); }; it('returns screens when a PermissionRequestHandler is not defined', async () => { const screens = await getScreenDetails(); expect(screens).to.not.equal('Read permission denied.'); }); it('returns an error when permission denied', async () => { session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => { if (permission === 'window-management') { callback(false); } else { callback(true); } }); const screens = await getScreenDetails(); expect(screens).to.equal('Permission denied.'); }); it('returns screens when permission is granted', async () => { session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => { if (permission === 'window-management') { callback(true); } else { callback(false); } }); const screens = await getScreenDetails(); expect(screens).to.not.equal('Permission denied.'); }); }); describe('navigator.clipboard.read', () => { let w: BrowserWindow; before(async () => { w = new BrowserWindow(); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); }); const readClipboard: any = () => { return w.webContents.executeJavaScript(` navigator.clipboard.read().then(clipboard => clipboard.toString()).catch(err => err.message); `, true); }; after(closeAllWindows); afterEach(() => { session.defaultSession.setPermissionRequestHandler(null); }); it('returns clipboard contents when a PermissionRequestHandler is not defined', async () => { const clipboard = await readClipboard(); expect(clipboard).to.not.equal('Read permission denied.'); }); it('returns an error when permission denied', async () => { session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => { if (permission === 'clipboard-read') { callback(false); } else { callback(true); } }); const clipboard = await readClipboard(); expect(clipboard).to.equal('Read permission denied.'); }); it('returns clipboard contents when permission is granted', async () => { session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => { if (permission === 'clipboard-read') { callback(true); } else { callback(false); } }); const clipboard = await readClipboard(); expect(clipboard).to.not.equal('Read permission denied.'); }); }); describe('navigator.clipboard.write', () => { let w: BrowserWindow; before(async () => { w = new BrowserWindow(); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); }); const writeClipboard: any = () => { return w.webContents.executeJavaScript(` navigator.clipboard.writeText('Hello World!').catch(err => err.message); `, true); }; after(closeAllWindows); afterEach(() => { session.defaultSession.setPermissionRequestHandler(null); }); it('returns clipboard contents when a PermissionRequestHandler is not defined', async () => { const clipboard = await writeClipboard(); expect(clipboard).to.not.equal('Write permission denied.'); }); it('returns an error when permission denied', async () => { session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => { if (permission === 'clipboard-sanitized-write') { callback(false); } else { callback(true); } }); const clipboard = await writeClipboard(); expect(clipboard).to.equal('Write permission denied.'); }); it('returns clipboard contents when permission is granted', async () => { session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => { if (permission === 'clipboard-sanitized-write') { callback(true); } else { callback(false); } }); const clipboard = await writeClipboard(); expect(clipboard).to.not.equal('Write permission denied.'); }); }); ifdescribe((process.platform !== 'linux' || app.isUnityRunning()))('navigator.setAppBadge/clearAppBadge', () => { let w: BrowserWindow; const expectedBadgeCount = 42; const fireAppBadgeAction: any = (action: string, value: any) => { return w.webContents.executeJavaScript(` navigator.${action}AppBadge(${value}).then(() => 'success').catch(err => err.message)`); }; // For some reason on macOS changing the badge count doesn't happen right away, so wait // until it changes. async function waitForBadgeCount (value: number) { let badgeCount = app.getBadgeCount(); while (badgeCount !== value) { await setTimeout(10); badgeCount = app.getBadgeCount(); } return badgeCount; } describe('in the renderer', () => { before(async () => { w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); }); after(() => { app.badgeCount = 0; closeAllWindows(); }); it('setAppBadge can set a numerical value', async () => { const result = await fireAppBadgeAction('set', expectedBadgeCount); expect(result).to.equal('success'); expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount); }); it('setAppBadge can set an empty(dot) value', async () => { const result = await fireAppBadgeAction('set'); expect(result).to.equal('success'); expect(waitForBadgeCount(0)).to.eventually.equal(0); }); it('clearAppBadge can clear a value', async () => { let result = await fireAppBadgeAction('set', expectedBadgeCount); expect(result).to.equal('success'); expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount); result = await fireAppBadgeAction('clear'); expect(result).to.equal('success'); expect(waitForBadgeCount(0)).to.eventually.equal(0); }); }); describe('in a service worker', () => { beforeEach(async () => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, partition: 'sw-file-scheme-spec', contextIsolation: false } }); }); afterEach(() => { app.badgeCount = 0; closeAllWindows(); }); it('setAppBadge can be called in a ServiceWorker', (done) => { w.webContents.on('ipc-message', (event, channel, message) => { if (channel === 'reload') { w.webContents.reload(); } else if (channel === 'error') { done(message); } else if (channel === 'response') { expect(message).to.equal('SUCCESS setting app badge'); expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount); session.fromPartition('sw-file-scheme-spec').clearStorageData({ storages: ['serviceworkers'] }).then(() => done()); } }); w.webContents.on('render-process-gone', () => done(new Error('WebContents crashed.'))); w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'badge-index.html'), { search: '?setBadge' }); }); it('clearAppBadge can be called in a ServiceWorker', (done) => { w.webContents.on('ipc-message', (event, channel, message) => { if (channel === 'reload') { w.webContents.reload(); } else if (channel === 'setAppBadge') { expect(message).to.equal('SUCCESS setting app badge'); expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount); } else if (channel === 'error') { done(message); } else if (channel === 'response') { expect(message).to.equal('SUCCESS clearing app badge'); expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount); session.fromPartition('sw-file-scheme-spec').clearStorageData({ storages: ['serviceworkers'] }).then(() => done()); } }); w.webContents.on('render-process-gone', () => done(new Error('WebContents crashed.'))); w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'badge-index.html'), { search: '?clearBadge' }); }); }); }); describe('navigator.bluetooth', () => { let w: BrowserWindow; before(async () => { w = new BrowserWindow({ show: false, webPreferences: { enableBlinkFeatures: 'WebBluetooth' } }); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); }); after(closeAllWindows); it('can request bluetooth devices', async () => { const bluetooth = await w.webContents.executeJavaScript(` navigator.bluetooth.requestDevice({ acceptAllDevices: true}).then(device => "Found a device!").catch(err => err.message);`, true); expect(bluetooth).to.be.oneOf(['Found a device!', 'Bluetooth adapter not available.', 'User cancelled the requestDevice() chooser.']); }); }); describe('navigator.hid', () => { let w: BrowserWindow; let server: http.Server; let serverUrl: string; before(async () => { w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); server = http.createServer((req, res) => { res.setHeader('Content-Type', 'text/html'); res.end('<body>'); }); serverUrl = (await listen(server)).url; }); const requestDevices: any = () => { return w.webContents.executeJavaScript(` navigator.hid.requestDevice({filters: []}).then(device => device.toString()).catch(err => err.toString()); `, true); }; after(() => { server.close(); closeAllWindows(); }); afterEach(() => { session.defaultSession.setPermissionCheckHandler(null); session.defaultSession.setDevicePermissionHandler(null); session.defaultSession.removeAllListeners('select-hid-device'); }); it('does not return a device if select-hid-device event is not defined', async () => { w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); const device = await requestDevices(); expect(device).to.equal(''); }); it('does not return a device when permission denied', async () => { let selectFired = false; w.webContents.session.on('select-hid-device', (event, details, callback) => { selectFired = true; callback(); }); session.defaultSession.setPermissionCheckHandler(() => false); const device = await requestDevices(); expect(selectFired).to.be.false(); expect(device).to.equal(''); }); it('returns a device when select-hid-device event is defined', async () => { let haveDevices = false; let selectFired = false; w.webContents.session.on('select-hid-device', (event, details, callback) => { expect(details.frame).to.have.property('frameTreeNodeId').that.is.a('number'); selectFired = true; if (details.deviceList.length > 0) { haveDevices = true; callback(details.deviceList[0].deviceId); } else { callback(); } }); const device = await requestDevices(); expect(selectFired).to.be.true(); if (haveDevices) { expect(device).to.contain('[object HIDDevice]'); } else { expect(device).to.equal(''); } if (haveDevices) { // Verify that navigation will clear device permissions const grantedDevices = await w.webContents.executeJavaScript('navigator.hid.getDevices()'); expect(grantedDevices).to.not.be.empty(); w.loadURL(serverUrl); const [,,,,, frameProcessId, frameRoutingId] = await once(w.webContents, 'did-frame-navigate'); const frame = webFrameMain.fromId(frameProcessId, frameRoutingId); expect(!!frame).to.be.true(); if (frame) { const grantedDevicesOnNewPage = await frame.executeJavaScript('navigator.hid.getDevices()'); expect(grantedDevicesOnNewPage).to.be.empty(); } } }); it('returns a device when DevicePermissionHandler is defined', async () => { let haveDevices = false; let selectFired = false; let gotDevicePerms = false; w.webContents.session.on('select-hid-device', (event, details, callback) => { selectFired = true; if (details.deviceList.length > 0) { const foundDevice = details.deviceList.find((device) => { if (device.name && device.name !== '' && device.serialNumber && device.serialNumber !== '') { haveDevices = true; return true; } }); if (foundDevice) { callback(foundDevice.deviceId); return; } } callback(); }); session.defaultSession.setDevicePermissionHandler(() => { gotDevicePerms = true; return true; }); await w.webContents.executeJavaScript('navigator.hid.getDevices();', true); const device = await requestDevices(); expect(selectFired).to.be.true(); if (haveDevices) { expect(device).to.contain('[object HIDDevice]'); expect(gotDevicePerms).to.be.true(); } else { expect(device).to.equal(''); } }); it('excludes a device when a exclusionFilter is specified', async () => { const exclusionFilters = <any>[]; let haveDevices = false; let checkForExcludedDevice = false; w.webContents.session.on('select-hid-device', (event, details, callback) => { if (details.deviceList.length > 0) { details.deviceList.find((device) => { if (device.name && device.name !== '' && device.serialNumber && device.serialNumber !== '') { if (checkForExcludedDevice) { const compareDevice = { vendorId: device.vendorId, productId: device.productId }; expect(compareDevice).to.not.equal(exclusionFilters[0], 'excluded device should not be returned'); } else { haveDevices = true; exclusionFilters.push({ vendorId: device.vendorId, productId: device.productId }); return true; } } }); } callback(); }); await requestDevices(); if (haveDevices) { // We have devices to exclude, so check if exclusionFilters work checkForExcludedDevice = true; await w.webContents.executeJavaScript(` navigator.hid.requestDevice({filters: [], exclusionFilters: ${JSON.stringify(exclusionFilters)}}).then(device => device.toString()).catch(err => err.toString()); `, true); } }); it('supports device.forget()', async () => { let deletedDeviceFromEvent; let haveDevices = false; w.webContents.session.on('select-hid-device', (event, details, callback) => { if (details.deviceList.length > 0) { haveDevices = true; callback(details.deviceList[0].deviceId); } else { callback(); } }); w.webContents.session.on('hid-device-revoked', (event, details) => { deletedDeviceFromEvent = details.device; }); await requestDevices(); if (haveDevices) { const grantedDevices = await w.webContents.executeJavaScript('navigator.hid.getDevices()'); if (grantedDevices.length > 0) { const deletedDevice = await w.webContents.executeJavaScript(` navigator.hid.getDevices().then(devices => { devices[0].forget(); return { vendorId: devices[0].vendorId, productId: devices[0].productId, name: devices[0].productName } }) `); const grantedDevices2 = await w.webContents.executeJavaScript('navigator.hid.getDevices()'); expect(grantedDevices2.length).to.be.lessThan(grantedDevices.length); if (deletedDevice.name !== '' && deletedDevice.productId && deletedDevice.vendorId) { expect(deletedDeviceFromEvent).to.include(deletedDevice); } } } }); }); describe('navigator.usb', () => { let w: BrowserWindow; let server: http.Server; let serverUrl: string; before(async () => { w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); server = http.createServer((req, res) => { res.setHeader('Content-Type', 'text/html'); res.end('<body>'); }); serverUrl = (await listen(server)).url; }); const requestDevices: any = () => { return w.webContents.executeJavaScript(` navigator.usb.requestDevice({filters: []}).then(device => device.toString()).catch(err => err.toString()); `, true); }; const notFoundError = 'NotFoundError: Failed to execute \'requestDevice\' on \'USB\': No device selected.'; after(() => { server.close(); closeAllWindows(); }); afterEach(() => { session.defaultSession.setPermissionCheckHandler(null); session.defaultSession.setDevicePermissionHandler(null); session.defaultSession.removeAllListeners('select-usb-device'); }); it('does not return a device if select-usb-device event is not defined', async () => { w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); const device = await requestDevices(); expect(device).to.equal(notFoundError); }); it('does not return a device when permission denied', async () => { let selectFired = false; w.webContents.session.on('select-usb-device', (event, details, callback) => { selectFired = true; callback(); }); session.defaultSession.setPermissionCheckHandler(() => false); const device = await requestDevices(); expect(selectFired).to.be.false(); expect(device).to.equal(notFoundError); }); it('returns a device when select-usb-device event is defined', async () => { let haveDevices = false; let selectFired = false; w.webContents.session.on('select-usb-device', (event, details, callback) => { expect(details.frame).to.have.property('frameTreeNodeId').that.is.a('number'); selectFired = true; if (details.deviceList.length > 0) { haveDevices = true; callback(details.deviceList[0].deviceId); } else { callback(); } }); const device = await requestDevices(); expect(selectFired).to.be.true(); if (haveDevices) { expect(device).to.contain('[object USBDevice]'); } else { expect(device).to.equal(notFoundError); } if (haveDevices) { // Verify that navigation will clear device permissions const grantedDevices = await w.webContents.executeJavaScript('navigator.usb.getDevices()'); expect(grantedDevices).to.not.be.empty(); w.loadURL(serverUrl); const [,,,,, frameProcessId, frameRoutingId] = await once(w.webContents, 'did-frame-navigate'); const frame = webFrameMain.fromId(frameProcessId, frameRoutingId); expect(!!frame).to.be.true(); if (frame) { const grantedDevicesOnNewPage = await frame.executeJavaScript('navigator.usb.getDevices()'); expect(grantedDevicesOnNewPage).to.be.empty(); } } }); it('returns a device when DevicePermissionHandler is defined', async () => { let haveDevices = false; let selectFired = false; let gotDevicePerms = false; w.webContents.session.on('select-usb-device', (event, details, callback) => { selectFired = true; if (details.deviceList.length > 0) { const foundDevice = details.deviceList.find((device) => { if (device.productName && device.productName !== '' && device.serialNumber && device.serialNumber !== '') { haveDevices = true; return true; } }); if (foundDevice) { callback(foundDevice.deviceId); return; } } callback(); }); session.defaultSession.setDevicePermissionHandler(() => { gotDevicePerms = true; return true; }); await w.webContents.executeJavaScript('navigator.usb.getDevices();', true); const device = await requestDevices(); expect(selectFired).to.be.true(); if (haveDevices) { expect(device).to.contain('[object USBDevice]'); expect(gotDevicePerms).to.be.true(); } else { expect(device).to.equal(notFoundError); } }); it('supports device.forget()', async () => { let deletedDeviceFromEvent; let haveDevices = false; w.webContents.session.on('select-usb-device', (event, details, callback) => { if (details.deviceList.length > 0) { haveDevices = true; callback(details.deviceList[0].deviceId); } else { callback(); } }); w.webContents.session.on('usb-device-revoked', (event, details) => { deletedDeviceFromEvent = details.device; }); await requestDevices(); if (haveDevices) { const grantedDevices = await w.webContents.executeJavaScript('navigator.usb.getDevices()'); if (grantedDevices.length > 0) { const deletedDevice: Electron.USBDevice = await w.webContents.executeJavaScript(` navigator.usb.getDevices().then(devices => { devices[0].forget(); return { vendorId: devices[0].vendorId, productId: devices[0].productId, productName: devices[0].productName } }) `); const grantedDevices2 = await w.webContents.executeJavaScript('navigator.usb.getDevices()'); expect(grantedDevices2.length).to.be.lessThan(grantedDevices.length); if (deletedDevice.productName !== '' && deletedDevice.productId && deletedDevice.vendorId) { expect(deletedDeviceFromEvent).to.include(deletedDevice); } } } }); });
closed
electron/electron
https://github.com/electron/electron
38,161
[Feature Request]: Allow commonjs2 scripts as sandboxed preload scripts
### 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. ### Problem Description When calling a preload script in sandboxed mode, `module` is not defined. This makes code that assigns `module.exports` crash with an error like "ReferenceError: module is not defined". This is made even more confusing since electron also emits an error "Unable to load preload script" which implies that the script was not found, and not just partly executed. This is a problem because many commonjs modules assign the `module.exports` property, as per [Node's documentation](https://nodejs.org/api/modules.html#the-module-object): > The `module.exports` object is created by the `Module` system. Sometimes this is not acceptable; many want their module to be an instance of some class. To do this, assign the desired export object to `module.exports`. Problematic commonjs scripts are created by: - `webpack` in ['commonjs2' mode](https://webpack.js.org/configuration/output/#type-commonjs2), which is the recommended format (see, e.g. Quasar https://github.com/quasarframework/quasar/issues/11759) - `esbuild` - `parcel` It seems that `rollup`, `swc`, and `typescript` do not reassign `module.exports` and so are not affected. ### Proposed Solution - Pass a `module` object with a mutable `exports` property to the [preload wrapper](https://github.com/electron/electron/blob/a8c0ed890f61664156886356ecb6ab9f73c69cf1/lib/sandboxed_renderer/init.ts#L105-L107). ### Alternatives Considered - Load the preload script as an ESM module - Use a module loader (e.g. an actual call to `require`) instead of interpolating the preload script into an `eval` call. ### Additional Information I'm not sure if this should be regarded as a feature request or a bug. It's quite surprising behavior and probably not intentional, so I'm leaning toward bug.
https://github.com/electron/electron/issues/38161
https://github.com/electron/electron/pull/39484
90865fa97d577105987d23db017c0332029228f6
3102a257af400e8b9bdddf4295d901007c65a2d6
2023-05-03T07:01:40Z
c++
2023-08-22T04:43:08Z
spec/fixtures/module/preload.js
const types = { require: typeof require, module: typeof module, process: typeof process, Buffer: typeof Buffer }; console.log(JSON.stringify(types));
closed
electron/electron
https://github.com/electron/electron
36,331
[Bug]: No BrowserCaptureMediaStreamTrack being returned when using preferCurrentTab
### 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 22.0.0-beta.4 ### 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 Looking at the tests written here https://github.com/electron/electron/pull/30702/files#diff-cc0dd3c6f0140615357588553aaf9e9f95e6132498626a5d788d8e297d98eee9 I have decided to try to use the Chromium 104+ feature for region capture. While the api appears to work, I cannot get the api call to return the expected BrowserCaptureMediaStreamTrack, instead the usual MediaStreamTrack is returned. This causes the ability to use cropTo from the track to fail since it doesnt exist in MediaStreamTrack. Given that this is still a beta, is this a known issue or do I need to do something different? ### Actual Behavior I would expect a BrowserCaptureMediaStreamTrack to be returned and track.cropTo(cropTarget) to work as expected, allowing me to share a region of the window/screen selected ### Testcase Gist URL https://gist.github.com/e277f244fcf0402152466a0fddc9720a ### Additional Information This code works fine when using it against Chrome
https://github.com/electron/electron/issues/36331
https://github.com/electron/electron/pull/39074
e1d63794e5ce74006188ed2b7f1c35b5793caf36
2481f94b4efe262c9ae2f5f16cd0845eeb6c4efd
2022-11-14T11:05:51Z
c++
2023-08-23T08:49:24Z
shell/browser/electron_browser_context.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_context.h" #include <memory> #include <utility> #include "base/barrier_closure.h" #include "base/base_paths.h" #include "base/command_line.h" #include "base/files/file_path.h" #include "base/no_destructor.h" #include "base/path_service.h" #include "base/strings/escape.h" #include "base/strings/string_util.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/pref_names.h" #include "components/keyed_service/content/browser_context_dependency_manager.h" #include "components/prefs/json_pref_store.h" #include "components/prefs/pref_registry_simple.h" #include "components/prefs/pref_service.h" #include "components/prefs/pref_service_factory.h" #include "components/prefs/value_map_pref_store.h" #include "components/proxy_config/pref_proxy_config_tracker_impl.h" #include "components/proxy_config/proxy_config_pref_names.h" #include "content/browser/blob_storage/chrome_blob_storage_context.h" // nogncheck #include "content/public/browser/browser_thread.h" #include "content/public/browser/cors_origin_pattern_setter.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/shared_cors_origin_access_list.h" #include "content/public/browser/storage_partition.h" #include "content/public/browser/web_contents_media_capture_id.h" #include "media/audio/audio_device_description.h" #include "services/network/public/cpp/features.h" #include "services/network/public/cpp/wrapper_shared_url_loader_factory.h" #include "services/network/public/mojom/network_context.mojom.h" #include "shell/browser/cookie_change_notifier.h" #include "shell/browser/electron_browser_client.h" #include "shell/browser/electron_browser_main_parts.h" #include "shell/browser/electron_download_manager_delegate.h" #include "shell/browser/electron_permission_manager.h" #include "shell/browser/net/resolve_proxy_helper.h" #include "shell/browser/protocol_registry.h" #include "shell/browser/special_storage_policy.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/web_contents_permission_helper.h" #include "shell/browser/web_view_manager.h" #include "shell/browser/zoom_level_delegate.h" #include "shell/common/application_info.h" #include "shell/common/electron_constants.h" #include "shell/common/electron_paths.h" #include "shell/common/gin_converters/frame_converter.h" #include "shell/common/gin_helper/error_thrower.h" #include "shell/common/options_switches.h" #include "shell/common/thread_restrictions.h" #include "third_party/blink/public/mojom/media/capture_handle_config.mojom.h" #include "third_party/blink/public/mojom/mediastream/media_stream.mojom.h" #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #include "extensions/browser/browser_context_keyed_service_factories.h" #include "extensions/browser/extension_pref_store.h" #include "extensions/browser/extension_pref_value_map_factory.h" #include "extensions/browser/extension_prefs.h" #include "extensions/browser/pref_names.h" #include "extensions/common/extension_api.h" #include "shell/browser/extensions/electron_browser_context_keyed_service_factories.h" #include "shell/browser/extensions/electron_extension_system.h" #include "shell/browser/extensions/electron_extension_system_factory.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_ELECTRON_EXTENSIONS) || \ BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) #include "components/pref_registry/pref_registry_syncable.h" #include "components/user_prefs/user_prefs.h" #endif #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) #include "base/i18n/rtl.h" #include "components/language/core/browser/language_prefs.h" #include "components/spellcheck/browser/pref_names.h" #include "components/spellcheck/common/spellcheck_common.h" #endif using content::BrowserThread; namespace electron { namespace { // Copied from chrome/browser/media/webrtc/desktop_capture_devices_util.cc. media::mojom::CaptureHandlePtr CreateCaptureHandle( content::WebContents* capturer, const url::Origin& capturer_origin, const content::DesktopMediaID& captured_id) { if (capturer_origin.opaque()) { return nullptr; } content::RenderFrameHost* const captured_rfh = content::RenderFrameHost::FromID( captured_id.web_contents_id.render_process_id, captured_id.web_contents_id.main_render_frame_id); if (!captured_rfh || !captured_rfh->IsActive()) { return nullptr; } content::WebContents* const captured = content::WebContents::FromRenderFrameHost(captured_rfh); if (!captured) { return nullptr; } const auto& captured_config = captured->GetCaptureHandleConfig(); if (!captured_config.all_origins_permitted && base::ranges::none_of( captured_config.permitted_origins, [capturer_origin](const url::Origin& permitted_origin) { return capturer_origin.IsSameOriginWith(permitted_origin); })) { return nullptr; } // Observing CaptureHandle when either the capturing or the captured party // is incognito is disallowed, except for self-capture. if (capturer->GetPrimaryMainFrame() != captured->GetPrimaryMainFrame()) { if (capturer->GetBrowserContext()->IsOffTheRecord() || captured->GetBrowserContext()->IsOffTheRecord()) { return nullptr; } } if (!captured_config.expose_origin && captured_config.capture_handle.empty()) { return nullptr; } auto result = media::mojom::CaptureHandle::New(); if (captured_config.expose_origin) { result->origin = captured->GetPrimaryMainFrame()->GetLastCommittedOrigin(); } result->capture_handle = captured_config.capture_handle; return result; } // Copied from chrome/browser/media/webrtc/desktop_capture_devices_util.cc. media::mojom::DisplayMediaInformationPtr DesktopMediaIDToDisplayMediaInformation( content::WebContents* capturer, const url::Origin& capturer_origin, const content::DesktopMediaID& media_id) { media::mojom::DisplayCaptureSurfaceType display_surface = media::mojom::DisplayCaptureSurfaceType::MONITOR; bool logical_surface = true; media::mojom::CursorCaptureType cursor = media::mojom::CursorCaptureType::NEVER; #if defined(USE_AURA) const bool uses_aura = media_id.window_id != content::DesktopMediaID::kNullId ? true : false; #else const bool uses_aura = false; #endif // defined(USE_AURA) media::mojom::CaptureHandlePtr capture_handle; switch (media_id.type) { case content::DesktopMediaID::TYPE_SCREEN: display_surface = media::mojom::DisplayCaptureSurfaceType::MONITOR; cursor = uses_aura ? media::mojom::CursorCaptureType::MOTION : media::mojom::CursorCaptureType::ALWAYS; break; case content::DesktopMediaID::TYPE_WINDOW: display_surface = media::mojom::DisplayCaptureSurfaceType::WINDOW; cursor = uses_aura ? media::mojom::CursorCaptureType::MOTION : media::mojom::CursorCaptureType::ALWAYS; break; case content::DesktopMediaID::TYPE_WEB_CONTENTS: display_surface = media::mojom::DisplayCaptureSurfaceType::BROWSER; cursor = media::mojom::CursorCaptureType::MOTION; capture_handle = CreateCaptureHandle(capturer, capturer_origin, media_id); break; case content::DesktopMediaID::TYPE_NONE: break; } return media::mojom::DisplayMediaInformation::New( display_surface, logical_surface, cursor, std::move(capture_handle)); } // Convert string to lower case and escape it. std::string MakePartitionName(const std::string& input) { return base::EscapePath(base::ToLowerASCII(input)); } } // namespace // static ElectronBrowserContext::BrowserContextMap& ElectronBrowserContext::browser_context_map() { static base::NoDestructor<ElectronBrowserContext::BrowserContextMap> browser_context_map; return *browser_context_map; } ElectronBrowserContext::ElectronBrowserContext( const PartitionOrPath partition_location, bool in_memory, base::Value::Dict options) : in_memory_pref_store_(new ValueMapPrefStore), storage_policy_(base::MakeRefCounted<SpecialStoragePolicy>()), protocol_registry_(base::WrapUnique(new ProtocolRegistry)), in_memory_(in_memory), ssl_config_(network::mojom::SSLConfig::New()) { // Read options. base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); use_cache_ = !command_line->HasSwitch(switches::kDisableHttpCache); if (auto use_cache_opt = options.FindBool("cache")) { use_cache_ = use_cache_opt.value(); } base::StringToInt(command_line->GetSwitchValueASCII(switches::kDiskCacheSize), &max_cache_size_); if (auto* path_value = std::get_if<std::reference_wrapper<const std::string>>( &partition_location)) { base::PathService::Get(DIR_SESSION_DATA, &path_); const std::string& partition_loc = path_value->get(); if (!in_memory && !partition_loc.empty()) { path_ = path_.Append(FILE_PATH_LITERAL("Partitions")) .Append(base::FilePath::FromUTF8Unsafe( MakePartitionName(partition_loc))); } } else if (auto* filepath_partition = std::get_if<std::reference_wrapper<const base::FilePath>>( &partition_location)) { const base::FilePath& partition_path = filepath_partition->get(); path_ = std::move(partition_path); } BrowserContextDependencyManager::GetInstance()->MarkBrowserContextLive(this); // Initialize Pref Registry. InitPrefs(); cookie_change_notifier_ = std::make_unique<CookieChangeNotifier>(this); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) if (!in_memory_) { BrowserContextDependencyManager::GetInstance() ->CreateBrowserContextServices(this); extension_system_ = static_cast<extensions::ElectronExtensionSystem*>( extensions::ExtensionSystem::Get(this)); extension_system_->InitForRegularProfile(true /* extensions_enabled */); extension_system_->FinishInitialization(); } #endif } ElectronBrowserContext::~ElectronBrowserContext() { DCHECK_CURRENTLY_ON(BrowserThread::UI); NotifyWillBeDestroyed(); // Notify any keyed services of browser context destruction. BrowserContextDependencyManager::GetInstance()->DestroyBrowserContextServices( this); ShutdownStoragePartitions(); BrowserThread::DeleteSoon(BrowserThread::IO, FROM_HERE, std::move(resource_context_)); } void ElectronBrowserContext::InitPrefs() { auto prefs_path = GetPath().Append(FILE_PATH_LITERAL("Preferences")); ScopedAllowBlockingForElectron allow_blocking; PrefServiceFactory prefs_factory; scoped_refptr<JsonPrefStore> pref_store = base::MakeRefCounted<JsonPrefStore>(prefs_path); pref_store->ReadPrefs(); // Synchronous. prefs_factory.set_user_prefs(pref_store); prefs_factory.set_command_line_prefs(in_memory_pref_store()); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) if (!in_memory_) { auto* ext_pref_store = new ExtensionPrefStore( ExtensionPrefValueMapFactory::GetForBrowserContext(this), IsOffTheRecord()); prefs_factory.set_extension_prefs(ext_pref_store); } #endif #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) || \ BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) auto registry = base::MakeRefCounted<user_prefs::PrefRegistrySyncable>(); #else auto registry = base::MakeRefCounted<PrefRegistrySimple>(); #endif registry->RegisterFilePathPref(prefs::kSelectFileLastDirectory, base::FilePath()); base::FilePath download_dir; base::PathService::Get(chrome::DIR_DEFAULT_DOWNLOADS, &download_dir); registry->RegisterFilePathPref(prefs::kDownloadDefaultDirectory, download_dir); registry->RegisterDictionaryPref(prefs::kDevToolsFileSystemPaths); InspectableWebContents::RegisterPrefs(registry.get()); MediaDeviceIDSalt::RegisterPrefs(registry.get()); ZoomLevelDelegate::RegisterPrefs(registry.get()); PrefProxyConfigTrackerImpl::RegisterPrefs(registry.get()); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) if (!in_memory_) extensions::ExtensionPrefs::RegisterProfilePrefs(registry.get()); #endif #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) BrowserContextDependencyManager::GetInstance() ->RegisterProfilePrefsForServices(registry.get()); language::LanguagePrefs::RegisterProfilePrefs(registry.get()); #endif prefs_ = prefs_factory.Create(registry.get()); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) || \ BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) user_prefs::UserPrefs::Set(this, prefs_.get()); #endif #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) // No configured dictionaries, the default will be en-US if (prefs()->GetList(spellcheck::prefs::kSpellCheckDictionaries).empty()) { std::string default_code = spellcheck::GetCorrespondingSpellCheckLanguage( base::i18n::GetConfiguredLocale()); if (!default_code.empty()) { base::Value::List language_codes; language_codes.Append(default_code); prefs()->Set(spellcheck::prefs::kSpellCheckDictionaries, base::Value(std::move(language_codes))); } } #endif } void ElectronBrowserContext::SetUserAgent(const std::string& user_agent) { user_agent_ = user_agent; } base::FilePath ElectronBrowserContext::GetPath() { return path_; } bool ElectronBrowserContext::IsOffTheRecord() { return in_memory_; } bool ElectronBrowserContext::CanUseHttpCache() const { return use_cache_; } int ElectronBrowserContext::GetMaxCacheSize() const { return max_cache_size_; } content::ResourceContext* ElectronBrowserContext::GetResourceContext() { if (!resource_context_) resource_context_ = std::make_unique<content::ResourceContext>(); return resource_context_.get(); } std::string ElectronBrowserContext::GetMediaDeviceIDSalt() { if (!media_device_id_salt_.get()) media_device_id_salt_ = std::make_unique<MediaDeviceIDSalt>(prefs_.get()); return media_device_id_salt_->GetSalt(); } std::unique_ptr<content::ZoomLevelDelegate> ElectronBrowserContext::CreateZoomLevelDelegate( const base::FilePath& partition_path) { if (!IsOffTheRecord()) { return std::make_unique<ZoomLevelDelegate>(prefs(), partition_path); } return std::unique_ptr<content::ZoomLevelDelegate>(); } content::DownloadManagerDelegate* ElectronBrowserContext::GetDownloadManagerDelegate() { if (!download_manager_delegate_.get()) { auto* download_manager = this->GetDownloadManager(); download_manager_delegate_ = std::make_unique<ElectronDownloadManagerDelegate>(download_manager); } return download_manager_delegate_.get(); } content::BrowserPluginGuestManager* ElectronBrowserContext::GetGuestManager() { if (!guest_manager_) guest_manager_ = std::make_unique<WebViewManager>(); return guest_manager_.get(); } content::PlatformNotificationService* ElectronBrowserContext::GetPlatformNotificationService() { return ElectronBrowserClient::Get()->GetPlatformNotificationService(); } content::PermissionControllerDelegate* ElectronBrowserContext::GetPermissionControllerDelegate() { if (!permission_manager_.get()) permission_manager_ = std::make_unique<ElectronPermissionManager>(); return permission_manager_.get(); } storage::SpecialStoragePolicy* ElectronBrowserContext::GetSpecialStoragePolicy() { return storage_policy_.get(); } std::string ElectronBrowserContext::GetUserAgent() const { return user_agent_.value_or(ElectronBrowserClient::Get()->GetUserAgent()); } predictors::PreconnectManager* ElectronBrowserContext::GetPreconnectManager() { if (!preconnect_manager_.get()) { preconnect_manager_ = std::make_unique<predictors::PreconnectManager>(nullptr, this); } return preconnect_manager_.get(); } scoped_refptr<network::SharedURLLoaderFactory> ElectronBrowserContext::GetURLLoaderFactory() { if (url_loader_factory_) return url_loader_factory_; mojo::PendingRemote<network::mojom::URLLoaderFactory> network_factory_remote; mojo::PendingReceiver<network::mojom::URLLoaderFactory> factory_receiver = network_factory_remote.InitWithNewPipeAndPassReceiver(); // Consult the embedder. mojo::PendingRemote<network::mojom::TrustedURLLoaderHeaderClient> header_client; static_cast<content::ContentBrowserClient*>(ElectronBrowserClient::Get()) ->WillCreateURLLoaderFactory( this, nullptr, -1, content::ContentBrowserClient::URLLoaderFactoryType::kNavigation, url::Origin(), absl::nullopt, ukm::kInvalidSourceIdObj, &factory_receiver, &header_client, nullptr, nullptr, nullptr, nullptr); network::mojom::URLLoaderFactoryParamsPtr params = network::mojom::URLLoaderFactoryParams::New(); params->header_client = std::move(header_client); params->process_id = network::mojom::kBrowserProcessId; params->is_trusted = true; params->is_corb_enabled = false; // The tests of net module would fail if this setting is true, it seems that // the non-NetworkService implementation always has web security enabled. params->disable_web_security = false; auto* storage_partition = GetDefaultStoragePartition(); storage_partition->GetNetworkContext()->CreateURLLoaderFactory( std::move(factory_receiver), std::move(params)); url_loader_factory_ = base::MakeRefCounted<network::WrapperSharedURLLoaderFactory>( std::move(network_factory_remote)); return url_loader_factory_; } content::PushMessagingService* ElectronBrowserContext::GetPushMessagingService() { return nullptr; } content::SSLHostStateDelegate* ElectronBrowserContext::GetSSLHostStateDelegate() { return nullptr; } content::BackgroundFetchDelegate* ElectronBrowserContext::GetBackgroundFetchDelegate() { return nullptr; } content::BackgroundSyncController* ElectronBrowserContext::GetBackgroundSyncController() { return nullptr; } content::BrowsingDataRemoverDelegate* ElectronBrowserContext::GetBrowsingDataRemoverDelegate() { return nullptr; } content::ClientHintsControllerDelegate* ElectronBrowserContext::GetClientHintsControllerDelegate() { return nullptr; } content::StorageNotificationService* ElectronBrowserContext::GetStorageNotificationService() { return nullptr; } content::ReduceAcceptLanguageControllerDelegate* ElectronBrowserContext::GetReduceAcceptLanguageControllerDelegate() { // Needs implementation // Refs https://chromium-review.googlesource.com/c/chromium/src/+/3687391 return nullptr; } ResolveProxyHelper* ElectronBrowserContext::GetResolveProxyHelper() { if (!resolve_proxy_helper_) { resolve_proxy_helper_ = base::MakeRefCounted<ResolveProxyHelper>(this); } return resolve_proxy_helper_.get(); } network::mojom::SSLConfigPtr ElectronBrowserContext::GetSSLConfig() { return ssl_config_.Clone(); } void ElectronBrowserContext::SetSSLConfig(network::mojom::SSLConfigPtr config) { ssl_config_ = std::move(config); if (ssl_config_client_) { ssl_config_client_->OnSSLConfigUpdated(ssl_config_.Clone()); } } void ElectronBrowserContext::SetSSLConfigClient( mojo::Remote<network::mojom::SSLConfigClient> client) { ssl_config_client_ = std::move(client); } void ElectronBrowserContext::SetDisplayMediaRequestHandler( DisplayMediaRequestHandler handler) { display_media_request_handler_ = handler; } void ElectronBrowserContext::DisplayMediaDeviceChosen( const content::MediaStreamRequest& request, content::MediaResponseCallback callback, gin::Arguments* args) { blink::mojom::StreamDevicesSetPtr stream_devices_set = blink::mojom::StreamDevicesSet::New(); v8::Local<v8::Value> result; if (!args->GetNext(&result) || result->IsNullOrUndefined()) { std::move(callback).Run( blink::mojom::StreamDevicesSet(), blink::mojom::MediaStreamRequestResult::CAPTURE_FAILURE, nullptr); return; } gin_helper::Dictionary result_dict; if (!gin::ConvertFromV8(args->isolate(), result, &result_dict)) { gin_helper::ErrorThrower(args->isolate()) .ThrowTypeError( "Display Media Request streams callback must be called with null " "or a valid object"); std::move(callback).Run( blink::mojom::StreamDevicesSet(), blink::mojom::MediaStreamRequestResult::CAPTURE_FAILURE, nullptr); return; } stream_devices_set->stream_devices.emplace_back( blink::mojom::StreamDevices::New()); blink::mojom::StreamDevices& devices = *stream_devices_set->stream_devices[0]; bool video_requested = request.video_type != blink::mojom::MediaStreamType::NO_SERVICE; bool audio_requested = request.audio_type != blink::mojom::MediaStreamType::NO_SERVICE; bool has_video = false; if (video_requested && result_dict.Has("video")) { gin_helper::Dictionary video_dict; std::string id; std::string name; content::RenderFrameHost* rfh; if (result_dict.Get("video", &video_dict) && video_dict.Get("id", &id) && video_dict.Get("name", &name)) { blink::MediaStreamDevice video_device(request.video_type, id, name); video_device.display_media_info = DesktopMediaIDToDisplayMediaInformation( nullptr, url::Origin::Create(request.security_origin), content::DesktopMediaID::Parse(request.requested_video_device_id)); devices.video_device = video_device; } else if (result_dict.Get("video", &rfh)) { auto* web_contents = content::WebContents::FromRenderFrameHost(rfh); blink::MediaStreamDevice video_device( request.video_type, content::WebContentsMediaCaptureId(rfh->GetProcess()->GetID(), rfh->GetRoutingID()) .ToString(), base::UTF16ToUTF8(web_contents->GetTitle())); video_device.display_media_info = DesktopMediaIDToDisplayMediaInformation( web_contents, url::Origin::Create(request.security_origin), content::DesktopMediaID::Parse(request.requested_video_device_id)); devices.video_device = video_device; } else { gin_helper::ErrorThrower(args->isolate()) .ThrowTypeError( "video must be a WebFrameMain or DesktopCapturerSource"); std::move(callback).Run( blink::mojom::StreamDevicesSet(), blink::mojom::MediaStreamRequestResult::CAPTURE_FAILURE, nullptr); return; } has_video = true; } if (audio_requested && result_dict.Has("audio")) { gin_helper::Dictionary audio_dict; std::string id; std::string name; content::RenderFrameHost* rfh; // NB. this is not permitted by the documentation, but is left here as an // "escape hatch" for providing an arbitrary name/id if needed in the // future. if (result_dict.Get("audio", &audio_dict) && audio_dict.Get("id", &id) && audio_dict.Get("name", &name)) { blink::MediaStreamDevice audio_device(request.audio_type, id, name); audio_device.display_media_info = DesktopMediaIDToDisplayMediaInformation( nullptr, url::Origin::Create(request.security_origin), content::DesktopMediaID::Parse(request.requested_audio_device_id)); devices.audio_device = audio_device; } else if (result_dict.Get("audio", &rfh)) { bool enable_local_echo = false; result_dict.Get("enableLocalEcho", &enable_local_echo); bool disable_local_echo = !enable_local_echo; auto* web_contents = content::WebContents::FromRenderFrameHost(rfh); blink::MediaStreamDevice audio_device( request.audio_type, content::WebContentsMediaCaptureId(rfh->GetProcess()->GetID(), rfh->GetRoutingID(), disable_local_echo) .ToString(), "Tab audio"); audio_device.display_media_info = DesktopMediaIDToDisplayMediaInformation( web_contents, url::Origin::Create(request.security_origin), content::DesktopMediaID::Parse(request.requested_audio_device_id)); devices.audio_device = audio_device; } else if (result_dict.Get("audio", &id)) { blink::MediaStreamDevice audio_device(request.audio_type, id, "System audio"); audio_device.display_media_info = DesktopMediaIDToDisplayMediaInformation( nullptr, url::Origin::Create(request.security_origin), content::DesktopMediaID::Parse(request.requested_audio_device_id)); devices.audio_device = audio_device; } else { gin_helper::ErrorThrower(args->isolate()) .ThrowTypeError( "audio must be a WebFrameMain, \"loopback\" or " "\"loopbackWithMute\""); std::move(callback).Run( blink::mojom::StreamDevicesSet(), blink::mojom::MediaStreamRequestResult::CAPTURE_FAILURE, nullptr); return; } } if ((video_requested && !has_video)) { gin_helper::ErrorThrower(args->isolate()) .ThrowTypeError( "Video was requested, but no video stream was provided"); std::move(callback).Run( blink::mojom::StreamDevicesSet(), blink::mojom::MediaStreamRequestResult::CAPTURE_FAILURE, nullptr); return; } std::move(callback).Run(*stream_devices_set, blink::mojom::MediaStreamRequestResult::OK, nullptr); } bool ElectronBrowserContext::ChooseDisplayMediaDevice( const content::MediaStreamRequest& request, content::MediaResponseCallback callback) { if (!display_media_request_handler_) return false; DisplayMediaResponseCallbackJs callbackJs = base::BindOnce(&DisplayMediaDeviceChosen, request, std::move(callback)); display_media_request_handler_.Run(request, std::move(callbackJs)); return true; } void ElectronBrowserContext::GrantDevicePermission( const url::Origin& origin, const base::Value& device, blink::PermissionType permission_type) { granted_devices_[permission_type][origin].push_back( std::make_unique<base::Value>(device.Clone())); } void ElectronBrowserContext::RevokeDevicePermission( const url::Origin& origin, const base::Value& device, blink::PermissionType permission_type) { const auto& current_devices_it = granted_devices_.find(permission_type); if (current_devices_it == granted_devices_.end()) return; const auto& origin_devices_it = current_devices_it->second.find(origin); if (origin_devices_it == current_devices_it->second.end()) return; for (auto it = origin_devices_it->second.begin(); it != origin_devices_it->second.end();) { if (DoesDeviceMatch(device, it->get(), permission_type)) { it = origin_devices_it->second.erase(it); } else { ++it; } } } bool ElectronBrowserContext::DoesDeviceMatch( const base::Value& device, const base::Value* device_to_compare, blink::PermissionType permission_type) { if (permission_type == static_cast<blink::PermissionType>( WebContentsPermissionHelper::PermissionType::HID) || permission_type == static_cast<blink::PermissionType>( WebContentsPermissionHelper::PermissionType::USB)) { if (device.GetDict().FindInt(kDeviceVendorIdKey) != device_to_compare->GetDict().FindInt(kDeviceVendorIdKey) || device.GetDict().FindInt(kDeviceProductIdKey) != device_to_compare->GetDict().FindInt(kDeviceProductIdKey)) { return false; } const auto* serial_number = device_to_compare->GetDict().FindString(kDeviceSerialNumberKey); const auto* device_serial_number = device.GetDict().FindString(kDeviceSerialNumberKey); if (serial_number && device_serial_number && *device_serial_number == *serial_number) return true; } else if (permission_type == static_cast<blink::PermissionType>( WebContentsPermissionHelper::PermissionType::SERIAL)) { #if BUILDFLAG(IS_WIN) const auto* instance_id = device.GetDict().FindString(kDeviceInstanceIdKey); const auto* port_instance_id = device_to_compare->GetDict().FindString(kDeviceInstanceIdKey); if (instance_id && port_instance_id && *instance_id == *port_instance_id) return true; #else const auto* serial_number = device.GetDict().FindString(kSerialNumberKey); const auto* port_serial_number = device_to_compare->GetDict().FindString(kSerialNumberKey); if (device.GetDict().FindInt(kVendorIdKey) != device_to_compare->GetDict().FindInt(kVendorIdKey) || device.GetDict().FindInt(kProductIdKey) != device_to_compare->GetDict().FindInt(kProductIdKey) || (serial_number && port_serial_number && *port_serial_number != *serial_number)) { return false; } #if BUILDFLAG(IS_MAC) const auto* usb_driver_key = device.GetDict().FindString(kUsbDriverKey); const auto* port_usb_driver_key = device_to_compare->GetDict().FindString(kUsbDriverKey); if (usb_driver_key && port_usb_driver_key && *usb_driver_key != *port_usb_driver_key) { return false; } #endif // BUILDFLAG(IS_MAC) return true; #endif // BUILDFLAG(IS_WIN) } return false; } bool ElectronBrowserContext::CheckDevicePermission( const url::Origin& origin, const base::Value& device, blink::PermissionType permission_type) { const auto& current_devices_it = granted_devices_.find(permission_type); if (current_devices_it == granted_devices_.end()) return false; const auto& origin_devices_it = current_devices_it->second.find(origin); if (origin_devices_it == current_devices_it->second.end()) return false; for (const auto& device_to_compare : origin_devices_it->second) { if (DoesDeviceMatch(device, device_to_compare.get(), permission_type)) return true; } return false; } // static ElectronBrowserContext* ElectronBrowserContext::From( const std::string& partition, bool in_memory, base::Value::Dict options) { PartitionKey key(partition, in_memory); ElectronBrowserContext* browser_context = browser_context_map()[key].get(); if (browser_context) { return browser_context; } auto* new_context = new ElectronBrowserContext(std::cref(partition), in_memory, std::move(options)); browser_context_map()[key] = std::unique_ptr<ElectronBrowserContext>(new_context); return new_context; } ElectronBrowserContext* ElectronBrowserContext::FromPath( const base::FilePath& path, base::Value::Dict options) { PartitionKey key(path); ElectronBrowserContext* browser_context = browser_context_map()[key].get(); if (browser_context) { return browser_context; } auto* new_context = new ElectronBrowserContext(std::cref(path), false, std::move(options)); browser_context_map()[key] = std::unique_ptr<ElectronBrowserContext>(new_context); return new_context; } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
36,331
[Bug]: No BrowserCaptureMediaStreamTrack being returned when using preferCurrentTab
### 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 22.0.0-beta.4 ### 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 Looking at the tests written here https://github.com/electron/electron/pull/30702/files#diff-cc0dd3c6f0140615357588553aaf9e9f95e6132498626a5d788d8e297d98eee9 I have decided to try to use the Chromium 104+ feature for region capture. While the api appears to work, I cannot get the api call to return the expected BrowserCaptureMediaStreamTrack, instead the usual MediaStreamTrack is returned. This causes the ability to use cropTo from the track to fail since it doesnt exist in MediaStreamTrack. Given that this is still a beta, is this a known issue or do I need to do something different? ### Actual Behavior I would expect a BrowserCaptureMediaStreamTrack to be returned and track.cropTo(cropTarget) to work as expected, allowing me to share a region of the window/screen selected ### Testcase Gist URL https://gist.github.com/e277f244fcf0402152466a0fddc9720a ### Additional Information This code works fine when using it against Chrome
https://github.com/electron/electron/issues/36331
https://github.com/electron/electron/pull/39074
e1d63794e5ce74006188ed2b7f1c35b5793caf36
2481f94b4efe262c9ae2f5f16cd0845eeb6c4efd
2022-11-14T11:05:51Z
c++
2023-08-23T08:49:24Z
spec/api-media-handler-spec.ts
import { expect } from 'chai'; import { BrowserWindow, session, desktopCapturer } from 'electron/main'; import { closeAllWindows } from './lib/window-helpers'; import * as http from 'node:http'; import { ifit, listen } from './lib/spec-helpers'; describe('setDisplayMediaRequestHandler', () => { afterEach(closeAllWindows); // These tests are done on an http server because navigator.userAgentData // requires a secure context. let server: http.Server; let serverUrl: string; before(async () => { server = http.createServer((req, res) => { res.setHeader('Content-Type', 'text/html'); res.end(''); }); serverUrl = (await listen(server)).url; }); after(() => { server.close(); }); // FIXME(nornagon): this test fails on our macOS CircleCI runners with the // error message: // [ERROR:video_capture_device_client.cc(659)] error@ OnStart@content/browser/media/capture/desktop_capture_device_mac.cc:98, CGDisplayStreamCreate failed, OS message: Value too large to be stored in data type (84) // This is possibly related to the OS/VM setup that CircleCI uses for macOS. // Our arm64 runners are in @jkleinsc's office, and are real machines, so the // test works there. ifit(!(process.platform === 'darwin' && process.arch === 'x64'))('works when calling getDisplayMedia', async function () { if ((await desktopCapturer.getSources({ types: ['screen'] })).length === 0) { return this.skip(); } const ses = session.fromPartition('' + Math.random()); let requestHandlerCalled = false; let mediaRequest: any = null; ses.setDisplayMediaRequestHandler((request, callback) => { requestHandlerCalled = true; mediaRequest = request; desktopCapturer.getSources({ types: ['screen'] }).then((sources) => { // Grant access to the first screen found. const { id, name } = sources[0]; callback({ video: { id, name } // TODO: 'loopback' and 'loopbackWithMute' are currently only supported on Windows. // audio: { id: 'loopback', name: 'System Audio' } }); }); }); const w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await w.loadURL(serverUrl); const { ok, message } = await w.webContents.executeJavaScript(` navigator.mediaDevices.getDisplayMedia({ video: true, audio: false, }).then(x => ({ok: x instanceof MediaStream}), e => ({ok: false, message: e.message})) `, true); expect(requestHandlerCalled).to.be.true(); expect(mediaRequest.videoRequested).to.be.true(); expect(mediaRequest.audioRequested).to.be.false(); expect(ok).to.be.true(message); }); it('does not crash when using a bogus ID', async () => { const ses = session.fromPartition('' + Math.random()); let requestHandlerCalled = false; ses.setDisplayMediaRequestHandler((request, callback) => { requestHandlerCalled = true; callback({ video: { id: 'bogus', name: 'whatever' } }); }); const w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await w.loadURL(serverUrl); const { ok, message } = await w.webContents.executeJavaScript(` navigator.mediaDevices.getDisplayMedia({ video: true, audio: true, }).then(x => ({ok: x instanceof MediaStream}), e => ({ok: false, message: e.message})) `, true); expect(requestHandlerCalled).to.be.true(); expect(ok).to.be.false(); expect(message).to.equal('Could not start video source'); }); it('successfully returns a capture handle', async () => { let w: BrowserWindow | null = null; const ses = session.fromPartition('' + Math.random()); let requestHandlerCalled = false; let mediaRequest: any = null; ses.setDisplayMediaRequestHandler((request, callback) => { requestHandlerCalled = true; mediaRequest = request; callback({ video: w?.webContents.mainFrame }); }); w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await w.loadURL(serverUrl); const { ok, handleID, captureHandle, message } = await w.webContents.executeJavaScript(` const handleID = crypto.randomUUID(); navigator.mediaDevices.setCaptureHandleConfig({ handle: handleID, exposeOrigin: true, permittedOrigins: ["*"], }); navigator.mediaDevices.getDisplayMedia({ video: true, audio: false }).then(stream => { const [videoTrack] = stream.getVideoTracks(); const captureHandle = videoTrack.getCaptureHandle(); return { ok: true, handleID, captureHandle, message: null } }, e => ({ ok: false, message: e.message })) `, true); expect(requestHandlerCalled).to.be.true(); expect(mediaRequest.videoRequested).to.be.true(); expect(mediaRequest.audioRequested).to.be.false(); expect(ok).to.be.true(); expect(captureHandle.handle).to.be.a('string'); expect(handleID).to.eq(captureHandle.handle); expect(message).to.be.null(); }); it('does not crash when providing only audio for a video request', async () => { const ses = session.fromPartition('' + Math.random()); let requestHandlerCalled = false; let callbackError: any; ses.setDisplayMediaRequestHandler((request, callback) => { requestHandlerCalled = true; try { callback({ audio: 'loopback' }); } catch (e) { callbackError = e; } }); const w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await w.loadURL(serverUrl); const { ok } = await w.webContents.executeJavaScript(` navigator.mediaDevices.getDisplayMedia({ video: true, }).then(x => ({ok: x instanceof MediaStream}), e => ({ok: false, message: e.message})) `, true); expect(requestHandlerCalled).to.be.true(); expect(ok).to.be.false(); expect(callbackError?.message).to.equal('Video was requested, but no video stream was provided'); }); it('does not crash when providing only an audio stream for an audio+video request', async () => { const ses = session.fromPartition('' + Math.random()); let requestHandlerCalled = false; let callbackError: any; ses.setDisplayMediaRequestHandler((request, callback) => { requestHandlerCalled = true; try { callback({ audio: 'loopback' }); } catch (e) { callbackError = e; } }); const w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await w.loadURL(serverUrl); const { ok } = await w.webContents.executeJavaScript(` navigator.mediaDevices.getDisplayMedia({ video: true, audio: true, }).then(x => ({ok: x instanceof MediaStream}), e => ({ok: false, message: e.message})) `, true); expect(requestHandlerCalled).to.be.true(); expect(ok).to.be.false(); expect(callbackError?.message).to.equal('Video was requested, but no video stream was provided'); }); it('does not crash when providing a non-loopback audio stream', async () => { const ses = session.fromPartition('' + Math.random()); let requestHandlerCalled = false; ses.setDisplayMediaRequestHandler((request, callback) => { requestHandlerCalled = true; callback({ video: w.webContents.mainFrame, audio: 'default' as any }); }); const w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await w.loadURL(serverUrl); const { ok } = await w.webContents.executeJavaScript(` navigator.mediaDevices.getDisplayMedia({ video: true, audio: true, }).then(x => ({ok: x instanceof MediaStream}), e => ({ok: false, message: e.message})) `, true); expect(requestHandlerCalled).to.be.true(); expect(ok).to.be.true(); }); it('does not crash when providing no streams', async () => { const ses = session.fromPartition('' + Math.random()); let requestHandlerCalled = false; let callbackError: any; ses.setDisplayMediaRequestHandler((request, callback) => { requestHandlerCalled = true; try { callback({}); } catch (e) { callbackError = e; } }); const w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await w.loadURL(serverUrl); const { ok } = await w.webContents.executeJavaScript(` navigator.mediaDevices.getDisplayMedia({ video: true, audio: true, }).then(x => ({ok: x instanceof MediaStream}), e => ({ok: false, message: e.message})) `, true); expect(requestHandlerCalled).to.be.true(); expect(ok).to.be.false(); expect(callbackError.message).to.equal('Video was requested, but no video stream was provided'); }); it('does not crash when using a bogus web-contents-media-stream:// ID', async () => { const ses = session.fromPartition('' + Math.random()); let requestHandlerCalled = false; ses.setDisplayMediaRequestHandler((request, callback) => { requestHandlerCalled = true; callback({ video: { id: 'web-contents-media-stream://9999:9999', name: 'whatever' } }); }); const w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await w.loadURL(serverUrl); const { ok } = await w.webContents.executeJavaScript(` navigator.mediaDevices.getDisplayMedia({ video: true, audio: true, }).then(x => ({ok: x instanceof MediaStream}), e => ({ok: false, message: e.message})) `, true); expect(requestHandlerCalled).to.be.true(); // This is a little surprising... apparently chrome will generate a stream // for this non-existent web contents? expect(ok).to.be.true(); }); it('is not called when calling getUserMedia', async () => { const ses = session.fromPartition('' + Math.random()); ses.setDisplayMediaRequestHandler(() => { throw new Error('bad'); }); const w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await w.loadURL(serverUrl); const { ok, message } = await w.webContents.executeJavaScript(` navigator.mediaDevices.getUserMedia({ video: true, audio: true, }).then(x => ({ok: x instanceof MediaStream}), e => ({ok: false, message: e.message})) `); expect(ok).to.be.true(message); }); it('works when calling getDisplayMedia with preferCurrentTab', async () => { const ses = session.fromPartition('' + Math.random()); let requestHandlerCalled = false; ses.setDisplayMediaRequestHandler((request, callback) => { requestHandlerCalled = true; callback({ video: w.webContents.mainFrame }); }); const w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await w.loadURL(serverUrl); const { ok, message } = await w.webContents.executeJavaScript(` navigator.mediaDevices.getDisplayMedia({ preferCurrentTab: true, video: true, audio: true, }).then(x => ({ok: x instanceof MediaStream}), e => ({ok: false, message: e.message})) `, true); expect(requestHandlerCalled).to.be.true(); expect(ok).to.be.true(message); }); ifit(!(process.platform === 'darwin' && process.arch === 'x64'))('can supply a screen response to preferCurrentTab', async () => { const ses = session.fromPartition('' + Math.random()); let requestHandlerCalled = false; ses.setDisplayMediaRequestHandler(async (request, callback) => { requestHandlerCalled = true; const sources = await desktopCapturer.getSources({ types: ['screen'] }); callback({ video: sources[0] }); }); const w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await w.loadURL(serverUrl); const { ok, message } = await w.webContents.executeJavaScript(` navigator.mediaDevices.getDisplayMedia({ preferCurrentTab: true, video: true, audio: true, }).then(x => ({ok: x instanceof MediaStream}), e => ({ok: false, message: e.message})) `, true); expect(requestHandlerCalled).to.be.true(); expect(ok).to.be.true(message); }); it('can supply a frame response', async () => { const ses = session.fromPartition('' + Math.random()); let requestHandlerCalled = false; ses.setDisplayMediaRequestHandler(async (request, callback) => { requestHandlerCalled = true; callback({ video: w.webContents.mainFrame }); }); const w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await w.loadURL(serverUrl); const { ok, message } = await w.webContents.executeJavaScript(` navigator.mediaDevices.getDisplayMedia({ video: true, }).then(x => ({ok: x instanceof MediaStream}), e => ({ok: false, message: e.message})) `, true); expect(requestHandlerCalled).to.be.true(); expect(ok).to.be.true(message); }); it('is not called when calling legacy getUserMedia', async () => { const ses = session.fromPartition('' + Math.random()); ses.setDisplayMediaRequestHandler(() => { throw new Error('bad'); }); const w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await w.loadURL(serverUrl); const { ok, message } = await w.webContents.executeJavaScript(` new Promise((resolve, reject) => navigator.getUserMedia({ video: true, audio: true, }, x => resolve({ok: x instanceof MediaStream}), e => reject({ok: false, message: e.message}))) `); expect(ok).to.be.true(message); }); it('is not called when calling legacy getUserMedia with desktop capture constraint', async () => { const ses = session.fromPartition('' + Math.random()); ses.setDisplayMediaRequestHandler(() => { throw new Error('bad'); }); const w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await w.loadURL(serverUrl); const { ok, message } = await w.webContents.executeJavaScript(` new Promise((resolve, reject) => navigator.getUserMedia({ video: { mandatory: { chromeMediaSource: 'desktop' } }, }, x => resolve({ok: x instanceof MediaStream}), e => reject({ok: false, message: e.message}))) `); expect(ok).to.be.true(message); }); it('works when calling getUserMedia without a media request handler', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(serverUrl); const { ok, message } = await w.webContents.executeJavaScript(` navigator.mediaDevices.getUserMedia({ video: true, audio: true, }).then(x => ({ok: x instanceof MediaStream}), e => ({ok: false, message: e.message})) `); expect(ok).to.be.true(message); }); it('works when calling legacy getUserMedia without a media request handler', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(serverUrl); const { ok, message } = await w.webContents.executeJavaScript(` new Promise((resolve, reject) => navigator.getUserMedia({ video: true, audio: true, }, x => resolve({ok: x instanceof MediaStream}), e => reject({ok: false, message: e.message}))) `); expect(ok).to.be.true(message); }); it('can remove a displayMediaRequestHandler', async () => { const ses = session.fromPartition('' + Math.random()); ses.setDisplayMediaRequestHandler(() => { throw new Error('bad'); }); ses.setDisplayMediaRequestHandler(null); const w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await w.loadURL(serverUrl); const { ok, message } = await w.webContents.executeJavaScript(` navigator.mediaDevices.getDisplayMedia({ video: true, }).then(x => ({ok: x instanceof MediaStream}), e => ({ok: false, message: e.message})) `, true); expect(ok).to.be.false(); expect(message).to.equal('Not supported'); }); });
closed
electron/electron
https://github.com/electron/electron
36,331
[Bug]: No BrowserCaptureMediaStreamTrack being returned when using preferCurrentTab
### 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 22.0.0-beta.4 ### 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 Looking at the tests written here https://github.com/electron/electron/pull/30702/files#diff-cc0dd3c6f0140615357588553aaf9e9f95e6132498626a5d788d8e297d98eee9 I have decided to try to use the Chromium 104+ feature for region capture. While the api appears to work, I cannot get the api call to return the expected BrowserCaptureMediaStreamTrack, instead the usual MediaStreamTrack is returned. This causes the ability to use cropTo from the track to fail since it doesnt exist in MediaStreamTrack. Given that this is still a beta, is this a known issue or do I need to do something different? ### Actual Behavior I would expect a BrowserCaptureMediaStreamTrack to be returned and track.cropTo(cropTarget) to work as expected, allowing me to share a region of the window/screen selected ### Testcase Gist URL https://gist.github.com/e277f244fcf0402152466a0fddc9720a ### Additional Information This code works fine when using it against Chrome
https://github.com/electron/electron/issues/36331
https://github.com/electron/electron/pull/39074
e1d63794e5ce74006188ed2b7f1c35b5793caf36
2481f94b4efe262c9ae2f5f16cd0845eeb6c4efd
2022-11-14T11:05:51Z
c++
2023-08-23T08:49:24Z
shell/browser/electron_browser_context.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_context.h" #include <memory> #include <utility> #include "base/barrier_closure.h" #include "base/base_paths.h" #include "base/command_line.h" #include "base/files/file_path.h" #include "base/no_destructor.h" #include "base/path_service.h" #include "base/strings/escape.h" #include "base/strings/string_util.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/pref_names.h" #include "components/keyed_service/content/browser_context_dependency_manager.h" #include "components/prefs/json_pref_store.h" #include "components/prefs/pref_registry_simple.h" #include "components/prefs/pref_service.h" #include "components/prefs/pref_service_factory.h" #include "components/prefs/value_map_pref_store.h" #include "components/proxy_config/pref_proxy_config_tracker_impl.h" #include "components/proxy_config/proxy_config_pref_names.h" #include "content/browser/blob_storage/chrome_blob_storage_context.h" // nogncheck #include "content/public/browser/browser_thread.h" #include "content/public/browser/cors_origin_pattern_setter.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/shared_cors_origin_access_list.h" #include "content/public/browser/storage_partition.h" #include "content/public/browser/web_contents_media_capture_id.h" #include "media/audio/audio_device_description.h" #include "services/network/public/cpp/features.h" #include "services/network/public/cpp/wrapper_shared_url_loader_factory.h" #include "services/network/public/mojom/network_context.mojom.h" #include "shell/browser/cookie_change_notifier.h" #include "shell/browser/electron_browser_client.h" #include "shell/browser/electron_browser_main_parts.h" #include "shell/browser/electron_download_manager_delegate.h" #include "shell/browser/electron_permission_manager.h" #include "shell/browser/net/resolve_proxy_helper.h" #include "shell/browser/protocol_registry.h" #include "shell/browser/special_storage_policy.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/web_contents_permission_helper.h" #include "shell/browser/web_view_manager.h" #include "shell/browser/zoom_level_delegate.h" #include "shell/common/application_info.h" #include "shell/common/electron_constants.h" #include "shell/common/electron_paths.h" #include "shell/common/gin_converters/frame_converter.h" #include "shell/common/gin_helper/error_thrower.h" #include "shell/common/options_switches.h" #include "shell/common/thread_restrictions.h" #include "third_party/blink/public/mojom/media/capture_handle_config.mojom.h" #include "third_party/blink/public/mojom/mediastream/media_stream.mojom.h" #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #include "extensions/browser/browser_context_keyed_service_factories.h" #include "extensions/browser/extension_pref_store.h" #include "extensions/browser/extension_pref_value_map_factory.h" #include "extensions/browser/extension_prefs.h" #include "extensions/browser/pref_names.h" #include "extensions/common/extension_api.h" #include "shell/browser/extensions/electron_browser_context_keyed_service_factories.h" #include "shell/browser/extensions/electron_extension_system.h" #include "shell/browser/extensions/electron_extension_system_factory.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_ELECTRON_EXTENSIONS) || \ BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) #include "components/pref_registry/pref_registry_syncable.h" #include "components/user_prefs/user_prefs.h" #endif #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) #include "base/i18n/rtl.h" #include "components/language/core/browser/language_prefs.h" #include "components/spellcheck/browser/pref_names.h" #include "components/spellcheck/common/spellcheck_common.h" #endif using content::BrowserThread; namespace electron { namespace { // Copied from chrome/browser/media/webrtc/desktop_capture_devices_util.cc. media::mojom::CaptureHandlePtr CreateCaptureHandle( content::WebContents* capturer, const url::Origin& capturer_origin, const content::DesktopMediaID& captured_id) { if (capturer_origin.opaque()) { return nullptr; } content::RenderFrameHost* const captured_rfh = content::RenderFrameHost::FromID( captured_id.web_contents_id.render_process_id, captured_id.web_contents_id.main_render_frame_id); if (!captured_rfh || !captured_rfh->IsActive()) { return nullptr; } content::WebContents* const captured = content::WebContents::FromRenderFrameHost(captured_rfh); if (!captured) { return nullptr; } const auto& captured_config = captured->GetCaptureHandleConfig(); if (!captured_config.all_origins_permitted && base::ranges::none_of( captured_config.permitted_origins, [capturer_origin](const url::Origin& permitted_origin) { return capturer_origin.IsSameOriginWith(permitted_origin); })) { return nullptr; } // Observing CaptureHandle when either the capturing or the captured party // is incognito is disallowed, except for self-capture. if (capturer->GetPrimaryMainFrame() != captured->GetPrimaryMainFrame()) { if (capturer->GetBrowserContext()->IsOffTheRecord() || captured->GetBrowserContext()->IsOffTheRecord()) { return nullptr; } } if (!captured_config.expose_origin && captured_config.capture_handle.empty()) { return nullptr; } auto result = media::mojom::CaptureHandle::New(); if (captured_config.expose_origin) { result->origin = captured->GetPrimaryMainFrame()->GetLastCommittedOrigin(); } result->capture_handle = captured_config.capture_handle; return result; } // Copied from chrome/browser/media/webrtc/desktop_capture_devices_util.cc. media::mojom::DisplayMediaInformationPtr DesktopMediaIDToDisplayMediaInformation( content::WebContents* capturer, const url::Origin& capturer_origin, const content::DesktopMediaID& media_id) { media::mojom::DisplayCaptureSurfaceType display_surface = media::mojom::DisplayCaptureSurfaceType::MONITOR; bool logical_surface = true; media::mojom::CursorCaptureType cursor = media::mojom::CursorCaptureType::NEVER; #if defined(USE_AURA) const bool uses_aura = media_id.window_id != content::DesktopMediaID::kNullId ? true : false; #else const bool uses_aura = false; #endif // defined(USE_AURA) media::mojom::CaptureHandlePtr capture_handle; switch (media_id.type) { case content::DesktopMediaID::TYPE_SCREEN: display_surface = media::mojom::DisplayCaptureSurfaceType::MONITOR; cursor = uses_aura ? media::mojom::CursorCaptureType::MOTION : media::mojom::CursorCaptureType::ALWAYS; break; case content::DesktopMediaID::TYPE_WINDOW: display_surface = media::mojom::DisplayCaptureSurfaceType::WINDOW; cursor = uses_aura ? media::mojom::CursorCaptureType::MOTION : media::mojom::CursorCaptureType::ALWAYS; break; case content::DesktopMediaID::TYPE_WEB_CONTENTS: display_surface = media::mojom::DisplayCaptureSurfaceType::BROWSER; cursor = media::mojom::CursorCaptureType::MOTION; capture_handle = CreateCaptureHandle(capturer, capturer_origin, media_id); break; case content::DesktopMediaID::TYPE_NONE: break; } return media::mojom::DisplayMediaInformation::New( display_surface, logical_surface, cursor, std::move(capture_handle)); } // Convert string to lower case and escape it. std::string MakePartitionName(const std::string& input) { return base::EscapePath(base::ToLowerASCII(input)); } } // namespace // static ElectronBrowserContext::BrowserContextMap& ElectronBrowserContext::browser_context_map() { static base::NoDestructor<ElectronBrowserContext::BrowserContextMap> browser_context_map; return *browser_context_map; } ElectronBrowserContext::ElectronBrowserContext( const PartitionOrPath partition_location, bool in_memory, base::Value::Dict options) : in_memory_pref_store_(new ValueMapPrefStore), storage_policy_(base::MakeRefCounted<SpecialStoragePolicy>()), protocol_registry_(base::WrapUnique(new ProtocolRegistry)), in_memory_(in_memory), ssl_config_(network::mojom::SSLConfig::New()) { // Read options. base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); use_cache_ = !command_line->HasSwitch(switches::kDisableHttpCache); if (auto use_cache_opt = options.FindBool("cache")) { use_cache_ = use_cache_opt.value(); } base::StringToInt(command_line->GetSwitchValueASCII(switches::kDiskCacheSize), &max_cache_size_); if (auto* path_value = std::get_if<std::reference_wrapper<const std::string>>( &partition_location)) { base::PathService::Get(DIR_SESSION_DATA, &path_); const std::string& partition_loc = path_value->get(); if (!in_memory && !partition_loc.empty()) { path_ = path_.Append(FILE_PATH_LITERAL("Partitions")) .Append(base::FilePath::FromUTF8Unsafe( MakePartitionName(partition_loc))); } } else if (auto* filepath_partition = std::get_if<std::reference_wrapper<const base::FilePath>>( &partition_location)) { const base::FilePath& partition_path = filepath_partition->get(); path_ = std::move(partition_path); } BrowserContextDependencyManager::GetInstance()->MarkBrowserContextLive(this); // Initialize Pref Registry. InitPrefs(); cookie_change_notifier_ = std::make_unique<CookieChangeNotifier>(this); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) if (!in_memory_) { BrowserContextDependencyManager::GetInstance() ->CreateBrowserContextServices(this); extension_system_ = static_cast<extensions::ElectronExtensionSystem*>( extensions::ExtensionSystem::Get(this)); extension_system_->InitForRegularProfile(true /* extensions_enabled */); extension_system_->FinishInitialization(); } #endif } ElectronBrowserContext::~ElectronBrowserContext() { DCHECK_CURRENTLY_ON(BrowserThread::UI); NotifyWillBeDestroyed(); // Notify any keyed services of browser context destruction. BrowserContextDependencyManager::GetInstance()->DestroyBrowserContextServices( this); ShutdownStoragePartitions(); BrowserThread::DeleteSoon(BrowserThread::IO, FROM_HERE, std::move(resource_context_)); } void ElectronBrowserContext::InitPrefs() { auto prefs_path = GetPath().Append(FILE_PATH_LITERAL("Preferences")); ScopedAllowBlockingForElectron allow_blocking; PrefServiceFactory prefs_factory; scoped_refptr<JsonPrefStore> pref_store = base::MakeRefCounted<JsonPrefStore>(prefs_path); pref_store->ReadPrefs(); // Synchronous. prefs_factory.set_user_prefs(pref_store); prefs_factory.set_command_line_prefs(in_memory_pref_store()); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) if (!in_memory_) { auto* ext_pref_store = new ExtensionPrefStore( ExtensionPrefValueMapFactory::GetForBrowserContext(this), IsOffTheRecord()); prefs_factory.set_extension_prefs(ext_pref_store); } #endif #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) || \ BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) auto registry = base::MakeRefCounted<user_prefs::PrefRegistrySyncable>(); #else auto registry = base::MakeRefCounted<PrefRegistrySimple>(); #endif registry->RegisterFilePathPref(prefs::kSelectFileLastDirectory, base::FilePath()); base::FilePath download_dir; base::PathService::Get(chrome::DIR_DEFAULT_DOWNLOADS, &download_dir); registry->RegisterFilePathPref(prefs::kDownloadDefaultDirectory, download_dir); registry->RegisterDictionaryPref(prefs::kDevToolsFileSystemPaths); InspectableWebContents::RegisterPrefs(registry.get()); MediaDeviceIDSalt::RegisterPrefs(registry.get()); ZoomLevelDelegate::RegisterPrefs(registry.get()); PrefProxyConfigTrackerImpl::RegisterPrefs(registry.get()); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) if (!in_memory_) extensions::ExtensionPrefs::RegisterProfilePrefs(registry.get()); #endif #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) BrowserContextDependencyManager::GetInstance() ->RegisterProfilePrefsForServices(registry.get()); language::LanguagePrefs::RegisterProfilePrefs(registry.get()); #endif prefs_ = prefs_factory.Create(registry.get()); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) || \ BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) user_prefs::UserPrefs::Set(this, prefs_.get()); #endif #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) // No configured dictionaries, the default will be en-US if (prefs()->GetList(spellcheck::prefs::kSpellCheckDictionaries).empty()) { std::string default_code = spellcheck::GetCorrespondingSpellCheckLanguage( base::i18n::GetConfiguredLocale()); if (!default_code.empty()) { base::Value::List language_codes; language_codes.Append(default_code); prefs()->Set(spellcheck::prefs::kSpellCheckDictionaries, base::Value(std::move(language_codes))); } } #endif } void ElectronBrowserContext::SetUserAgent(const std::string& user_agent) { user_agent_ = user_agent; } base::FilePath ElectronBrowserContext::GetPath() { return path_; } bool ElectronBrowserContext::IsOffTheRecord() { return in_memory_; } bool ElectronBrowserContext::CanUseHttpCache() const { return use_cache_; } int ElectronBrowserContext::GetMaxCacheSize() const { return max_cache_size_; } content::ResourceContext* ElectronBrowserContext::GetResourceContext() { if (!resource_context_) resource_context_ = std::make_unique<content::ResourceContext>(); return resource_context_.get(); } std::string ElectronBrowserContext::GetMediaDeviceIDSalt() { if (!media_device_id_salt_.get()) media_device_id_salt_ = std::make_unique<MediaDeviceIDSalt>(prefs_.get()); return media_device_id_salt_->GetSalt(); } std::unique_ptr<content::ZoomLevelDelegate> ElectronBrowserContext::CreateZoomLevelDelegate( const base::FilePath& partition_path) { if (!IsOffTheRecord()) { return std::make_unique<ZoomLevelDelegate>(prefs(), partition_path); } return std::unique_ptr<content::ZoomLevelDelegate>(); } content::DownloadManagerDelegate* ElectronBrowserContext::GetDownloadManagerDelegate() { if (!download_manager_delegate_.get()) { auto* download_manager = this->GetDownloadManager(); download_manager_delegate_ = std::make_unique<ElectronDownloadManagerDelegate>(download_manager); } return download_manager_delegate_.get(); } content::BrowserPluginGuestManager* ElectronBrowserContext::GetGuestManager() { if (!guest_manager_) guest_manager_ = std::make_unique<WebViewManager>(); return guest_manager_.get(); } content::PlatformNotificationService* ElectronBrowserContext::GetPlatformNotificationService() { return ElectronBrowserClient::Get()->GetPlatformNotificationService(); } content::PermissionControllerDelegate* ElectronBrowserContext::GetPermissionControllerDelegate() { if (!permission_manager_.get()) permission_manager_ = std::make_unique<ElectronPermissionManager>(); return permission_manager_.get(); } storage::SpecialStoragePolicy* ElectronBrowserContext::GetSpecialStoragePolicy() { return storage_policy_.get(); } std::string ElectronBrowserContext::GetUserAgent() const { return user_agent_.value_or(ElectronBrowserClient::Get()->GetUserAgent()); } predictors::PreconnectManager* ElectronBrowserContext::GetPreconnectManager() { if (!preconnect_manager_.get()) { preconnect_manager_ = std::make_unique<predictors::PreconnectManager>(nullptr, this); } return preconnect_manager_.get(); } scoped_refptr<network::SharedURLLoaderFactory> ElectronBrowserContext::GetURLLoaderFactory() { if (url_loader_factory_) return url_loader_factory_; mojo::PendingRemote<network::mojom::URLLoaderFactory> network_factory_remote; mojo::PendingReceiver<network::mojom::URLLoaderFactory> factory_receiver = network_factory_remote.InitWithNewPipeAndPassReceiver(); // Consult the embedder. mojo::PendingRemote<network::mojom::TrustedURLLoaderHeaderClient> header_client; static_cast<content::ContentBrowserClient*>(ElectronBrowserClient::Get()) ->WillCreateURLLoaderFactory( this, nullptr, -1, content::ContentBrowserClient::URLLoaderFactoryType::kNavigation, url::Origin(), absl::nullopt, ukm::kInvalidSourceIdObj, &factory_receiver, &header_client, nullptr, nullptr, nullptr, nullptr); network::mojom::URLLoaderFactoryParamsPtr params = network::mojom::URLLoaderFactoryParams::New(); params->header_client = std::move(header_client); params->process_id = network::mojom::kBrowserProcessId; params->is_trusted = true; params->is_corb_enabled = false; // The tests of net module would fail if this setting is true, it seems that // the non-NetworkService implementation always has web security enabled. params->disable_web_security = false; auto* storage_partition = GetDefaultStoragePartition(); storage_partition->GetNetworkContext()->CreateURLLoaderFactory( std::move(factory_receiver), std::move(params)); url_loader_factory_ = base::MakeRefCounted<network::WrapperSharedURLLoaderFactory>( std::move(network_factory_remote)); return url_loader_factory_; } content::PushMessagingService* ElectronBrowserContext::GetPushMessagingService() { return nullptr; } content::SSLHostStateDelegate* ElectronBrowserContext::GetSSLHostStateDelegate() { return nullptr; } content::BackgroundFetchDelegate* ElectronBrowserContext::GetBackgroundFetchDelegate() { return nullptr; } content::BackgroundSyncController* ElectronBrowserContext::GetBackgroundSyncController() { return nullptr; } content::BrowsingDataRemoverDelegate* ElectronBrowserContext::GetBrowsingDataRemoverDelegate() { return nullptr; } content::ClientHintsControllerDelegate* ElectronBrowserContext::GetClientHintsControllerDelegate() { return nullptr; } content::StorageNotificationService* ElectronBrowserContext::GetStorageNotificationService() { return nullptr; } content::ReduceAcceptLanguageControllerDelegate* ElectronBrowserContext::GetReduceAcceptLanguageControllerDelegate() { // Needs implementation // Refs https://chromium-review.googlesource.com/c/chromium/src/+/3687391 return nullptr; } ResolveProxyHelper* ElectronBrowserContext::GetResolveProxyHelper() { if (!resolve_proxy_helper_) { resolve_proxy_helper_ = base::MakeRefCounted<ResolveProxyHelper>(this); } return resolve_proxy_helper_.get(); } network::mojom::SSLConfigPtr ElectronBrowserContext::GetSSLConfig() { return ssl_config_.Clone(); } void ElectronBrowserContext::SetSSLConfig(network::mojom::SSLConfigPtr config) { ssl_config_ = std::move(config); if (ssl_config_client_) { ssl_config_client_->OnSSLConfigUpdated(ssl_config_.Clone()); } } void ElectronBrowserContext::SetSSLConfigClient( mojo::Remote<network::mojom::SSLConfigClient> client) { ssl_config_client_ = std::move(client); } void ElectronBrowserContext::SetDisplayMediaRequestHandler( DisplayMediaRequestHandler handler) { display_media_request_handler_ = handler; } void ElectronBrowserContext::DisplayMediaDeviceChosen( const content::MediaStreamRequest& request, content::MediaResponseCallback callback, gin::Arguments* args) { blink::mojom::StreamDevicesSetPtr stream_devices_set = blink::mojom::StreamDevicesSet::New(); v8::Local<v8::Value> result; if (!args->GetNext(&result) || result->IsNullOrUndefined()) { std::move(callback).Run( blink::mojom::StreamDevicesSet(), blink::mojom::MediaStreamRequestResult::CAPTURE_FAILURE, nullptr); return; } gin_helper::Dictionary result_dict; if (!gin::ConvertFromV8(args->isolate(), result, &result_dict)) { gin_helper::ErrorThrower(args->isolate()) .ThrowTypeError( "Display Media Request streams callback must be called with null " "or a valid object"); std::move(callback).Run( blink::mojom::StreamDevicesSet(), blink::mojom::MediaStreamRequestResult::CAPTURE_FAILURE, nullptr); return; } stream_devices_set->stream_devices.emplace_back( blink::mojom::StreamDevices::New()); blink::mojom::StreamDevices& devices = *stream_devices_set->stream_devices[0]; bool video_requested = request.video_type != blink::mojom::MediaStreamType::NO_SERVICE; bool audio_requested = request.audio_type != blink::mojom::MediaStreamType::NO_SERVICE; bool has_video = false; if (video_requested && result_dict.Has("video")) { gin_helper::Dictionary video_dict; std::string id; std::string name; content::RenderFrameHost* rfh; if (result_dict.Get("video", &video_dict) && video_dict.Get("id", &id) && video_dict.Get("name", &name)) { blink::MediaStreamDevice video_device(request.video_type, id, name); video_device.display_media_info = DesktopMediaIDToDisplayMediaInformation( nullptr, url::Origin::Create(request.security_origin), content::DesktopMediaID::Parse(request.requested_video_device_id)); devices.video_device = video_device; } else if (result_dict.Get("video", &rfh)) { auto* web_contents = content::WebContents::FromRenderFrameHost(rfh); blink::MediaStreamDevice video_device( request.video_type, content::WebContentsMediaCaptureId(rfh->GetProcess()->GetID(), rfh->GetRoutingID()) .ToString(), base::UTF16ToUTF8(web_contents->GetTitle())); video_device.display_media_info = DesktopMediaIDToDisplayMediaInformation( web_contents, url::Origin::Create(request.security_origin), content::DesktopMediaID::Parse(request.requested_video_device_id)); devices.video_device = video_device; } else { gin_helper::ErrorThrower(args->isolate()) .ThrowTypeError( "video must be a WebFrameMain or DesktopCapturerSource"); std::move(callback).Run( blink::mojom::StreamDevicesSet(), blink::mojom::MediaStreamRequestResult::CAPTURE_FAILURE, nullptr); return; } has_video = true; } if (audio_requested && result_dict.Has("audio")) { gin_helper::Dictionary audio_dict; std::string id; std::string name; content::RenderFrameHost* rfh; // NB. this is not permitted by the documentation, but is left here as an // "escape hatch" for providing an arbitrary name/id if needed in the // future. if (result_dict.Get("audio", &audio_dict) && audio_dict.Get("id", &id) && audio_dict.Get("name", &name)) { blink::MediaStreamDevice audio_device(request.audio_type, id, name); audio_device.display_media_info = DesktopMediaIDToDisplayMediaInformation( nullptr, url::Origin::Create(request.security_origin), content::DesktopMediaID::Parse(request.requested_audio_device_id)); devices.audio_device = audio_device; } else if (result_dict.Get("audio", &rfh)) { bool enable_local_echo = false; result_dict.Get("enableLocalEcho", &enable_local_echo); bool disable_local_echo = !enable_local_echo; auto* web_contents = content::WebContents::FromRenderFrameHost(rfh); blink::MediaStreamDevice audio_device( request.audio_type, content::WebContentsMediaCaptureId(rfh->GetProcess()->GetID(), rfh->GetRoutingID(), disable_local_echo) .ToString(), "Tab audio"); audio_device.display_media_info = DesktopMediaIDToDisplayMediaInformation( web_contents, url::Origin::Create(request.security_origin), content::DesktopMediaID::Parse(request.requested_audio_device_id)); devices.audio_device = audio_device; } else if (result_dict.Get("audio", &id)) { blink::MediaStreamDevice audio_device(request.audio_type, id, "System audio"); audio_device.display_media_info = DesktopMediaIDToDisplayMediaInformation( nullptr, url::Origin::Create(request.security_origin), content::DesktopMediaID::Parse(request.requested_audio_device_id)); devices.audio_device = audio_device; } else { gin_helper::ErrorThrower(args->isolate()) .ThrowTypeError( "audio must be a WebFrameMain, \"loopback\" or " "\"loopbackWithMute\""); std::move(callback).Run( blink::mojom::StreamDevicesSet(), blink::mojom::MediaStreamRequestResult::CAPTURE_FAILURE, nullptr); return; } } if ((video_requested && !has_video)) { gin_helper::ErrorThrower(args->isolate()) .ThrowTypeError( "Video was requested, but no video stream was provided"); std::move(callback).Run( blink::mojom::StreamDevicesSet(), blink::mojom::MediaStreamRequestResult::CAPTURE_FAILURE, nullptr); return; } std::move(callback).Run(*stream_devices_set, blink::mojom::MediaStreamRequestResult::OK, nullptr); } bool ElectronBrowserContext::ChooseDisplayMediaDevice( const content::MediaStreamRequest& request, content::MediaResponseCallback callback) { if (!display_media_request_handler_) return false; DisplayMediaResponseCallbackJs callbackJs = base::BindOnce(&DisplayMediaDeviceChosen, request, std::move(callback)); display_media_request_handler_.Run(request, std::move(callbackJs)); return true; } void ElectronBrowserContext::GrantDevicePermission( const url::Origin& origin, const base::Value& device, blink::PermissionType permission_type) { granted_devices_[permission_type][origin].push_back( std::make_unique<base::Value>(device.Clone())); } void ElectronBrowserContext::RevokeDevicePermission( const url::Origin& origin, const base::Value& device, blink::PermissionType permission_type) { const auto& current_devices_it = granted_devices_.find(permission_type); if (current_devices_it == granted_devices_.end()) return; const auto& origin_devices_it = current_devices_it->second.find(origin); if (origin_devices_it == current_devices_it->second.end()) return; for (auto it = origin_devices_it->second.begin(); it != origin_devices_it->second.end();) { if (DoesDeviceMatch(device, it->get(), permission_type)) { it = origin_devices_it->second.erase(it); } else { ++it; } } } bool ElectronBrowserContext::DoesDeviceMatch( const base::Value& device, const base::Value* device_to_compare, blink::PermissionType permission_type) { if (permission_type == static_cast<blink::PermissionType>( WebContentsPermissionHelper::PermissionType::HID) || permission_type == static_cast<blink::PermissionType>( WebContentsPermissionHelper::PermissionType::USB)) { if (device.GetDict().FindInt(kDeviceVendorIdKey) != device_to_compare->GetDict().FindInt(kDeviceVendorIdKey) || device.GetDict().FindInt(kDeviceProductIdKey) != device_to_compare->GetDict().FindInt(kDeviceProductIdKey)) { return false; } const auto* serial_number = device_to_compare->GetDict().FindString(kDeviceSerialNumberKey); const auto* device_serial_number = device.GetDict().FindString(kDeviceSerialNumberKey); if (serial_number && device_serial_number && *device_serial_number == *serial_number) return true; } else if (permission_type == static_cast<blink::PermissionType>( WebContentsPermissionHelper::PermissionType::SERIAL)) { #if BUILDFLAG(IS_WIN) const auto* instance_id = device.GetDict().FindString(kDeviceInstanceIdKey); const auto* port_instance_id = device_to_compare->GetDict().FindString(kDeviceInstanceIdKey); if (instance_id && port_instance_id && *instance_id == *port_instance_id) return true; #else const auto* serial_number = device.GetDict().FindString(kSerialNumberKey); const auto* port_serial_number = device_to_compare->GetDict().FindString(kSerialNumberKey); if (device.GetDict().FindInt(kVendorIdKey) != device_to_compare->GetDict().FindInt(kVendorIdKey) || device.GetDict().FindInt(kProductIdKey) != device_to_compare->GetDict().FindInt(kProductIdKey) || (serial_number && port_serial_number && *port_serial_number != *serial_number)) { return false; } #if BUILDFLAG(IS_MAC) const auto* usb_driver_key = device.GetDict().FindString(kUsbDriverKey); const auto* port_usb_driver_key = device_to_compare->GetDict().FindString(kUsbDriverKey); if (usb_driver_key && port_usb_driver_key && *usb_driver_key != *port_usb_driver_key) { return false; } #endif // BUILDFLAG(IS_MAC) return true; #endif // BUILDFLAG(IS_WIN) } return false; } bool ElectronBrowserContext::CheckDevicePermission( const url::Origin& origin, const base::Value& device, blink::PermissionType permission_type) { const auto& current_devices_it = granted_devices_.find(permission_type); if (current_devices_it == granted_devices_.end()) return false; const auto& origin_devices_it = current_devices_it->second.find(origin); if (origin_devices_it == current_devices_it->second.end()) return false; for (const auto& device_to_compare : origin_devices_it->second) { if (DoesDeviceMatch(device, device_to_compare.get(), permission_type)) return true; } return false; } // static ElectronBrowserContext* ElectronBrowserContext::From( const std::string& partition, bool in_memory, base::Value::Dict options) { PartitionKey key(partition, in_memory); ElectronBrowserContext* browser_context = browser_context_map()[key].get(); if (browser_context) { return browser_context; } auto* new_context = new ElectronBrowserContext(std::cref(partition), in_memory, std::move(options)); browser_context_map()[key] = std::unique_ptr<ElectronBrowserContext>(new_context); return new_context; } ElectronBrowserContext* ElectronBrowserContext::FromPath( const base::FilePath& path, base::Value::Dict options) { PartitionKey key(path); ElectronBrowserContext* browser_context = browser_context_map()[key].get(); if (browser_context) { return browser_context; } auto* new_context = new ElectronBrowserContext(std::cref(path), false, std::move(options)); browser_context_map()[key] = std::unique_ptr<ElectronBrowserContext>(new_context); return new_context; } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
36,331
[Bug]: No BrowserCaptureMediaStreamTrack being returned when using preferCurrentTab
### 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 22.0.0-beta.4 ### 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 Looking at the tests written here https://github.com/electron/electron/pull/30702/files#diff-cc0dd3c6f0140615357588553aaf9e9f95e6132498626a5d788d8e297d98eee9 I have decided to try to use the Chromium 104+ feature for region capture. While the api appears to work, I cannot get the api call to return the expected BrowserCaptureMediaStreamTrack, instead the usual MediaStreamTrack is returned. This causes the ability to use cropTo from the track to fail since it doesnt exist in MediaStreamTrack. Given that this is still a beta, is this a known issue or do I need to do something different? ### Actual Behavior I would expect a BrowserCaptureMediaStreamTrack to be returned and track.cropTo(cropTarget) to work as expected, allowing me to share a region of the window/screen selected ### Testcase Gist URL https://gist.github.com/e277f244fcf0402152466a0fddc9720a ### Additional Information This code works fine when using it against Chrome
https://github.com/electron/electron/issues/36331
https://github.com/electron/electron/pull/39074
e1d63794e5ce74006188ed2b7f1c35b5793caf36
2481f94b4efe262c9ae2f5f16cd0845eeb6c4efd
2022-11-14T11:05:51Z
c++
2023-08-23T08:49:24Z
spec/api-media-handler-spec.ts
import { expect } from 'chai'; import { BrowserWindow, session, desktopCapturer } from 'electron/main'; import { closeAllWindows } from './lib/window-helpers'; import * as http from 'node:http'; import { ifit, listen } from './lib/spec-helpers'; describe('setDisplayMediaRequestHandler', () => { afterEach(closeAllWindows); // These tests are done on an http server because navigator.userAgentData // requires a secure context. let server: http.Server; let serverUrl: string; before(async () => { server = http.createServer((req, res) => { res.setHeader('Content-Type', 'text/html'); res.end(''); }); serverUrl = (await listen(server)).url; }); after(() => { server.close(); }); // FIXME(nornagon): this test fails on our macOS CircleCI runners with the // error message: // [ERROR:video_capture_device_client.cc(659)] error@ OnStart@content/browser/media/capture/desktop_capture_device_mac.cc:98, CGDisplayStreamCreate failed, OS message: Value too large to be stored in data type (84) // This is possibly related to the OS/VM setup that CircleCI uses for macOS. // Our arm64 runners are in @jkleinsc's office, and are real machines, so the // test works there. ifit(!(process.platform === 'darwin' && process.arch === 'x64'))('works when calling getDisplayMedia', async function () { if ((await desktopCapturer.getSources({ types: ['screen'] })).length === 0) { return this.skip(); } const ses = session.fromPartition('' + Math.random()); let requestHandlerCalled = false; let mediaRequest: any = null; ses.setDisplayMediaRequestHandler((request, callback) => { requestHandlerCalled = true; mediaRequest = request; desktopCapturer.getSources({ types: ['screen'] }).then((sources) => { // Grant access to the first screen found. const { id, name } = sources[0]; callback({ video: { id, name } // TODO: 'loopback' and 'loopbackWithMute' are currently only supported on Windows. // audio: { id: 'loopback', name: 'System Audio' } }); }); }); const w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await w.loadURL(serverUrl); const { ok, message } = await w.webContents.executeJavaScript(` navigator.mediaDevices.getDisplayMedia({ video: true, audio: false, }).then(x => ({ok: x instanceof MediaStream}), e => ({ok: false, message: e.message})) `, true); expect(requestHandlerCalled).to.be.true(); expect(mediaRequest.videoRequested).to.be.true(); expect(mediaRequest.audioRequested).to.be.false(); expect(ok).to.be.true(message); }); it('does not crash when using a bogus ID', async () => { const ses = session.fromPartition('' + Math.random()); let requestHandlerCalled = false; ses.setDisplayMediaRequestHandler((request, callback) => { requestHandlerCalled = true; callback({ video: { id: 'bogus', name: 'whatever' } }); }); const w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await w.loadURL(serverUrl); const { ok, message } = await w.webContents.executeJavaScript(` navigator.mediaDevices.getDisplayMedia({ video: true, audio: true, }).then(x => ({ok: x instanceof MediaStream}), e => ({ok: false, message: e.message})) `, true); expect(requestHandlerCalled).to.be.true(); expect(ok).to.be.false(); expect(message).to.equal('Could not start video source'); }); it('successfully returns a capture handle', async () => { let w: BrowserWindow | null = null; const ses = session.fromPartition('' + Math.random()); let requestHandlerCalled = false; let mediaRequest: any = null; ses.setDisplayMediaRequestHandler((request, callback) => { requestHandlerCalled = true; mediaRequest = request; callback({ video: w?.webContents.mainFrame }); }); w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await w.loadURL(serverUrl); const { ok, handleID, captureHandle, message } = await w.webContents.executeJavaScript(` const handleID = crypto.randomUUID(); navigator.mediaDevices.setCaptureHandleConfig({ handle: handleID, exposeOrigin: true, permittedOrigins: ["*"], }); navigator.mediaDevices.getDisplayMedia({ video: true, audio: false }).then(stream => { const [videoTrack] = stream.getVideoTracks(); const captureHandle = videoTrack.getCaptureHandle(); return { ok: true, handleID, captureHandle, message: null } }, e => ({ ok: false, message: e.message })) `, true); expect(requestHandlerCalled).to.be.true(); expect(mediaRequest.videoRequested).to.be.true(); expect(mediaRequest.audioRequested).to.be.false(); expect(ok).to.be.true(); expect(captureHandle.handle).to.be.a('string'); expect(handleID).to.eq(captureHandle.handle); expect(message).to.be.null(); }); it('does not crash when providing only audio for a video request', async () => { const ses = session.fromPartition('' + Math.random()); let requestHandlerCalled = false; let callbackError: any; ses.setDisplayMediaRequestHandler((request, callback) => { requestHandlerCalled = true; try { callback({ audio: 'loopback' }); } catch (e) { callbackError = e; } }); const w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await w.loadURL(serverUrl); const { ok } = await w.webContents.executeJavaScript(` navigator.mediaDevices.getDisplayMedia({ video: true, }).then(x => ({ok: x instanceof MediaStream}), e => ({ok: false, message: e.message})) `, true); expect(requestHandlerCalled).to.be.true(); expect(ok).to.be.false(); expect(callbackError?.message).to.equal('Video was requested, but no video stream was provided'); }); it('does not crash when providing only an audio stream for an audio+video request', async () => { const ses = session.fromPartition('' + Math.random()); let requestHandlerCalled = false; let callbackError: any; ses.setDisplayMediaRequestHandler((request, callback) => { requestHandlerCalled = true; try { callback({ audio: 'loopback' }); } catch (e) { callbackError = e; } }); const w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await w.loadURL(serverUrl); const { ok } = await w.webContents.executeJavaScript(` navigator.mediaDevices.getDisplayMedia({ video: true, audio: true, }).then(x => ({ok: x instanceof MediaStream}), e => ({ok: false, message: e.message})) `, true); expect(requestHandlerCalled).to.be.true(); expect(ok).to.be.false(); expect(callbackError?.message).to.equal('Video was requested, but no video stream was provided'); }); it('does not crash when providing a non-loopback audio stream', async () => { const ses = session.fromPartition('' + Math.random()); let requestHandlerCalled = false; ses.setDisplayMediaRequestHandler((request, callback) => { requestHandlerCalled = true; callback({ video: w.webContents.mainFrame, audio: 'default' as any }); }); const w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await w.loadURL(serverUrl); const { ok } = await w.webContents.executeJavaScript(` navigator.mediaDevices.getDisplayMedia({ video: true, audio: true, }).then(x => ({ok: x instanceof MediaStream}), e => ({ok: false, message: e.message})) `, true); expect(requestHandlerCalled).to.be.true(); expect(ok).to.be.true(); }); it('does not crash when providing no streams', async () => { const ses = session.fromPartition('' + Math.random()); let requestHandlerCalled = false; let callbackError: any; ses.setDisplayMediaRequestHandler((request, callback) => { requestHandlerCalled = true; try { callback({}); } catch (e) { callbackError = e; } }); const w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await w.loadURL(serverUrl); const { ok } = await w.webContents.executeJavaScript(` navigator.mediaDevices.getDisplayMedia({ video: true, audio: true, }).then(x => ({ok: x instanceof MediaStream}), e => ({ok: false, message: e.message})) `, true); expect(requestHandlerCalled).to.be.true(); expect(ok).to.be.false(); expect(callbackError.message).to.equal('Video was requested, but no video stream was provided'); }); it('does not crash when using a bogus web-contents-media-stream:// ID', async () => { const ses = session.fromPartition('' + Math.random()); let requestHandlerCalled = false; ses.setDisplayMediaRequestHandler((request, callback) => { requestHandlerCalled = true; callback({ video: { id: 'web-contents-media-stream://9999:9999', name: 'whatever' } }); }); const w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await w.loadURL(serverUrl); const { ok } = await w.webContents.executeJavaScript(` navigator.mediaDevices.getDisplayMedia({ video: true, audio: true, }).then(x => ({ok: x instanceof MediaStream}), e => ({ok: false, message: e.message})) `, true); expect(requestHandlerCalled).to.be.true(); // This is a little surprising... apparently chrome will generate a stream // for this non-existent web contents? expect(ok).to.be.true(); }); it('is not called when calling getUserMedia', async () => { const ses = session.fromPartition('' + Math.random()); ses.setDisplayMediaRequestHandler(() => { throw new Error('bad'); }); const w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await w.loadURL(serverUrl); const { ok, message } = await w.webContents.executeJavaScript(` navigator.mediaDevices.getUserMedia({ video: true, audio: true, }).then(x => ({ok: x instanceof MediaStream}), e => ({ok: false, message: e.message})) `); expect(ok).to.be.true(message); }); it('works when calling getDisplayMedia with preferCurrentTab', async () => { const ses = session.fromPartition('' + Math.random()); let requestHandlerCalled = false; ses.setDisplayMediaRequestHandler((request, callback) => { requestHandlerCalled = true; callback({ video: w.webContents.mainFrame }); }); const w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await w.loadURL(serverUrl); const { ok, message } = await w.webContents.executeJavaScript(` navigator.mediaDevices.getDisplayMedia({ preferCurrentTab: true, video: true, audio: true, }).then(x => ({ok: x instanceof MediaStream}), e => ({ok: false, message: e.message})) `, true); expect(requestHandlerCalled).to.be.true(); expect(ok).to.be.true(message); }); ifit(!(process.platform === 'darwin' && process.arch === 'x64'))('can supply a screen response to preferCurrentTab', async () => { const ses = session.fromPartition('' + Math.random()); let requestHandlerCalled = false; ses.setDisplayMediaRequestHandler(async (request, callback) => { requestHandlerCalled = true; const sources = await desktopCapturer.getSources({ types: ['screen'] }); callback({ video: sources[0] }); }); const w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await w.loadURL(serverUrl); const { ok, message } = await w.webContents.executeJavaScript(` navigator.mediaDevices.getDisplayMedia({ preferCurrentTab: true, video: true, audio: true, }).then(x => ({ok: x instanceof MediaStream}), e => ({ok: false, message: e.message})) `, true); expect(requestHandlerCalled).to.be.true(); expect(ok).to.be.true(message); }); it('can supply a frame response', async () => { const ses = session.fromPartition('' + Math.random()); let requestHandlerCalled = false; ses.setDisplayMediaRequestHandler(async (request, callback) => { requestHandlerCalled = true; callback({ video: w.webContents.mainFrame }); }); const w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await w.loadURL(serverUrl); const { ok, message } = await w.webContents.executeJavaScript(` navigator.mediaDevices.getDisplayMedia({ video: true, }).then(x => ({ok: x instanceof MediaStream}), e => ({ok: false, message: e.message})) `, true); expect(requestHandlerCalled).to.be.true(); expect(ok).to.be.true(message); }); it('is not called when calling legacy getUserMedia', async () => { const ses = session.fromPartition('' + Math.random()); ses.setDisplayMediaRequestHandler(() => { throw new Error('bad'); }); const w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await w.loadURL(serverUrl); const { ok, message } = await w.webContents.executeJavaScript(` new Promise((resolve, reject) => navigator.getUserMedia({ video: true, audio: true, }, x => resolve({ok: x instanceof MediaStream}), e => reject({ok: false, message: e.message}))) `); expect(ok).to.be.true(message); }); it('is not called when calling legacy getUserMedia with desktop capture constraint', async () => { const ses = session.fromPartition('' + Math.random()); ses.setDisplayMediaRequestHandler(() => { throw new Error('bad'); }); const w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await w.loadURL(serverUrl); const { ok, message } = await w.webContents.executeJavaScript(` new Promise((resolve, reject) => navigator.getUserMedia({ video: { mandatory: { chromeMediaSource: 'desktop' } }, }, x => resolve({ok: x instanceof MediaStream}), e => reject({ok: false, message: e.message}))) `); expect(ok).to.be.true(message); }); it('works when calling getUserMedia without a media request handler', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(serverUrl); const { ok, message } = await w.webContents.executeJavaScript(` navigator.mediaDevices.getUserMedia({ video: true, audio: true, }).then(x => ({ok: x instanceof MediaStream}), e => ({ok: false, message: e.message})) `); expect(ok).to.be.true(message); }); it('works when calling legacy getUserMedia without a media request handler', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(serverUrl); const { ok, message } = await w.webContents.executeJavaScript(` new Promise((resolve, reject) => navigator.getUserMedia({ video: true, audio: true, }, x => resolve({ok: x instanceof MediaStream}), e => reject({ok: false, message: e.message}))) `); expect(ok).to.be.true(message); }); it('can remove a displayMediaRequestHandler', async () => { const ses = session.fromPartition('' + Math.random()); ses.setDisplayMediaRequestHandler(() => { throw new Error('bad'); }); ses.setDisplayMediaRequestHandler(null); const w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await w.loadURL(serverUrl); const { ok, message } = await w.webContents.executeJavaScript(` navigator.mediaDevices.getDisplayMedia({ video: true, }).then(x => ({ok: x instanceof MediaStream}), e => ({ok: false, message: e.message})) `, true); expect(ok).to.be.false(); expect(message).to.equal('Not supported'); }); });
closed
electron/electron
https://github.com/electron/electron
39,079
[Bug]: render process: assert.ok(false) throws TypeError instead of AssertionError
### 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 25.2.0 ### What operating system are you using? Other Linux ### Operating System Version Fedora 38 ### What arch are you using? x64 ### Last Known Working Electron version 11.1.0 ### Expected Behavior `AssertionError [ERR_ASSERTION]: false == true` ### Actual Behavior `TypeError: call.getFileName is not a function` ### Testcase Gist URL https://gist.github.com/ianhattendorf/82aeba581323093882168ddf69b6c6c2 ### Additional Information This broke a while back for both main + render processes (https://github.com/electron/electron/issues/24577) and was fixed in **11.0.0** (verified with fiddle). It later regressed, breaking for _only render processes_ in **11.1.1**. https://github.com/electron/electron/compare/v11.1.0...v11.1.1 @codebytere maybe you remember this from last time?
https://github.com/electron/electron/issues/39079
https://github.com/electron/electron/pull/39540
2481f94b4efe262c9ae2f5f16cd0845eeb6c4efd
ddc7e3ebb3c34357d4999174d692e18124cb7798
2023-07-12T22:59:47Z
c++
2023-08-23T09:38:47Z
patches/node/.patches
refactor_alter_child_process_fork_to_use_execute_script_with.patch feat_initialize_asar_support.patch expose_get_builtin_module_function.patch build_add_gn_build_files.patch fix_add_default_values_for_variables_in_common_gypi.patch fix_expose_tracing_agent_and_use_tracing_tracingcontroller_instead.patch pass_all_globals_through_require.patch build_modify_js2c_py_to_allow_injection_of_original-fs_and_custom_embedder_js.patch refactor_allow_embedder_overriding_of_internal_fs_calls.patch chore_allow_the_node_entrypoint_to_be_a_builtin_module.patch chore_add_context_to_context_aware_module_prevention.patch fix_handle_boringssl_and_openssl_incompatibilities.patch fix_crypto_tests_to_run_with_bssl.patch fix_account_for_debugger_agent_race_condition.patch fix_readbarrier_undefined_symbol_error_on_woa_arm64.patch fix_suppress_clang_-wdeprecated-declarations_in_libuv.patch fix_serdes_test.patch feat_add_knostartdebugsignalhandler_to_environment_to_prevent.patch feat_add_uv_loop_interrupt_on_io_change_option_to_uv_loop_configure.patch json_parse_errors_made_user-friendly.patch support_v8_sandboxed_pointers.patch build_ensure_v8_pointer_compression_sandbox_is_enabled_on_64bit.patch build_ensure_native_module_compilation_fails_if_not_using_a_new.patch fix_override_createjob_in_node_platform.patch v8_api_advance_api_deprecation.patch fix_parallel_test-v8-stats.patch fix_expose_the_built-in_electron_module_via_the_esm_loader.patch api_pass_oomdetails_to_oomerrorcallback.patch fix_expose_lookupandcompile_with_parameters.patch enable_crashpad_linux_node_processes.patch test_formally_mark_some_tests_as_flaky.patch fix_adapt_debugger_tests_for_upstream_v8_changes.patch chore_remove_--no-harmony-atomics_related_code.patch fix_account_for_createexternalizablestring_v8_global.patch fix_wunreachable-code_warning_in_ares_init_rand_engine.patch fix_-wshadow_warning.patch fix_do_not_resolve_electron_entrypoints.patch fix_adapt_generator_tostringtag_prototype_to_v8.patch fix_ftbfs_werror_wunreachable-code-break.patch fix_ftbfs_werror_wextra-semi.patch fix_isurl_implementation.patch ci_ensure_node_tests_set_electron_run_as_node.patch chore_update_fixtures_errors_force_colors_snapshot.patch
closed
electron/electron
https://github.com/electron/electron
39,079
[Bug]: render process: assert.ok(false) throws TypeError instead of AssertionError
### 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 25.2.0 ### What operating system are you using? Other Linux ### Operating System Version Fedora 38 ### What arch are you using? x64 ### Last Known Working Electron version 11.1.0 ### Expected Behavior `AssertionError [ERR_ASSERTION]: false == true` ### Actual Behavior `TypeError: call.getFileName is not a function` ### Testcase Gist URL https://gist.github.com/ianhattendorf/82aeba581323093882168ddf69b6c6c2 ### Additional Information This broke a while back for both main + render processes (https://github.com/electron/electron/issues/24577) and was fixed in **11.0.0** (verified with fiddle). It later regressed, breaking for _only render processes_ in **11.1.1**. https://github.com/electron/electron/compare/v11.1.0...v11.1.1 @codebytere maybe you remember this from last time?
https://github.com/electron/electron/issues/39079
https://github.com/electron/electron/pull/39540
2481f94b4efe262c9ae2f5f16cd0845eeb6c4efd
ddc7e3ebb3c34357d4999174d692e18124cb7798
2023-07-12T22:59:47Z
c++
2023-08-23T09:38:47Z
patches/node/fix_assert_module_in_the_renderer_process.patch
closed
electron/electron
https://github.com/electron/electron
39,079
[Bug]: render process: assert.ok(false) throws TypeError instead of AssertionError
### 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 25.2.0 ### What operating system are you using? Other Linux ### Operating System Version Fedora 38 ### What arch are you using? x64 ### Last Known Working Electron version 11.1.0 ### Expected Behavior `AssertionError [ERR_ASSERTION]: false == true` ### Actual Behavior `TypeError: call.getFileName is not a function` ### Testcase Gist URL https://gist.github.com/ianhattendorf/82aeba581323093882168ddf69b6c6c2 ### Additional Information This broke a while back for both main + render processes (https://github.com/electron/electron/issues/24577) and was fixed in **11.0.0** (verified with fiddle). It later regressed, breaking for _only render processes_ in **11.1.1**. https://github.com/electron/electron/compare/v11.1.0...v11.1.1 @codebytere maybe you remember this from last time?
https://github.com/electron/electron/issues/39079
https://github.com/electron/electron/pull/39540
2481f94b4efe262c9ae2f5f16cd0845eeb6c4efd
ddc7e3ebb3c34357d4999174d692e18124cb7798
2023-07-12T22:59:47Z
c++
2023-08-23T09:38:47Z
patches/node/.patches
refactor_alter_child_process_fork_to_use_execute_script_with.patch feat_initialize_asar_support.patch expose_get_builtin_module_function.patch build_add_gn_build_files.patch fix_add_default_values_for_variables_in_common_gypi.patch fix_expose_tracing_agent_and_use_tracing_tracingcontroller_instead.patch pass_all_globals_through_require.patch build_modify_js2c_py_to_allow_injection_of_original-fs_and_custom_embedder_js.patch refactor_allow_embedder_overriding_of_internal_fs_calls.patch chore_allow_the_node_entrypoint_to_be_a_builtin_module.patch chore_add_context_to_context_aware_module_prevention.patch fix_handle_boringssl_and_openssl_incompatibilities.patch fix_crypto_tests_to_run_with_bssl.patch fix_account_for_debugger_agent_race_condition.patch fix_readbarrier_undefined_symbol_error_on_woa_arm64.patch fix_suppress_clang_-wdeprecated-declarations_in_libuv.patch fix_serdes_test.patch feat_add_knostartdebugsignalhandler_to_environment_to_prevent.patch feat_add_uv_loop_interrupt_on_io_change_option_to_uv_loop_configure.patch json_parse_errors_made_user-friendly.patch support_v8_sandboxed_pointers.patch build_ensure_v8_pointer_compression_sandbox_is_enabled_on_64bit.patch build_ensure_native_module_compilation_fails_if_not_using_a_new.patch fix_override_createjob_in_node_platform.patch v8_api_advance_api_deprecation.patch fix_parallel_test-v8-stats.patch fix_expose_the_built-in_electron_module_via_the_esm_loader.patch api_pass_oomdetails_to_oomerrorcallback.patch fix_expose_lookupandcompile_with_parameters.patch enable_crashpad_linux_node_processes.patch test_formally_mark_some_tests_as_flaky.patch fix_adapt_debugger_tests_for_upstream_v8_changes.patch chore_remove_--no-harmony-atomics_related_code.patch fix_account_for_createexternalizablestring_v8_global.patch fix_wunreachable-code_warning_in_ares_init_rand_engine.patch fix_-wshadow_warning.patch fix_do_not_resolve_electron_entrypoints.patch fix_adapt_generator_tostringtag_prototype_to_v8.patch fix_ftbfs_werror_wunreachable-code-break.patch fix_ftbfs_werror_wextra-semi.patch fix_isurl_implementation.patch ci_ensure_node_tests_set_electron_run_as_node.patch chore_update_fixtures_errors_force_colors_snapshot.patch
closed
electron/electron
https://github.com/electron/electron
39,079
[Bug]: render process: assert.ok(false) throws TypeError instead of AssertionError
### 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 25.2.0 ### What operating system are you using? Other Linux ### Operating System Version Fedora 38 ### What arch are you using? x64 ### Last Known Working Electron version 11.1.0 ### Expected Behavior `AssertionError [ERR_ASSERTION]: false == true` ### Actual Behavior `TypeError: call.getFileName is not a function` ### Testcase Gist URL https://gist.github.com/ianhattendorf/82aeba581323093882168ddf69b6c6c2 ### Additional Information This broke a while back for both main + render processes (https://github.com/electron/electron/issues/24577) and was fixed in **11.0.0** (verified with fiddle). It later regressed, breaking for _only render processes_ in **11.1.1**. https://github.com/electron/electron/compare/v11.1.0...v11.1.1 @codebytere maybe you remember this from last time?
https://github.com/electron/electron/issues/39079
https://github.com/electron/electron/pull/39540
2481f94b4efe262c9ae2f5f16cd0845eeb6c4efd
ddc7e3ebb3c34357d4999174d692e18124cb7798
2023-07-12T22:59:47Z
c++
2023-08-23T09:38:47Z
patches/node/fix_assert_module_in_the_renderer_process.patch
closed
electron/electron
https://github.com/electron/electron
39,257
[Bug]: BrowserView y-coordinate is not respected on macOS Ventura (13.4.1 and 13.5)
### 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 25.3.2 ### What operating system are you using? macOS ### Operating System Version macOS Ventura (13.4.1 and 13.5) ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version 22.3.18 ### Expected Behavior This code should place a BrowserView on top of the default BrowserWindow, respecting the indicated x and y coordinates: ``` const bwin = new BrowserWindow({ width: 300, height: 500 }) bwin.loadURL('https://electronjs.org/') const bview = new BrowserView() bview.setBounds({ x: 0, y: 0, width: 300, height: 300 }) bwin.addBrowserView(bview) bview.webContents.loadURL('https://github.com/') ``` ### Actual Behavior While the previous code works perfectly on Windows 11, on macOS the y-coordinate of the BrowserView is shifted by the same amount of pixels as the height of BrowserWindow (causing the BrowserView to disappear). So on macOS to correctly position the BrowserView you need to set its y-coordinate to -BrowserViewHeight ``` const bwin = new BrowserWindow({ width: 300, height: 500 }) bwin.loadURL('https://electronjs.org/') const bview = new BrowserView() bview.setBounds({ x: 0, y: -500, // <------- !!! width: 300, height: 300 }) bwin.addBrowserView(bview) bview.webContents.loadURL('https://github.com/') ``` ### Testcase Gist URL https://gist.github.com/360b53fa59bce4a9e49549954bc23444 ### Additional Information _No response_
https://github.com/electron/electron/issues/39257
https://github.com/electron/electron/pull/39605
522bba3dc6b4893fdcf4d1a978fec0204b50d63b
a8999bc529390e7a9a2515bfa23445b34b10860a
2023-07-27T11:07:57Z
c++
2023-08-23T13:55:31Z
shell/browser/api/electron_api_base_window.cc
// Copyright (c) 2018 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_base_window.h" #include <algorithm> #include <string> #include <utility> #include <vector> #include "base/containers/contains.h" #include "base/task/single_thread_task_runner.h" #include "electron/buildflags/buildflags.h" #include "gin/dictionary.h" #include "shell/browser/api/electron_api_browser_view.h" #include "shell/browser/api/electron_api_menu.h" #include "shell/browser/api/electron_api_view.h" #include "shell/browser/api/electron_api_web_contents.h" #include "shell/browser/javascript_environment.h" #include "shell/common/color_util.h" #include "shell/common/gin_converters/callback_converter.h" #include "shell/common/gin_converters/file_path_converter.h" #include "shell/common/gin_converters/gfx_converter.h" #include "shell/common/gin_converters/image_converter.h" #include "shell/common/gin_converters/native_window_converter.h" #include "shell/common/gin_converters/optional_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/gin_helper/persistent_dictionary.h" #include "shell/common/node_includes.h" #include "shell/common/options_switches.h" #if defined(TOOLKIT_VIEWS) #include "shell/browser/native_window_views.h" #endif #if BUILDFLAG(IS_WIN) #include "shell/browser/ui/win/taskbar_host.h" #include "ui/base/win/shell.h" #endif #if BUILDFLAG(IS_WIN) namespace gin { template <> struct Converter<electron::TaskbarHost::ThumbarButton> { static bool FromV8(v8::Isolate* isolate, v8::Handle<v8::Value> val, electron::TaskbarHost::ThumbarButton* out) { gin::Dictionary dict(isolate); if (!gin::ConvertFromV8(isolate, val, &dict)) return false; dict.Get("click", &(out->clicked_callback)); dict.Get("tooltip", &(out->tooltip)); dict.Get("flags", &out->flags); return dict.Get("icon", &(out->icon)); } }; } // namespace gin #endif namespace electron::api { namespace { // Converts binary data to Buffer. v8::Local<v8::Value> ToBuffer(v8::Isolate* isolate, void* val, int size) { auto buffer = node::Buffer::Copy(isolate, static_cast<char*>(val), size); if (buffer.IsEmpty()) return v8::Null(isolate); else return buffer.ToLocalChecked(); } } // namespace BaseWindow::BaseWindow(v8::Isolate* isolate, const gin_helper::Dictionary& options) { // The parent window. gin::Handle<BaseWindow> parent; if (options.Get("parent", &parent) && !parent.IsEmpty()) parent_window_.Reset(isolate, parent.ToV8()); // Offscreen windows are always created frameless. gin_helper::Dictionary web_preferences; bool offscreen; if (options.Get(options::kWebPreferences, &web_preferences) && web_preferences.Get(options::kOffscreen, &offscreen) && offscreen) { const_cast<gin_helper::Dictionary&>(options).Set(options::kFrame, false); } // Creates NativeWindow. window_.reset(NativeWindow::Create( options, parent.IsEmpty() ? nullptr : parent->window_.get())); window_->AddObserver(this); #if defined(TOOLKIT_VIEWS) v8::Local<v8::Value> icon; if (options.Get(options::kIcon, &icon)) { SetIconImpl(isolate, icon, NativeImage::OnConvertError::kWarn); } #endif } BaseWindow::BaseWindow(gin_helper::Arguments* args, const gin_helper::Dictionary& options) : BaseWindow(args->isolate(), options) { InitWithArgs(args); // Init window after everything has been setup. window()->InitFromOptions(options); } BaseWindow::~BaseWindow() { CloseImmediately(); // Destroy the native window in next tick because the native code might be // iterating all windows. base::SingleThreadTaskRunner::GetCurrentDefault()->DeleteSoon( FROM_HERE, window_.release()); // Remove global reference so the JS object can be garbage collected. self_ref_.Reset(); } void BaseWindow::InitWith(v8::Isolate* isolate, v8::Local<v8::Object> wrapper) { AttachAsUserData(window_.get()); gin_helper::TrackableObject<BaseWindow>::InitWith(isolate, wrapper); // We can only append this window to parent window's child windows after this // window's JS wrapper gets initialized. if (!parent_window_.IsEmpty()) { gin::Handle<BaseWindow> parent; gin::ConvertFromV8(isolate, GetParentWindow(), &parent); DCHECK(!parent.IsEmpty()); parent->child_windows_.Set(isolate, weak_map_id(), wrapper); } // Reference this object in case it got garbage collected. self_ref_.Reset(isolate, wrapper); } void BaseWindow::WillCloseWindow(bool* prevent_default) { if (Emit("close")) { *prevent_default = true; } } void BaseWindow::OnWindowClosed() { // Invalidate weak ptrs before the Javascript object is destroyed, // there might be some delayed emit events which shouldn't be // triggered after this. weak_factory_.InvalidateWeakPtrs(); RemoveFromWeakMap(); window_->RemoveObserver(this); // We can not call Destroy here because we need to call Emit first, but we // also do not want any method to be used, so just mark as destroyed here. MarkDestroyed(); Emit("closed"); RemoveFromParentChildWindows(); BaseWindow::ResetBrowserViews(); // Destroy the native class when window is closed. base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask( FROM_HERE, GetDestroyClosure()); } void BaseWindow::OnWindowEndSession() { Emit("session-end"); } void BaseWindow::OnWindowBlur() { EmitEventSoon("blur"); } void BaseWindow::OnWindowFocus() { EmitEventSoon("focus"); } void BaseWindow::OnWindowShow() { Emit("show"); } void BaseWindow::OnWindowHide() { Emit("hide"); } void BaseWindow::OnWindowMaximize() { Emit("maximize"); } void BaseWindow::OnWindowUnmaximize() { Emit("unmaximize"); } void BaseWindow::OnWindowMinimize() { Emit("minimize"); } void BaseWindow::OnWindowRestore() { Emit("restore"); } void BaseWindow::OnWindowWillResize(const gfx::Rect& new_bounds, const gfx::ResizeEdge& edge, bool* prevent_default) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); auto info = gin::Dictionary::CreateEmpty(isolate); info.Set("edge", edge); if (Emit("will-resize", new_bounds, info)) { *prevent_default = true; } } void BaseWindow::OnWindowResize() { Emit("resize"); } void BaseWindow::OnWindowResized() { Emit("resized"); } void BaseWindow::OnWindowWillMove(const gfx::Rect& new_bounds, bool* prevent_default) { if (Emit("will-move", new_bounds)) { *prevent_default = true; } } void BaseWindow::OnWindowMove() { Emit("move"); } void BaseWindow::OnWindowMoved() { Emit("moved"); } void BaseWindow::OnWindowEnterFullScreen() { Emit("enter-full-screen"); } void BaseWindow::OnWindowLeaveFullScreen() { Emit("leave-full-screen"); } void BaseWindow::OnWindowSwipe(const std::string& direction) { Emit("swipe", direction); } void BaseWindow::OnWindowRotateGesture(float rotation) { Emit("rotate-gesture", rotation); } void BaseWindow::OnWindowSheetBegin() { Emit("sheet-begin"); } void BaseWindow::OnWindowSheetEnd() { Emit("sheet-end"); } void BaseWindow::OnWindowEnterHtmlFullScreen() { Emit("enter-html-full-screen"); } void BaseWindow::OnWindowLeaveHtmlFullScreen() { Emit("leave-html-full-screen"); } void BaseWindow::OnWindowAlwaysOnTopChanged() { Emit("always-on-top-changed", IsAlwaysOnTop()); } void BaseWindow::OnExecuteAppCommand(const std::string& command_name) { Emit("app-command", command_name); } void BaseWindow::OnTouchBarItemResult(const std::string& item_id, const base::Value::Dict& details) { Emit("-touch-bar-interaction", item_id, details); } void BaseWindow::OnNewWindowForTab() { Emit("new-window-for-tab"); } void BaseWindow::OnSystemContextMenu(int x, int y, bool* prevent_default) { if (Emit("system-context-menu", gfx::Point(x, y))) { *prevent_default = true; } } #if BUILDFLAG(IS_WIN) void BaseWindow::OnWindowMessage(UINT message, WPARAM w_param, LPARAM l_param) { if (IsWindowMessageHooked(message)) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); messages_callback_map_[message].Run( ToBuffer(isolate, static_cast<void*>(&w_param), sizeof(WPARAM)), ToBuffer(isolate, static_cast<void*>(&l_param), sizeof(LPARAM))); } } #endif void BaseWindow::SetContentView(gin::Handle<View> view) { ResetBrowserViews(); content_view_.Reset(isolate(), view.ToV8()); window_->SetContentView(view->view()); } void BaseWindow::CloseImmediately() { if (!window_->IsClosed()) window_->CloseImmediately(); } void BaseWindow::Close() { window_->Close(); } void BaseWindow::Focus() { window_->Focus(true); } void BaseWindow::Blur() { window_->Focus(false); } bool BaseWindow::IsFocused() { return window_->IsFocused(); } void BaseWindow::Show() { window_->Show(); } void BaseWindow::ShowInactive() { // This method doesn't make sense for modal window. if (IsModal()) return; window_->ShowInactive(); } void BaseWindow::Hide() { window_->Hide(); } bool BaseWindow::IsVisible() { return window_->IsVisible(); } bool BaseWindow::IsEnabled() { return window_->IsEnabled(); } void BaseWindow::SetEnabled(bool enable) { window_->SetEnabled(enable); } void BaseWindow::Maximize() { window_->Maximize(); } void BaseWindow::Unmaximize() { window_->Unmaximize(); } bool BaseWindow::IsMaximized() { return window_->IsMaximized(); } void BaseWindow::Minimize() { window_->Minimize(); } void BaseWindow::Restore() { window_->Restore(); } bool BaseWindow::IsMinimized() { return window_->IsMinimized(); } void BaseWindow::SetFullScreen(bool fullscreen) { window_->SetFullScreen(fullscreen); } bool BaseWindow::IsFullscreen() { return window_->IsFullscreen(); } void BaseWindow::SetBounds(const gfx::Rect& bounds, gin_helper::Arguments* args) { bool animate = false; args->GetNext(&animate); window_->SetBounds(bounds, animate); } gfx::Rect BaseWindow::GetBounds() { return window_->GetBounds(); } bool BaseWindow::IsNormal() { return window_->IsNormal(); } gfx::Rect BaseWindow::GetNormalBounds() { return window_->GetNormalBounds(); } void BaseWindow::SetContentBounds(const gfx::Rect& bounds, gin_helper::Arguments* args) { bool animate = false; args->GetNext(&animate); window_->SetContentBounds(bounds, animate); } gfx::Rect BaseWindow::GetContentBounds() { return window_->GetContentBounds(); } void BaseWindow::SetSize(int width, int height, gin_helper::Arguments* args) { bool animate = false; gfx::Size size = window_->GetMinimumSize(); size.SetToMax(gfx::Size(width, height)); args->GetNext(&animate); window_->SetSize(size, animate); } std::vector<int> BaseWindow::GetSize() { std::vector<int> result(2); gfx::Size size = window_->GetSize(); result[0] = size.width(); result[1] = size.height(); return result; } void BaseWindow::SetContentSize(int width, int height, gin_helper::Arguments* args) { bool animate = false; args->GetNext(&animate); window_->SetContentSize(gfx::Size(width, height), animate); } std::vector<int> BaseWindow::GetContentSize() { std::vector<int> result(2); gfx::Size size = window_->GetContentSize(); result[0] = size.width(); result[1] = size.height(); return result; } void BaseWindow::SetMinimumSize(int width, int height) { window_->SetMinimumSize(gfx::Size(width, height)); } std::vector<int> BaseWindow::GetMinimumSize() { std::vector<int> result(2); gfx::Size size = window_->GetMinimumSize(); result[0] = size.width(); result[1] = size.height(); return result; } void BaseWindow::SetMaximumSize(int width, int height) { window_->SetMaximumSize(gfx::Size(width, height)); } std::vector<int> BaseWindow::GetMaximumSize() { std::vector<int> result(2); gfx::Size size = window_->GetMaximumSize(); result[0] = size.width(); result[1] = size.height(); return result; } void BaseWindow::SetSheetOffset(double offsetY, gin_helper::Arguments* args) { double offsetX = 0.0; args->GetNext(&offsetX); window_->SetSheetOffset(offsetX, offsetY); } void BaseWindow::SetResizable(bool resizable) { window_->SetResizable(resizable); } bool BaseWindow::IsResizable() { return window_->IsResizable(); } void BaseWindow::SetMovable(bool movable) { window_->SetMovable(movable); } bool BaseWindow::IsMovable() { return window_->IsMovable(); } void BaseWindow::SetMinimizable(bool minimizable) { window_->SetMinimizable(minimizable); } bool BaseWindow::IsMinimizable() { return window_->IsMinimizable(); } void BaseWindow::SetMaximizable(bool maximizable) { window_->SetMaximizable(maximizable); } bool BaseWindow::IsMaximizable() { return window_->IsMaximizable(); } void BaseWindow::SetFullScreenable(bool fullscreenable) { window_->SetFullScreenable(fullscreenable); } bool BaseWindow::IsFullScreenable() { return window_->IsFullScreenable(); } void BaseWindow::SetClosable(bool closable) { window_->SetClosable(closable); } bool BaseWindow::IsClosable() { return window_->IsClosable(); } void BaseWindow::SetAlwaysOnTop(bool top, gin_helper::Arguments* args) { std::string level = "floating"; int relative_level = 0; args->GetNext(&level); args->GetNext(&relative_level); ui::ZOrderLevel z_order = top ? ui::ZOrderLevel::kFloatingWindow : ui::ZOrderLevel::kNormal; window_->SetAlwaysOnTop(z_order, level, relative_level); } bool BaseWindow::IsAlwaysOnTop() { return window_->GetZOrderLevel() != ui::ZOrderLevel::kNormal; } void BaseWindow::Center() { window_->Center(); } void BaseWindow::SetPosition(int x, int y, gin_helper::Arguments* args) { bool animate = false; args->GetNext(&animate); window_->SetPosition(gfx::Point(x, y), animate); } std::vector<int> BaseWindow::GetPosition() { std::vector<int> result(2); gfx::Point pos = window_->GetPosition(); result[0] = pos.x(); result[1] = pos.y(); return result; } void BaseWindow::MoveAbove(const std::string& sourceId, gin_helper::Arguments* args) { if (!window_->MoveAbove(sourceId)) args->ThrowError("Invalid media source id"); } void BaseWindow::MoveTop() { window_->MoveTop(); } void BaseWindow::SetTitle(const std::string& title) { window_->SetTitle(title); } std::string BaseWindow::GetTitle() { return window_->GetTitle(); } void BaseWindow::SetAccessibleTitle(const std::string& title) { window_->SetAccessibleTitle(title); } std::string BaseWindow::GetAccessibleTitle() { return window_->GetAccessibleTitle(); } void BaseWindow::FlashFrame(bool flash) { window_->FlashFrame(flash); } void BaseWindow::SetSkipTaskbar(bool skip) { window_->SetSkipTaskbar(skip); } void BaseWindow::SetExcludedFromShownWindowsMenu(bool excluded) { window_->SetExcludedFromShownWindowsMenu(excluded); } bool BaseWindow::IsExcludedFromShownWindowsMenu() { return window_->IsExcludedFromShownWindowsMenu(); } void BaseWindow::SetSimpleFullScreen(bool simple_fullscreen) { window_->SetSimpleFullScreen(simple_fullscreen); } bool BaseWindow::IsSimpleFullScreen() { return window_->IsSimpleFullScreen(); } void BaseWindow::SetKiosk(bool kiosk) { window_->SetKiosk(kiosk); } bool BaseWindow::IsKiosk() { return window_->IsKiosk(); } bool BaseWindow::IsTabletMode() const { return window_->IsTabletMode(); } void BaseWindow::SetBackgroundColor(const std::string& color_name) { SkColor color = ParseCSSColor(color_name); window_->SetBackgroundColor(color); } std::string BaseWindow::GetBackgroundColor(gin_helper::Arguments* args) { return ToRGBHex(window_->GetBackgroundColor()); } void BaseWindow::InvalidateShadow() { window_->InvalidateShadow(); } void BaseWindow::SetHasShadow(bool has_shadow) { window_->SetHasShadow(has_shadow); } bool BaseWindow::HasShadow() { return window_->HasShadow(); } void BaseWindow::SetOpacity(const double opacity) { window_->SetOpacity(opacity); } double BaseWindow::GetOpacity() { return window_->GetOpacity(); } void BaseWindow::SetShape(const std::vector<gfx::Rect>& rects) { window_->widget()->SetShape(std::make_unique<std::vector<gfx::Rect>>(rects)); } void BaseWindow::SetRepresentedFilename(const std::string& filename) { window_->SetRepresentedFilename(filename); } std::string BaseWindow::GetRepresentedFilename() { return window_->GetRepresentedFilename(); } void BaseWindow::SetDocumentEdited(bool edited) { window_->SetDocumentEdited(edited); } bool BaseWindow::IsDocumentEdited() { return window_->IsDocumentEdited(); } void BaseWindow::SetIgnoreMouseEvents(bool ignore, gin_helper::Arguments* args) { gin_helper::Dictionary options; bool forward = false; args->GetNext(&options) && options.Get("forward", &forward); return window_->SetIgnoreMouseEvents(ignore, forward); } void BaseWindow::SetContentProtection(bool enable) { return window_->SetContentProtection(enable); } void BaseWindow::SetFocusable(bool focusable) { return window_->SetFocusable(focusable); } bool BaseWindow::IsFocusable() { return window_->IsFocusable(); } void BaseWindow::SetMenu(v8::Isolate* isolate, v8::Local<v8::Value> value) { auto context = isolate->GetCurrentContext(); gin::Handle<Menu> menu; v8::Local<v8::Object> object; if (value->IsObject() && value->ToObject(context).ToLocal(&object) && gin::ConvertFromV8(isolate, value, &menu) && !menu.IsEmpty()) { // We only want to update the menu if the menu has a non-zero item count, // or we risk crashes. if (menu->model()->GetItemCount() == 0) { RemoveMenu(); } else { window_->SetMenu(menu->model()); } menu_.Reset(isolate, menu.ToV8()); } else if (value->IsNull()) { RemoveMenu(); } else { isolate->ThrowException( v8::Exception::TypeError(gin::StringToV8(isolate, "Invalid Menu"))); } } void BaseWindow::RemoveMenu() { menu_.Reset(); window_->SetMenu(nullptr); } void BaseWindow::SetParentWindow(v8::Local<v8::Value> value, gin_helper::Arguments* args) { if (IsModal()) { args->ThrowError("Can not be called for modal window"); return; } gin::Handle<BaseWindow> parent; if (value->IsNull() || value->IsUndefined()) { RemoveFromParentChildWindows(); parent_window_.Reset(); window_->SetParentWindow(nullptr); } else if (gin::ConvertFromV8(isolate(), value, &parent)) { RemoveFromParentChildWindows(); parent_window_.Reset(isolate(), value); window_->SetParentWindow(parent->window_.get()); parent->child_windows_.Set(isolate(), weak_map_id(), GetWrapper()); } else { args->ThrowError("Must pass BaseWindow instance or null"); } } void BaseWindow::SetBrowserView( absl::optional<gin::Handle<BrowserView>> browser_view) { ResetBrowserViews(); if (browser_view) AddBrowserView(*browser_view); } void BaseWindow::AddBrowserView(gin::Handle<BrowserView> browser_view) { if (!base::Contains(browser_views_, browser_view.ToV8())) { // If we're reparenting a BrowserView, ensure that it's detached from // its previous owner window. BaseWindow* owner_window = browser_view->owner_window(); if (owner_window) { // iter == browser_views_.end() should imply owner_window != this. DCHECK_NE(owner_window, this); owner_window->RemoveBrowserView(browser_view); browser_view->SetOwnerWindow(nullptr); } window_->AddBrowserView(browser_view->view()); window_->AddDraggableRegionProvider(browser_view.get()); browser_view->SetOwnerWindow(this); browser_views_.emplace_back().Reset(isolate(), browser_view.ToV8()); } } void BaseWindow::RemoveBrowserView(gin::Handle<BrowserView> browser_view) { auto iter = std::find(browser_views_.begin(), browser_views_.end(), browser_view.ToV8()); if (iter != browser_views_.end()) { window_->RemoveDraggableRegionProvider(browser_view.get()); window_->RemoveBrowserView(browser_view->view()); browser_view->SetOwnerWindow(nullptr); iter->Reset(); browser_views_.erase(iter); } } void BaseWindow::SetTopBrowserView(gin::Handle<BrowserView> browser_view, gin_helper::Arguments* args) { BaseWindow* owner_window = browser_view->owner_window(); auto iter = std::find(browser_views_.begin(), browser_views_.end(), browser_view.ToV8()); if (iter == browser_views_.end() || (owner_window && owner_window != this)) { args->ThrowError("Given BrowserView is not attached to the window"); return; } browser_views_.erase(iter); browser_views_.emplace_back().Reset(isolate(), browser_view.ToV8()); window_->SetTopBrowserView(browser_view->view()); } std::string BaseWindow::GetMediaSourceId() const { return window_->GetDesktopMediaID().ToString(); } v8::Local<v8::Value> BaseWindow::GetNativeWindowHandle() { // TODO(MarshallOfSound): Replace once // https://chromium-review.googlesource.com/c/chromium/src/+/1253094/ has // landed NativeWindowHandle handle = window_->GetNativeWindowHandle(); return ToBuffer(isolate(), &handle, sizeof(handle)); } void BaseWindow::SetProgressBar(double progress, gin_helper::Arguments* args) { gin_helper::Dictionary options; std::string mode; args->GetNext(&options) && options.Get("mode", &mode); NativeWindow::ProgressState state = NativeWindow::ProgressState::kNormal; if (mode == "error") state = NativeWindow::ProgressState::kError; else if (mode == "paused") state = NativeWindow::ProgressState::kPaused; else if (mode == "indeterminate") state = NativeWindow::ProgressState::kIndeterminate; else if (mode == "none") state = NativeWindow::ProgressState::kNone; window_->SetProgressBar(progress, state); } void BaseWindow::SetOverlayIcon(const gfx::Image& overlay, const std::string& description) { window_->SetOverlayIcon(overlay, description); } void BaseWindow::SetVisibleOnAllWorkspaces(bool visible, gin_helper::Arguments* args) { gin_helper::Dictionary options; bool visibleOnFullScreen = false; bool skipTransformProcessType = false; if (args->GetNext(&options)) { options.Get("visibleOnFullScreen", &visibleOnFullScreen); options.Get("skipTransformProcessType", &skipTransformProcessType); } return window_->SetVisibleOnAllWorkspaces(visible, visibleOnFullScreen, skipTransformProcessType); } bool BaseWindow::IsVisibleOnAllWorkspaces() { return window_->IsVisibleOnAllWorkspaces(); } void BaseWindow::SetAutoHideCursor(bool auto_hide) { window_->SetAutoHideCursor(auto_hide); } void BaseWindow::SetVibrancy(v8::Isolate* isolate, v8::Local<v8::Value> value) { std::string type = gin::V8ToString(isolate, value); window_->SetVibrancy(type); } void BaseWindow::SetBackgroundMaterial(const std::string& material_type) { window_->SetBackgroundMaterial(material_type); } #if BUILDFLAG(IS_MAC) std::string BaseWindow::GetAlwaysOnTopLevel() { return window_->GetAlwaysOnTopLevel(); } void BaseWindow::SetWindowButtonVisibility(bool visible) { window_->SetWindowButtonVisibility(visible); } bool BaseWindow::GetWindowButtonVisibility() const { return window_->GetWindowButtonVisibility(); } void BaseWindow::SetWindowButtonPosition(absl::optional<gfx::Point> position) { window_->SetWindowButtonPosition(std::move(position)); } absl::optional<gfx::Point> BaseWindow::GetWindowButtonPosition() const { return window_->GetWindowButtonPosition(); } #endif #if BUILDFLAG(IS_MAC) bool BaseWindow::IsHiddenInMissionControl() { return window_->IsHiddenInMissionControl(); } void BaseWindow::SetHiddenInMissionControl(bool hidden) { window_->SetHiddenInMissionControl(hidden); } #endif void BaseWindow::SetTouchBar( std::vector<gin_helper::PersistentDictionary> items) { window_->SetTouchBar(std::move(items)); } void BaseWindow::RefreshTouchBarItem(const std::string& item_id) { window_->RefreshTouchBarItem(item_id); } void BaseWindow::SetEscapeTouchBarItem(gin_helper::PersistentDictionary item) { window_->SetEscapeTouchBarItem(std::move(item)); } void BaseWindow::SelectPreviousTab() { window_->SelectPreviousTab(); } void BaseWindow::SelectNextTab() { window_->SelectNextTab(); } void BaseWindow::ShowAllTabs() { window_->ShowAllTabs(); } void BaseWindow::MergeAllWindows() { window_->MergeAllWindows(); } void BaseWindow::MoveTabToNewWindow() { window_->MoveTabToNewWindow(); } void BaseWindow::ToggleTabBar() { window_->ToggleTabBar(); } void BaseWindow::AddTabbedWindow(NativeWindow* window, gin_helper::Arguments* args) { if (!window_->AddTabbedWindow(window)) args->ThrowError("AddTabbedWindow cannot be called by a window on itself."); } void BaseWindow::SetAutoHideMenuBar(bool auto_hide) { window_->SetAutoHideMenuBar(auto_hide); } bool BaseWindow::IsMenuBarAutoHide() { return window_->IsMenuBarAutoHide(); } void BaseWindow::SetMenuBarVisibility(bool visible) { window_->SetMenuBarVisibility(visible); } bool BaseWindow::IsMenuBarVisible() { return window_->IsMenuBarVisible(); } void BaseWindow::SetAspectRatio(double aspect_ratio, gin_helper::Arguments* args) { gfx::Size extra_size; args->GetNext(&extra_size); window_->SetAspectRatio(aspect_ratio, extra_size); } void BaseWindow::PreviewFile(const std::string& path, gin_helper::Arguments* args) { std::string display_name; if (!args->GetNext(&display_name)) display_name = path; window_->PreviewFile(path, display_name); } void BaseWindow::CloseFilePreview() { window_->CloseFilePreview(); } void BaseWindow::SetGTKDarkThemeEnabled(bool use_dark_theme) { window_->SetGTKDarkThemeEnabled(use_dark_theme); } v8::Local<v8::Value> BaseWindow::GetContentView() const { if (content_view_.IsEmpty()) return v8::Null(isolate()); else return v8::Local<v8::Value>::New(isolate(), content_view_); } v8::Local<v8::Value> BaseWindow::GetParentWindow() const { if (parent_window_.IsEmpty()) return v8::Null(isolate()); else return v8::Local<v8::Value>::New(isolate(), parent_window_); } std::vector<v8::Local<v8::Object>> BaseWindow::GetChildWindows() const { return child_windows_.Values(isolate()); } v8::Local<v8::Value> BaseWindow::GetBrowserView( gin_helper::Arguments* args) const { if (browser_views_.empty()) { return v8::Null(isolate()); } else if (browser_views_.size() == 1) { auto first_view = browser_views_.begin(); return v8::Local<v8::Value>::New(isolate(), *first_view); } else { args->ThrowError( "BrowserWindow have multiple BrowserViews, " "Use getBrowserViews() instead"); return v8::Null(isolate()); } } std::vector<v8::Local<v8::Value>> BaseWindow::GetBrowserViews() const { std::vector<v8::Local<v8::Value>> ret; for (auto const& browser_view : browser_views_) { ret.push_back(v8::Local<v8::Value>::New(isolate(), browser_view)); } return ret; } bool BaseWindow::IsModal() const { return window_->is_modal(); } bool BaseWindow::SetThumbarButtons(gin_helper::Arguments* args) { #if BUILDFLAG(IS_WIN) std::vector<TaskbarHost::ThumbarButton> buttons; if (!args->GetNext(&buttons)) { args->ThrowError(); return false; } auto* window = static_cast<NativeWindowViews*>(window_.get()); return window->taskbar_host().SetThumbarButtons( window_->GetAcceleratedWidget(), buttons); #else return false; #endif } #if defined(TOOLKIT_VIEWS) void BaseWindow::SetIcon(v8::Isolate* isolate, v8::Local<v8::Value> icon) { SetIconImpl(isolate, icon, NativeImage::OnConvertError::kThrow); } void BaseWindow::SetIconImpl(v8::Isolate* isolate, v8::Local<v8::Value> icon, NativeImage::OnConvertError on_error) { NativeImage* native_image = nullptr; if (!NativeImage::TryConvertNativeImage(isolate, icon, &native_image, on_error)) return; #if BUILDFLAG(IS_WIN) static_cast<NativeWindowViews*>(window_.get()) ->SetIcon(native_image->GetHICON(GetSystemMetrics(SM_CXSMICON)), native_image->GetHICON(GetSystemMetrics(SM_CXICON))); #elif BUILDFLAG(IS_LINUX) static_cast<NativeWindowViews*>(window_.get()) ->SetIcon(native_image->image().AsImageSkia()); #endif } #endif #if BUILDFLAG(IS_WIN) bool BaseWindow::HookWindowMessage(UINT message, const MessageCallback& callback) { messages_callback_map_[message] = callback; return true; } void BaseWindow::UnhookWindowMessage(UINT message) { messages_callback_map_.erase(message); } bool BaseWindow::IsWindowMessageHooked(UINT message) { return base::Contains(messages_callback_map_, message); } void BaseWindow::UnhookAllWindowMessages() { messages_callback_map_.clear(); } bool BaseWindow::SetThumbnailClip(const gfx::Rect& region) { auto* window = static_cast<NativeWindowViews*>(window_.get()); return window->taskbar_host().SetThumbnailClip( window_->GetAcceleratedWidget(), region); } bool BaseWindow::SetThumbnailToolTip(const std::string& tooltip) { auto* window = static_cast<NativeWindowViews*>(window_.get()); return window->taskbar_host().SetThumbnailToolTip( window_->GetAcceleratedWidget(), tooltip); } void BaseWindow::SetAppDetails(const gin_helper::Dictionary& options) { std::wstring app_id; base::FilePath app_icon_path; int app_icon_index = 0; std::wstring relaunch_command; std::wstring relaunch_display_name; options.Get("appId", &app_id); options.Get("appIconPath", &app_icon_path); options.Get("appIconIndex", &app_icon_index); options.Get("relaunchCommand", &relaunch_command); options.Get("relaunchDisplayName", &relaunch_display_name); ui::win::SetAppDetailsForWindow(app_id, app_icon_path, app_icon_index, relaunch_command, relaunch_display_name, window_->GetAcceleratedWidget()); } #endif int32_t BaseWindow::GetID() const { return weak_map_id(); } void BaseWindow::ResetBrowserViews() { v8::HandleScope scope(isolate()); for (auto& item : browser_views_) { gin::Handle<BrowserView> browser_view; if (gin::ConvertFromV8(isolate(), v8::Local<v8::Value>::New(isolate(), item), &browser_view) && !browser_view.IsEmpty()) { // There's a chance that the BrowserView may have been reparented - only // reset if the owner window is *this* window. BaseWindow* owner_window = browser_view->owner_window(); DCHECK_EQ(owner_window, this); browser_view->SetOwnerWindow(nullptr); window_->RemoveBrowserView(browser_view->view()); window_->RemoveDraggableRegionProvider(browser_view.get()); browser_view->SetOwnerWindow(nullptr); } item.Reset(); } browser_views_.clear(); } void BaseWindow::RemoveFromParentChildWindows() { if (parent_window_.IsEmpty()) return; gin::Handle<BaseWindow> parent; if (!gin::ConvertFromV8(isolate(), GetParentWindow(), &parent) || parent.IsEmpty()) { return; } parent->child_windows_.Remove(weak_map_id()); } // static gin_helper::WrappableBase* BaseWindow::New(gin_helper::Arguments* args) { gin_helper::Dictionary options = gin::Dictionary::CreateEmpty(args->isolate()); args->GetNext(&options); return new BaseWindow(args, options); } // static void BaseWindow::BuildPrototype(v8::Isolate* isolate, v8::Local<v8::FunctionTemplate> prototype) { prototype->SetClassName(gin::StringToV8(isolate, "BaseWindow")); gin_helper::Destroyable::MakeDestroyable(isolate, prototype); gin_helper::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate()) .SetMethod("setContentView", &BaseWindow::SetContentView) .SetMethod("close", &BaseWindow::Close) .SetMethod("focus", &BaseWindow::Focus) .SetMethod("blur", &BaseWindow::Blur) .SetMethod("isFocused", &BaseWindow::IsFocused) .SetMethod("show", &BaseWindow::Show) .SetMethod("showInactive", &BaseWindow::ShowInactive) .SetMethod("hide", &BaseWindow::Hide) .SetMethod("isVisible", &BaseWindow::IsVisible) .SetMethod("isEnabled", &BaseWindow::IsEnabled) .SetMethod("setEnabled", &BaseWindow::SetEnabled) .SetMethod("maximize", &BaseWindow::Maximize) .SetMethod("unmaximize", &BaseWindow::Unmaximize) .SetMethod("isMaximized", &BaseWindow::IsMaximized) .SetMethod("minimize", &BaseWindow::Minimize) .SetMethod("restore", &BaseWindow::Restore) .SetMethod("isMinimized", &BaseWindow::IsMinimized) .SetMethod("setFullScreen", &BaseWindow::SetFullScreen) .SetMethod("isFullScreen", &BaseWindow::IsFullscreen) .SetMethod("setBounds", &BaseWindow::SetBounds) .SetMethod("getBounds", &BaseWindow::GetBounds) .SetMethod("isNormal", &BaseWindow::IsNormal) .SetMethod("getNormalBounds", &BaseWindow::GetNormalBounds) .SetMethod("setSize", &BaseWindow::SetSize) .SetMethod("getSize", &BaseWindow::GetSize) .SetMethod("setContentBounds", &BaseWindow::SetContentBounds) .SetMethod("getContentBounds", &BaseWindow::GetContentBounds) .SetMethod("setContentSize", &BaseWindow::SetContentSize) .SetMethod("getContentSize", &BaseWindow::GetContentSize) .SetMethod("setMinimumSize", &BaseWindow::SetMinimumSize) .SetMethod("getMinimumSize", &BaseWindow::GetMinimumSize) .SetMethod("setMaximumSize", &BaseWindow::SetMaximumSize) .SetMethod("getMaximumSize", &BaseWindow::GetMaximumSize) .SetMethod("setSheetOffset", &BaseWindow::SetSheetOffset) .SetMethod("moveAbove", &BaseWindow::MoveAbove) .SetMethod("moveTop", &BaseWindow::MoveTop) .SetMethod("setResizable", &BaseWindow::SetResizable) .SetMethod("isResizable", &BaseWindow::IsResizable) .SetMethod("setMovable", &BaseWindow::SetMovable) .SetMethod("isMovable", &BaseWindow::IsMovable) .SetMethod("setMinimizable", &BaseWindow::SetMinimizable) .SetMethod("isMinimizable", &BaseWindow::IsMinimizable) .SetMethod("setMaximizable", &BaseWindow::SetMaximizable) .SetMethod("isMaximizable", &BaseWindow::IsMaximizable) .SetMethod("setFullScreenable", &BaseWindow::SetFullScreenable) .SetMethod("isFullScreenable", &BaseWindow::IsFullScreenable) .SetMethod("setClosable", &BaseWindow::SetClosable) .SetMethod("isClosable", &BaseWindow::IsClosable) .SetMethod("setAlwaysOnTop", &BaseWindow::SetAlwaysOnTop) .SetMethod("isAlwaysOnTop", &BaseWindow::IsAlwaysOnTop) .SetMethod("center", &BaseWindow::Center) .SetMethod("setPosition", &BaseWindow::SetPosition) .SetMethod("getPosition", &BaseWindow::GetPosition) .SetMethod("setTitle", &BaseWindow::SetTitle) .SetMethod("getTitle", &BaseWindow::GetTitle) .SetProperty("accessibleTitle", &BaseWindow::GetAccessibleTitle, &BaseWindow::SetAccessibleTitle) .SetMethod("flashFrame", &BaseWindow::FlashFrame) .SetMethod("setSkipTaskbar", &BaseWindow::SetSkipTaskbar) .SetMethod("setSimpleFullScreen", &BaseWindow::SetSimpleFullScreen) .SetMethod("isSimpleFullScreen", &BaseWindow::IsSimpleFullScreen) .SetMethod("setKiosk", &BaseWindow::SetKiosk) .SetMethod("isKiosk", &BaseWindow::IsKiosk) .SetMethod("isTabletMode", &BaseWindow::IsTabletMode) .SetMethod("setBackgroundColor", &BaseWindow::SetBackgroundColor) .SetMethod("getBackgroundColor", &BaseWindow::GetBackgroundColor) .SetMethod("setHasShadow", &BaseWindow::SetHasShadow) .SetMethod("hasShadow", &BaseWindow::HasShadow) .SetMethod("setOpacity", &BaseWindow::SetOpacity) .SetMethod("getOpacity", &BaseWindow::GetOpacity) .SetMethod("setShape", &BaseWindow::SetShape) .SetMethod("setRepresentedFilename", &BaseWindow::SetRepresentedFilename) .SetMethod("getRepresentedFilename", &BaseWindow::GetRepresentedFilename) .SetMethod("setDocumentEdited", &BaseWindow::SetDocumentEdited) .SetMethod("isDocumentEdited", &BaseWindow::IsDocumentEdited) .SetMethod("setIgnoreMouseEvents", &BaseWindow::SetIgnoreMouseEvents) .SetMethod("setContentProtection", &BaseWindow::SetContentProtection) .SetMethod("setFocusable", &BaseWindow::SetFocusable) .SetMethod("isFocusable", &BaseWindow::IsFocusable) .SetMethod("setMenu", &BaseWindow::SetMenu) .SetMethod("removeMenu", &BaseWindow::RemoveMenu) .SetMethod("setParentWindow", &BaseWindow::SetParentWindow) .SetMethod("setBrowserView", &BaseWindow::SetBrowserView) .SetMethod("addBrowserView", &BaseWindow::AddBrowserView) .SetMethod("removeBrowserView", &BaseWindow::RemoveBrowserView) .SetMethod("setTopBrowserView", &BaseWindow::SetTopBrowserView) .SetMethod("getMediaSourceId", &BaseWindow::GetMediaSourceId) .SetMethod("getNativeWindowHandle", &BaseWindow::GetNativeWindowHandle) .SetMethod("setProgressBar", &BaseWindow::SetProgressBar) .SetMethod("setOverlayIcon", &BaseWindow::SetOverlayIcon) .SetMethod("setVisibleOnAllWorkspaces", &BaseWindow::SetVisibleOnAllWorkspaces) .SetMethod("isVisibleOnAllWorkspaces", &BaseWindow::IsVisibleOnAllWorkspaces) #if BUILDFLAG(IS_MAC) .SetMethod("invalidateShadow", &BaseWindow::InvalidateShadow) .SetMethod("_getAlwaysOnTopLevel", &BaseWindow::GetAlwaysOnTopLevel) .SetMethod("setAutoHideCursor", &BaseWindow::SetAutoHideCursor) #endif .SetMethod("setVibrancy", &BaseWindow::SetVibrancy) .SetMethod("setBackgroundMaterial", &BaseWindow::SetBackgroundMaterial) #if BUILDFLAG(IS_MAC) .SetMethod("isHiddenInMissionControl", &BaseWindow::IsHiddenInMissionControl) .SetMethod("setHiddenInMissionControl", &BaseWindow::SetHiddenInMissionControl) #endif .SetMethod("_setTouchBarItems", &BaseWindow::SetTouchBar) .SetMethod("_refreshTouchBarItem", &BaseWindow::RefreshTouchBarItem) .SetMethod("_setEscapeTouchBarItem", &BaseWindow::SetEscapeTouchBarItem) #if BUILDFLAG(IS_MAC) .SetMethod("selectPreviousTab", &BaseWindow::SelectPreviousTab) .SetMethod("selectNextTab", &BaseWindow::SelectNextTab) .SetMethod("showAllTabs", &BaseWindow::ShowAllTabs) .SetMethod("mergeAllWindows", &BaseWindow::MergeAllWindows) .SetMethod("moveTabToNewWindow", &BaseWindow::MoveTabToNewWindow) .SetMethod("toggleTabBar", &BaseWindow::ToggleTabBar) .SetMethod("addTabbedWindow", &BaseWindow::AddTabbedWindow) .SetMethod("setWindowButtonVisibility", &BaseWindow::SetWindowButtonVisibility) .SetMethod("_getWindowButtonVisibility", &BaseWindow::GetWindowButtonVisibility) .SetMethod("setWindowButtonPosition", &BaseWindow::SetWindowButtonPosition) .SetMethod("getWindowButtonPosition", &BaseWindow::GetWindowButtonPosition) .SetProperty("excludedFromShownWindowsMenu", &BaseWindow::IsExcludedFromShownWindowsMenu, &BaseWindow::SetExcludedFromShownWindowsMenu) #endif .SetMethod("setAutoHideMenuBar", &BaseWindow::SetAutoHideMenuBar) .SetMethod("isMenuBarAutoHide", &BaseWindow::IsMenuBarAutoHide) .SetMethod("setMenuBarVisibility", &BaseWindow::SetMenuBarVisibility) .SetMethod("isMenuBarVisible", &BaseWindow::IsMenuBarVisible) .SetMethod("setAspectRatio", &BaseWindow::SetAspectRatio) .SetMethod("previewFile", &BaseWindow::PreviewFile) .SetMethod("closeFilePreview", &BaseWindow::CloseFilePreview) .SetMethod("getContentView", &BaseWindow::GetContentView) .SetMethod("getParentWindow", &BaseWindow::GetParentWindow) .SetMethod("getChildWindows", &BaseWindow::GetChildWindows) .SetMethod("getBrowserView", &BaseWindow::GetBrowserView) .SetMethod("getBrowserViews", &BaseWindow::GetBrowserViews) .SetMethod("isModal", &BaseWindow::IsModal) .SetMethod("setThumbarButtons", &BaseWindow::SetThumbarButtons) #if defined(TOOLKIT_VIEWS) .SetMethod("setIcon", &BaseWindow::SetIcon) #endif #if BUILDFLAG(IS_WIN) .SetMethod("hookWindowMessage", &BaseWindow::HookWindowMessage) .SetMethod("isWindowMessageHooked", &BaseWindow::IsWindowMessageHooked) .SetMethod("unhookWindowMessage", &BaseWindow::UnhookWindowMessage) .SetMethod("unhookAllWindowMessages", &BaseWindow::UnhookAllWindowMessages) .SetMethod("setThumbnailClip", &BaseWindow::SetThumbnailClip) .SetMethod("setThumbnailToolTip", &BaseWindow::SetThumbnailToolTip) .SetMethod("setAppDetails", &BaseWindow::SetAppDetails) #endif .SetProperty("id", &BaseWindow::GetID); } } // namespace electron::api namespace { using electron::api::BaseWindow; void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused, v8::Local<v8::Context> context, void* priv) { v8::Isolate* isolate = context->GetIsolate(); BaseWindow::SetConstructor(isolate, base::BindRepeating(&BaseWindow::New)); gin_helper::Dictionary constructor(isolate, BaseWindow::GetConstructor(isolate) ->GetFunction(context) .ToLocalChecked()); constructor.SetMethod("fromId", &BaseWindow::FromWeakMapID); constructor.SetMethod("getAllWindows", &BaseWindow::GetAll); gin_helper::Dictionary dict(isolate, exports); dict.Set("BaseWindow", constructor); } } // namespace NODE_LINKED_BINDING_CONTEXT_AWARE(electron_browser_base_window, Initialize)
closed
electron/electron
https://github.com/electron/electron
39,257
[Bug]: BrowserView y-coordinate is not respected on macOS Ventura (13.4.1 and 13.5)
### 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 25.3.2 ### What operating system are you using? macOS ### Operating System Version macOS Ventura (13.4.1 and 13.5) ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version 22.3.18 ### Expected Behavior This code should place a BrowserView on top of the default BrowserWindow, respecting the indicated x and y coordinates: ``` const bwin = new BrowserWindow({ width: 300, height: 500 }) bwin.loadURL('https://electronjs.org/') const bview = new BrowserView() bview.setBounds({ x: 0, y: 0, width: 300, height: 300 }) bwin.addBrowserView(bview) bview.webContents.loadURL('https://github.com/') ``` ### Actual Behavior While the previous code works perfectly on Windows 11, on macOS the y-coordinate of the BrowserView is shifted by the same amount of pixels as the height of BrowserWindow (causing the BrowserView to disappear). So on macOS to correctly position the BrowserView you need to set its y-coordinate to -BrowserViewHeight ``` const bwin = new BrowserWindow({ width: 300, height: 500 }) bwin.loadURL('https://electronjs.org/') const bview = new BrowserView() bview.setBounds({ x: 0, y: -500, // <------- !!! width: 300, height: 300 }) bwin.addBrowserView(bview) bview.webContents.loadURL('https://github.com/') ``` ### Testcase Gist URL https://gist.github.com/360b53fa59bce4a9e49549954bc23444 ### Additional Information _No response_
https://github.com/electron/electron/issues/39257
https://github.com/electron/electron/pull/39605
522bba3dc6b4893fdcf4d1a978fec0204b50d63b
a8999bc529390e7a9a2515bfa23445b34b10860a
2023-07-27T11:07:57Z
c++
2023-08-23T13:55:31Z
shell/browser/api/electron_api_browser_view.h
// Copyright (c) 2017 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_BROWSER_VIEW_H_ #define ELECTRON_SHELL_BROWSER_API_ELECTRON_API_BROWSER_VIEW_H_ #include <memory> #include <string> #include "base/memory/raw_ptr.h" #include "content/public/browser/web_contents_observer.h" #include "gin/handle.h" #include "gin/wrappable.h" #include "shell/browser/draggable_region_provider.h" #include "shell/browser/extended_web_contents_observer.h" #include "shell/browser/native_browser_view.h" #include "shell/browser/native_window.h" #include "shell/common/api/api.mojom.h" #include "shell/common/gin_helper/constructible.h" #include "shell/common/gin_helper/error_thrower.h" #include "shell/common/gin_helper/pinnable.h" namespace gfx { class Rect; } namespace gin_helper { class Dictionary; } namespace electron::api { class WebContents; class BaseWindow; class BrowserView : public gin::Wrappable<BrowserView>, public gin_helper::Constructible<BrowserView>, public gin_helper::Pinnable<BrowserView>, public content::WebContentsObserver, public ExtendedWebContentsObserver, public DraggableRegionProvider { public: // gin_helper::Constructible static gin::Handle<BrowserView> New(gin_helper::ErrorThrower thrower, gin::Arguments* args); static void FillObjectTemplate(v8::Isolate*, v8::Local<v8::ObjectTemplate>); static const char* GetClassName() { return "BrowserView"; } // gin::Wrappable static gin::WrapperInfo kWrapperInfo; const char* GetTypeName() override; WebContents* web_contents() const { return api_web_contents_; } NativeBrowserView* view() const { return view_.get(); } BaseWindow* owner_window() const { return owner_window_.get(); } void SetOwnerWindow(BaseWindow* window); int32_t ID() const { return id_; } int NonClientHitTest(const gfx::Point& point) override; // disable copy BrowserView(const BrowserView&) = delete; BrowserView& operator=(const BrowserView&) = delete; protected: BrowserView(gin::Arguments* args, const gin_helper::Dictionary& options); ~BrowserView() override; // content::WebContentsObserver: void WebContentsDestroyed() override; // ExtendedWebContentsObserver: void OnCloseContents() override; private: void SetAutoResize(AutoResizeFlags flags); void SetBounds(const gfx::Rect& bounds); gfx::Rect GetBounds(); void SetBackgroundColor(const std::string& color_name); v8::Local<v8::Value> GetWebContents(v8::Isolate*); v8::Global<v8::Value> web_contents_; class raw_ptr<WebContents> api_web_contents_ = nullptr; std::unique_ptr<NativeBrowserView> view_; base::WeakPtr<BaseWindow> owner_window_; int32_t id_; }; } // namespace electron::api #endif // ELECTRON_SHELL_BROWSER_API_ELECTRON_API_BROWSER_VIEW_H_
closed
electron/electron
https://github.com/electron/electron
39,257
[Bug]: BrowserView y-coordinate is not respected on macOS Ventura (13.4.1 and 13.5)
### 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 25.3.2 ### What operating system are you using? macOS ### Operating System Version macOS Ventura (13.4.1 and 13.5) ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version 22.3.18 ### Expected Behavior This code should place a BrowserView on top of the default BrowserWindow, respecting the indicated x and y coordinates: ``` const bwin = new BrowserWindow({ width: 300, height: 500 }) bwin.loadURL('https://electronjs.org/') const bview = new BrowserView() bview.setBounds({ x: 0, y: 0, width: 300, height: 300 }) bwin.addBrowserView(bview) bview.webContents.loadURL('https://github.com/') ``` ### Actual Behavior While the previous code works perfectly on Windows 11, on macOS the y-coordinate of the BrowserView is shifted by the same amount of pixels as the height of BrowserWindow (causing the BrowserView to disappear). So on macOS to correctly position the BrowserView you need to set its y-coordinate to -BrowserViewHeight ``` const bwin = new BrowserWindow({ width: 300, height: 500 }) bwin.loadURL('https://electronjs.org/') const bview = new BrowserView() bview.setBounds({ x: 0, y: -500, // <------- !!! width: 300, height: 300 }) bwin.addBrowserView(bview) bview.webContents.loadURL('https://github.com/') ``` ### Testcase Gist URL https://gist.github.com/360b53fa59bce4a9e49549954bc23444 ### Additional Information _No response_
https://github.com/electron/electron/issues/39257
https://github.com/electron/electron/pull/39605
522bba3dc6b4893fdcf4d1a978fec0204b50d63b
a8999bc529390e7a9a2515bfa23445b34b10860a
2023-07-27T11:07:57Z
c++
2023-08-23T13:55:31Z
shell/browser/native_browser_view_mac.mm
// 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/browser/native_browser_view_mac.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/ui/inspectable_web_contents_view.h" #include "skia/ext/skia_utils_mac.h" #include "ui/gfx/geometry/rect.h" // Match view::Views behavior where the view sticks to the top-left origin. const NSAutoresizingMaskOptions kDefaultAutoResizingMask = NSViewMaxXMargin | NSViewMinYMargin; namespace electron { NativeBrowserViewMac::NativeBrowserViewMac( InspectableWebContents* inspectable_web_contents) : NativeBrowserView(inspectable_web_contents) { auto* iwc_view = GetInspectableWebContentsView(); if (!iwc_view) return; auto* view = iwc_view->GetNativeView().GetNativeNSView(); view.autoresizingMask = kDefaultAutoResizingMask; } NativeBrowserViewMac::~NativeBrowserViewMac() = default; void NativeBrowserViewMac::SetAutoResizeFlags(uint8_t flags) { NSAutoresizingMaskOptions autoresizing_mask = kDefaultAutoResizingMask; if (flags & kAutoResizeWidth) { autoresizing_mask |= NSViewWidthSizable; } if (flags & kAutoResizeHeight) { autoresizing_mask |= NSViewHeightSizable; } if (flags & kAutoResizeHorizontal) { autoresizing_mask |= NSViewMaxXMargin | NSViewMinXMargin | NSViewWidthSizable; } if (flags & kAutoResizeVertical) { autoresizing_mask |= NSViewMaxYMargin | NSViewMinYMargin | NSViewHeightSizable; } auto* iwc_view = GetInspectableWebContentsView(); if (!iwc_view) return; auto* view = iwc_view->GetNativeView().GetNativeNSView(); view.autoresizingMask = autoresizing_mask; } void NativeBrowserViewMac::SetBounds(const gfx::Rect& bounds) { auto* iwc_view = GetInspectableWebContentsView(); if (!iwc_view) return; auto* view = iwc_view->GetNativeView().GetNativeNSView(); auto* superview = view.superview; const auto superview_height = superview ? superview.frame.size.height : 0; view.frame = NSMakeRect(bounds.x(), superview_height - bounds.y() - bounds.height(), bounds.width(), bounds.height()); } gfx::Rect NativeBrowserViewMac::GetBounds() { auto* iwc_view = GetInspectableWebContentsView(); if (!iwc_view) return gfx::Rect(); NSView* view = iwc_view->GetNativeView().GetNativeNSView(); const int superview_height = (view.superview) ? view.superview.frame.size.height : 0; return gfx::Rect( view.frame.origin.x, superview_height - view.frame.origin.y - view.frame.size.height, view.frame.size.width, view.frame.size.height); } void NativeBrowserViewMac::SetBackgroundColor(SkColor color) { auto* iwc_view = GetInspectableWebContentsView(); if (!iwc_view) return; auto* view = iwc_view->GetNativeView().GetNativeNSView(); view.wantsLayer = YES; view.layer.backgroundColor = skia::CGColorCreateFromSkColor(color); } // static NativeBrowserView* NativeBrowserView::Create( InspectableWebContents* inspectable_web_contents) { return new NativeBrowserViewMac(inspectable_web_contents); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
39,257
[Bug]: BrowserView y-coordinate is not respected on macOS Ventura (13.4.1 and 13.5)
### 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 25.3.2 ### What operating system are you using? macOS ### Operating System Version macOS Ventura (13.4.1 and 13.5) ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version 22.3.18 ### Expected Behavior This code should place a BrowserView on top of the default BrowserWindow, respecting the indicated x and y coordinates: ``` const bwin = new BrowserWindow({ width: 300, height: 500 }) bwin.loadURL('https://electronjs.org/') const bview = new BrowserView() bview.setBounds({ x: 0, y: 0, width: 300, height: 300 }) bwin.addBrowserView(bview) bview.webContents.loadURL('https://github.com/') ``` ### Actual Behavior While the previous code works perfectly on Windows 11, on macOS the y-coordinate of the BrowserView is shifted by the same amount of pixels as the height of BrowserWindow (causing the BrowserView to disappear). So on macOS to correctly position the BrowserView you need to set its y-coordinate to -BrowserViewHeight ``` const bwin = new BrowserWindow({ width: 300, height: 500 }) bwin.loadURL('https://electronjs.org/') const bview = new BrowserView() bview.setBounds({ x: 0, y: -500, // <------- !!! width: 300, height: 300 }) bwin.addBrowserView(bview) bview.webContents.loadURL('https://github.com/') ``` ### Testcase Gist URL https://gist.github.com/360b53fa59bce4a9e49549954bc23444 ### Additional Information _No response_
https://github.com/electron/electron/issues/39257
https://github.com/electron/electron/pull/39605
522bba3dc6b4893fdcf4d1a978fec0204b50d63b
a8999bc529390e7a9a2515bfa23445b34b10860a
2023-07-27T11:07:57Z
c++
2023-08-23T13:55:31Z
spec/api-browser-view-spec.ts
import { expect } from 'chai'; import * as path from 'node:path'; import { BrowserView, BrowserWindow, screen, webContents } from 'electron/main'; import { closeWindow } from './lib/window-helpers'; import { defer, ifit, startRemoteControlApp } from './lib/spec-helpers'; import { areColorsSimilar, captureScreen, getPixelColor } from './lib/screen-helpers'; import { once } from 'node:events'; describe('BrowserView module', () => { const fixtures = path.resolve(__dirname, 'fixtures'); let w: BrowserWindow; let view: BrowserView; beforeEach(() => { expect(webContents.getAllWebContents()).to.have.length(0); w = new BrowserWindow({ show: false, width: 400, height: 400, webPreferences: { backgroundThrottling: false } }); }); afterEach(async () => { const p = once(w.webContents, 'destroyed'); await closeWindow(w); w = null as any; await p; if (view && view.webContents) { const p = once(view.webContents, 'destroyed'); view.webContents.destroy(); view = null as any; await p; } expect(webContents.getAllWebContents()).to.have.length(0); }); it('sets the correct class name on the prototype', () => { expect(BrowserView.prototype.constructor.name).to.equal('BrowserView'); }); it('can be created with an existing webContents', async () => { const wc = (webContents as typeof ElectronInternal.WebContents).create({ sandbox: true }); await wc.loadURL('about:blank'); view = new BrowserView({ webContents: wc } as any); expect(view.webContents.getURL()).to.equal('about:blank'); }); describe('BrowserView.setBackgroundColor()', () => { it('does not throw for valid args', () => { view = new BrowserView(); view.setBackgroundColor('#000'); }); it('throws for invalid args', () => { view = new BrowserView(); expect(() => { view.setBackgroundColor(null as any); }).to.throw(/conversion failure/); }); // Linux and arm64 platforms (WOA and macOS) do not return any capture sources ifit(process.platform === 'darwin' && process.arch === 'x64')('sets the background color to transparent if none is set', async () => { const display = screen.getPrimaryDisplay(); const WINDOW_BACKGROUND_COLOR = '#55ccbb'; w.show(); w.setBounds(display.bounds); w.setBackgroundColor(WINDOW_BACKGROUND_COLOR); await w.loadURL('about:blank'); view = new BrowserView(); view.setBounds(display.bounds); w.setBrowserView(view); await view.webContents.loadURL('data:text/html,hello there'); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); expect(areColorsSimilar(centerColor, WINDOW_BACKGROUND_COLOR)).to.be.true(); }); // Linux and arm64 platforms (WOA and macOS) do not return any capture sources ifit(process.platform === 'darwin' && process.arch === 'x64')('successfully applies the background color', async () => { const WINDOW_BACKGROUND_COLOR = '#55ccbb'; const VIEW_BACKGROUND_COLOR = '#ff00ff'; const display = screen.getPrimaryDisplay(); w.show(); w.setBounds(display.bounds); w.setBackgroundColor(WINDOW_BACKGROUND_COLOR); await w.loadURL('about:blank'); view = new BrowserView(); view.setBounds(display.bounds); w.setBrowserView(view); w.setBackgroundColor(VIEW_BACKGROUND_COLOR); await view.webContents.loadURL('data:text/html,hello there'); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); expect(areColorsSimilar(centerColor, VIEW_BACKGROUND_COLOR)).to.be.true(); }); }); describe('BrowserView.setAutoResize()', () => { it('does not throw for valid args', () => { view = new BrowserView(); view.setAutoResize({}); view.setAutoResize({ width: true, height: false }); }); it('throws for invalid args', () => { view = new BrowserView(); expect(() => { view.setAutoResize(null as any); }).to.throw(/conversion failure/); }); }); describe('BrowserView.setBounds()', () => { it('does not throw for valid args', () => { view = new BrowserView(); view.setBounds({ x: 0, y: 0, width: 1, height: 1 }); }); it('throws for invalid args', () => { view = new BrowserView(); expect(() => { view.setBounds(null as any); }).to.throw(/conversion failure/); expect(() => { view.setBounds({} as any); }).to.throw(/conversion failure/); }); }); describe('BrowserView.getBounds()', () => { it('returns the current bounds', () => { view = new BrowserView(); const bounds = { x: 10, y: 20, width: 30, height: 40 }; view.setBounds(bounds); expect(view.getBounds()).to.deep.equal(bounds); }); }); describe('BrowserWindow.setBrowserView()', () => { it('does not throw for valid args', () => { view = new BrowserView(); w.setBrowserView(view); }); it('does not throw if called multiple times with same view', () => { view = new BrowserView(); w.setBrowserView(view); w.setBrowserView(view); w.setBrowserView(view); }); }); describe('BrowserWindow.getBrowserView()', () => { it('returns the set view', () => { view = new BrowserView(); w.setBrowserView(view); const view2 = w.getBrowserView(); expect(view2!.webContents.id).to.equal(view.webContents.id); }); it('returns null if none is set', () => { const view = w.getBrowserView(); expect(view).to.be.null('view'); }); }); describe('BrowserWindow.addBrowserView()', () => { it('does not throw for valid args', () => { const view1 = new BrowserView(); defer(() => view1.webContents.destroy()); w.addBrowserView(view1); defer(() => w.removeBrowserView(view1)); const view2 = new BrowserView(); defer(() => view2.webContents.destroy()); w.addBrowserView(view2); defer(() => w.removeBrowserView(view2)); }); it('does not throw if called multiple times with same view', () => { view = new BrowserView(); w.addBrowserView(view); w.addBrowserView(view); w.addBrowserView(view); }); it('does not crash if the BrowserView webContents are destroyed prior to window addition', () => { expect(() => { const view1 = new BrowserView(); view1.webContents.destroy(); w.addBrowserView(view1); }).to.not.throw(); }); it('does not crash if the webContents is destroyed after a URL is loaded', () => { view = new BrowserView(); expect(async () => { view.setBounds({ x: 0, y: 0, width: 400, height: 300 }); await view.webContents.loadURL('data:text/html,hello there'); view.webContents.destroy(); }).to.not.throw(); }); it('can handle BrowserView reparenting', async () => { view = new BrowserView(); w.addBrowserView(view); view.webContents.loadURL('about:blank'); await once(view.webContents, 'did-finish-load'); const w2 = new BrowserWindow({ show: false }); w2.addBrowserView(view); w.close(); view.webContents.loadURL(`file://${fixtures}/pages/blank.html`); await once(view.webContents, 'did-finish-load'); // Clean up - the afterEach hook assumes the webContents on w is still alive. w = new BrowserWindow({ show: false }); w2.close(); w2.destroy(); }); }); describe('BrowserWindow.removeBrowserView()', () => { it('does not throw if called multiple times with same view', () => { expect(() => { view = new BrowserView(); w.addBrowserView(view); w.removeBrowserView(view); w.removeBrowserView(view); }).to.not.throw(); }); it('can be called on a BrowserView with a destroyed webContents', (done) => { view = new BrowserView(); w.addBrowserView(view); view.webContents.on('destroyed', () => { w.removeBrowserView(view); done(); }); view.webContents.loadURL('data:text/html,hello there').then(() => { view.webContents.close(); }); }); }); describe('BrowserWindow.getBrowserViews()', () => { it('returns same views as was added', () => { const view1 = new BrowserView(); defer(() => view1.webContents.destroy()); w.addBrowserView(view1); defer(() => w.removeBrowserView(view1)); const view2 = new BrowserView(); defer(() => view2.webContents.destroy()); w.addBrowserView(view2); defer(() => w.removeBrowserView(view2)); const views = w.getBrowserViews(); expect(views).to.have.lengthOf(2); expect(views[0].webContents.id).to.equal(view1.webContents.id); expect(views[1].webContents.id).to.equal(view2.webContents.id); }); it('persists ordering by z-index', () => { const view1 = new BrowserView(); defer(() => view1.webContents.destroy()); w.addBrowserView(view1); defer(() => w.removeBrowserView(view1)); const view2 = new BrowserView(); defer(() => view2.webContents.destroy()); w.addBrowserView(view2); defer(() => w.removeBrowserView(view2)); w.setTopBrowserView(view1); const views = w.getBrowserViews(); expect(views).to.have.lengthOf(2); expect(views[0].webContents.id).to.equal(view2.webContents.id); expect(views[1].webContents.id).to.equal(view1.webContents.id); }); }); describe('BrowserWindow.setTopBrowserView()', () => { it('should throw an error when a BrowserView is not attached to the window', () => { view = new BrowserView(); expect(() => { w.setTopBrowserView(view); }).to.throw(/is not attached/); }); it('should throw an error when a BrowserView is attached to some other window', () => { view = new BrowserView(); const win2 = new BrowserWindow(); w.addBrowserView(view); view.setBounds({ x: 0, y: 0, width: 100, height: 100 }); win2.addBrowserView(view); expect(() => { w.setTopBrowserView(view); }).to.throw(/is not attached/); win2.close(); win2.destroy(); }); }); describe('BrowserView.webContents.getOwnerBrowserWindow()', () => { it('points to owning window', () => { view = new BrowserView(); expect(view.webContents.getOwnerBrowserWindow()).to.be.null('owner browser window'); w.setBrowserView(view); expect(view.webContents.getOwnerBrowserWindow()).to.equal(w); w.setBrowserView(null); expect(view.webContents.getOwnerBrowserWindow()).to.be.null('owner browser window'); }); }); describe('shutdown behavior', () => { it('does not crash on exit', async () => { const rc = await startRemoteControlApp(); await rc.remotely(() => { const { BrowserView, app } = require('electron'); // eslint-disable-next-line no-new new BrowserView({}); setTimeout(() => { app.quit(); }); }); const [code] = await once(rc.process, 'exit'); expect(code).to.equal(0); }); it('does not crash on exit if added to a browser window', async () => { const rc = await startRemoteControlApp(); await rc.remotely(() => { const { app, BrowserView, BrowserWindow } = require('electron'); const bv = new BrowserView(); bv.webContents.loadURL('about:blank'); const bw = new BrowserWindow({ show: false }); bw.addBrowserView(bv); setTimeout(() => { app.quit(); }); }); const [code] = await once(rc.process, 'exit'); expect(code).to.equal(0); }); it('emits the destroyed event when webContents.close() is called', async () => { view = new BrowserView(); w.setBrowserView(view); await view.webContents.loadFile(path.join(fixtures, 'pages', 'a.html')); view.webContents.close(); await once(view.webContents, 'destroyed'); }); it('emits the destroyed event when window.close() is called', async () => { view = new BrowserView(); w.setBrowserView(view); await view.webContents.loadFile(path.join(fixtures, 'pages', 'a.html')); view.webContents.executeJavaScript('window.close()'); await once(view.webContents, 'destroyed'); }); }); describe('window.open()', () => { it('works in BrowserView', (done) => { view = new BrowserView(); w.setBrowserView(view); view.webContents.setWindowOpenHandler(({ url, frameName }) => { expect(url).to.equal('http://host/'); expect(frameName).to.equal('host'); done(); return { action: 'deny' }; }); view.webContents.loadFile(path.join(fixtures, 'pages', 'window-open.html')); }); }); describe('BrowserView.capturePage(rect)', () => { it('returns a Promise with a Buffer', async () => { view = new BrowserView({ webPreferences: { backgroundThrottling: false } }); w.addBrowserView(view); view.setBounds({ ...w.getBounds(), x: 0, y: 0 }); const image = await view.webContents.capturePage({ x: 0, y: 0, width: 100, height: 100 }); expect(image.isEmpty()).to.equal(true); }); xit('resolves after the window is hidden and capturer count is non-zero', async () => { view = new BrowserView({ webPreferences: { backgroundThrottling: false } }); w.setBrowserView(view); view.setBounds({ ...w.getBounds(), x: 0, y: 0 }); await view.webContents.loadFile(path.join(fixtures, 'pages', 'a.html')); const image = await view.webContents.capturePage(); expect(image.isEmpty()).to.equal(false); }); }); });
closed
electron/electron
https://github.com/electron/electron
39,257
[Bug]: BrowserView y-coordinate is not respected on macOS Ventura (13.4.1 and 13.5)
### 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 25.3.2 ### What operating system are you using? macOS ### Operating System Version macOS Ventura (13.4.1 and 13.5) ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version 22.3.18 ### Expected Behavior This code should place a BrowserView on top of the default BrowserWindow, respecting the indicated x and y coordinates: ``` const bwin = new BrowserWindow({ width: 300, height: 500 }) bwin.loadURL('https://electronjs.org/') const bview = new BrowserView() bview.setBounds({ x: 0, y: 0, width: 300, height: 300 }) bwin.addBrowserView(bview) bview.webContents.loadURL('https://github.com/') ``` ### Actual Behavior While the previous code works perfectly on Windows 11, on macOS the y-coordinate of the BrowserView is shifted by the same amount of pixels as the height of BrowserWindow (causing the BrowserView to disappear). So on macOS to correctly position the BrowserView you need to set its y-coordinate to -BrowserViewHeight ``` const bwin = new BrowserWindow({ width: 300, height: 500 }) bwin.loadURL('https://electronjs.org/') const bview = new BrowserView() bview.setBounds({ x: 0, y: -500, // <------- !!! width: 300, height: 300 }) bwin.addBrowserView(bview) bview.webContents.loadURL('https://github.com/') ``` ### Testcase Gist URL https://gist.github.com/360b53fa59bce4a9e49549954bc23444 ### Additional Information _No response_
https://github.com/electron/electron/issues/39257
https://github.com/electron/electron/pull/39605
522bba3dc6b4893fdcf4d1a978fec0204b50d63b
a8999bc529390e7a9a2515bfa23445b34b10860a
2023-07-27T11:07:57Z
c++
2023-08-23T13:55:31Z
shell/browser/api/electron_api_base_window.cc
// Copyright (c) 2018 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_base_window.h" #include <algorithm> #include <string> #include <utility> #include <vector> #include "base/containers/contains.h" #include "base/task/single_thread_task_runner.h" #include "electron/buildflags/buildflags.h" #include "gin/dictionary.h" #include "shell/browser/api/electron_api_browser_view.h" #include "shell/browser/api/electron_api_menu.h" #include "shell/browser/api/electron_api_view.h" #include "shell/browser/api/electron_api_web_contents.h" #include "shell/browser/javascript_environment.h" #include "shell/common/color_util.h" #include "shell/common/gin_converters/callback_converter.h" #include "shell/common/gin_converters/file_path_converter.h" #include "shell/common/gin_converters/gfx_converter.h" #include "shell/common/gin_converters/image_converter.h" #include "shell/common/gin_converters/native_window_converter.h" #include "shell/common/gin_converters/optional_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/gin_helper/persistent_dictionary.h" #include "shell/common/node_includes.h" #include "shell/common/options_switches.h" #if defined(TOOLKIT_VIEWS) #include "shell/browser/native_window_views.h" #endif #if BUILDFLAG(IS_WIN) #include "shell/browser/ui/win/taskbar_host.h" #include "ui/base/win/shell.h" #endif #if BUILDFLAG(IS_WIN) namespace gin { template <> struct Converter<electron::TaskbarHost::ThumbarButton> { static bool FromV8(v8::Isolate* isolate, v8::Handle<v8::Value> val, electron::TaskbarHost::ThumbarButton* out) { gin::Dictionary dict(isolate); if (!gin::ConvertFromV8(isolate, val, &dict)) return false; dict.Get("click", &(out->clicked_callback)); dict.Get("tooltip", &(out->tooltip)); dict.Get("flags", &out->flags); return dict.Get("icon", &(out->icon)); } }; } // namespace gin #endif namespace electron::api { namespace { // Converts binary data to Buffer. v8::Local<v8::Value> ToBuffer(v8::Isolate* isolate, void* val, int size) { auto buffer = node::Buffer::Copy(isolate, static_cast<char*>(val), size); if (buffer.IsEmpty()) return v8::Null(isolate); else return buffer.ToLocalChecked(); } } // namespace BaseWindow::BaseWindow(v8::Isolate* isolate, const gin_helper::Dictionary& options) { // The parent window. gin::Handle<BaseWindow> parent; if (options.Get("parent", &parent) && !parent.IsEmpty()) parent_window_.Reset(isolate, parent.ToV8()); // Offscreen windows are always created frameless. gin_helper::Dictionary web_preferences; bool offscreen; if (options.Get(options::kWebPreferences, &web_preferences) && web_preferences.Get(options::kOffscreen, &offscreen) && offscreen) { const_cast<gin_helper::Dictionary&>(options).Set(options::kFrame, false); } // Creates NativeWindow. window_.reset(NativeWindow::Create( options, parent.IsEmpty() ? nullptr : parent->window_.get())); window_->AddObserver(this); #if defined(TOOLKIT_VIEWS) v8::Local<v8::Value> icon; if (options.Get(options::kIcon, &icon)) { SetIconImpl(isolate, icon, NativeImage::OnConvertError::kWarn); } #endif } BaseWindow::BaseWindow(gin_helper::Arguments* args, const gin_helper::Dictionary& options) : BaseWindow(args->isolate(), options) { InitWithArgs(args); // Init window after everything has been setup. window()->InitFromOptions(options); } BaseWindow::~BaseWindow() { CloseImmediately(); // Destroy the native window in next tick because the native code might be // iterating all windows. base::SingleThreadTaskRunner::GetCurrentDefault()->DeleteSoon( FROM_HERE, window_.release()); // Remove global reference so the JS object can be garbage collected. self_ref_.Reset(); } void BaseWindow::InitWith(v8::Isolate* isolate, v8::Local<v8::Object> wrapper) { AttachAsUserData(window_.get()); gin_helper::TrackableObject<BaseWindow>::InitWith(isolate, wrapper); // We can only append this window to parent window's child windows after this // window's JS wrapper gets initialized. if (!parent_window_.IsEmpty()) { gin::Handle<BaseWindow> parent; gin::ConvertFromV8(isolate, GetParentWindow(), &parent); DCHECK(!parent.IsEmpty()); parent->child_windows_.Set(isolate, weak_map_id(), wrapper); } // Reference this object in case it got garbage collected. self_ref_.Reset(isolate, wrapper); } void BaseWindow::WillCloseWindow(bool* prevent_default) { if (Emit("close")) { *prevent_default = true; } } void BaseWindow::OnWindowClosed() { // Invalidate weak ptrs before the Javascript object is destroyed, // there might be some delayed emit events which shouldn't be // triggered after this. weak_factory_.InvalidateWeakPtrs(); RemoveFromWeakMap(); window_->RemoveObserver(this); // We can not call Destroy here because we need to call Emit first, but we // also do not want any method to be used, so just mark as destroyed here. MarkDestroyed(); Emit("closed"); RemoveFromParentChildWindows(); BaseWindow::ResetBrowserViews(); // Destroy the native class when window is closed. base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask( FROM_HERE, GetDestroyClosure()); } void BaseWindow::OnWindowEndSession() { Emit("session-end"); } void BaseWindow::OnWindowBlur() { EmitEventSoon("blur"); } void BaseWindow::OnWindowFocus() { EmitEventSoon("focus"); } void BaseWindow::OnWindowShow() { Emit("show"); } void BaseWindow::OnWindowHide() { Emit("hide"); } void BaseWindow::OnWindowMaximize() { Emit("maximize"); } void BaseWindow::OnWindowUnmaximize() { Emit("unmaximize"); } void BaseWindow::OnWindowMinimize() { Emit("minimize"); } void BaseWindow::OnWindowRestore() { Emit("restore"); } void BaseWindow::OnWindowWillResize(const gfx::Rect& new_bounds, const gfx::ResizeEdge& edge, bool* prevent_default) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); auto info = gin::Dictionary::CreateEmpty(isolate); info.Set("edge", edge); if (Emit("will-resize", new_bounds, info)) { *prevent_default = true; } } void BaseWindow::OnWindowResize() { Emit("resize"); } void BaseWindow::OnWindowResized() { Emit("resized"); } void BaseWindow::OnWindowWillMove(const gfx::Rect& new_bounds, bool* prevent_default) { if (Emit("will-move", new_bounds)) { *prevent_default = true; } } void BaseWindow::OnWindowMove() { Emit("move"); } void BaseWindow::OnWindowMoved() { Emit("moved"); } void BaseWindow::OnWindowEnterFullScreen() { Emit("enter-full-screen"); } void BaseWindow::OnWindowLeaveFullScreen() { Emit("leave-full-screen"); } void BaseWindow::OnWindowSwipe(const std::string& direction) { Emit("swipe", direction); } void BaseWindow::OnWindowRotateGesture(float rotation) { Emit("rotate-gesture", rotation); } void BaseWindow::OnWindowSheetBegin() { Emit("sheet-begin"); } void BaseWindow::OnWindowSheetEnd() { Emit("sheet-end"); } void BaseWindow::OnWindowEnterHtmlFullScreen() { Emit("enter-html-full-screen"); } void BaseWindow::OnWindowLeaveHtmlFullScreen() { Emit("leave-html-full-screen"); } void BaseWindow::OnWindowAlwaysOnTopChanged() { Emit("always-on-top-changed", IsAlwaysOnTop()); } void BaseWindow::OnExecuteAppCommand(const std::string& command_name) { Emit("app-command", command_name); } void BaseWindow::OnTouchBarItemResult(const std::string& item_id, const base::Value::Dict& details) { Emit("-touch-bar-interaction", item_id, details); } void BaseWindow::OnNewWindowForTab() { Emit("new-window-for-tab"); } void BaseWindow::OnSystemContextMenu(int x, int y, bool* prevent_default) { if (Emit("system-context-menu", gfx::Point(x, y))) { *prevent_default = true; } } #if BUILDFLAG(IS_WIN) void BaseWindow::OnWindowMessage(UINT message, WPARAM w_param, LPARAM l_param) { if (IsWindowMessageHooked(message)) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); messages_callback_map_[message].Run( ToBuffer(isolate, static_cast<void*>(&w_param), sizeof(WPARAM)), ToBuffer(isolate, static_cast<void*>(&l_param), sizeof(LPARAM))); } } #endif void BaseWindow::SetContentView(gin::Handle<View> view) { ResetBrowserViews(); content_view_.Reset(isolate(), view.ToV8()); window_->SetContentView(view->view()); } void BaseWindow::CloseImmediately() { if (!window_->IsClosed()) window_->CloseImmediately(); } void BaseWindow::Close() { window_->Close(); } void BaseWindow::Focus() { window_->Focus(true); } void BaseWindow::Blur() { window_->Focus(false); } bool BaseWindow::IsFocused() { return window_->IsFocused(); } void BaseWindow::Show() { window_->Show(); } void BaseWindow::ShowInactive() { // This method doesn't make sense for modal window. if (IsModal()) return; window_->ShowInactive(); } void BaseWindow::Hide() { window_->Hide(); } bool BaseWindow::IsVisible() { return window_->IsVisible(); } bool BaseWindow::IsEnabled() { return window_->IsEnabled(); } void BaseWindow::SetEnabled(bool enable) { window_->SetEnabled(enable); } void BaseWindow::Maximize() { window_->Maximize(); } void BaseWindow::Unmaximize() { window_->Unmaximize(); } bool BaseWindow::IsMaximized() { return window_->IsMaximized(); } void BaseWindow::Minimize() { window_->Minimize(); } void BaseWindow::Restore() { window_->Restore(); } bool BaseWindow::IsMinimized() { return window_->IsMinimized(); } void BaseWindow::SetFullScreen(bool fullscreen) { window_->SetFullScreen(fullscreen); } bool BaseWindow::IsFullscreen() { return window_->IsFullscreen(); } void BaseWindow::SetBounds(const gfx::Rect& bounds, gin_helper::Arguments* args) { bool animate = false; args->GetNext(&animate); window_->SetBounds(bounds, animate); } gfx::Rect BaseWindow::GetBounds() { return window_->GetBounds(); } bool BaseWindow::IsNormal() { return window_->IsNormal(); } gfx::Rect BaseWindow::GetNormalBounds() { return window_->GetNormalBounds(); } void BaseWindow::SetContentBounds(const gfx::Rect& bounds, gin_helper::Arguments* args) { bool animate = false; args->GetNext(&animate); window_->SetContentBounds(bounds, animate); } gfx::Rect BaseWindow::GetContentBounds() { return window_->GetContentBounds(); } void BaseWindow::SetSize(int width, int height, gin_helper::Arguments* args) { bool animate = false; gfx::Size size = window_->GetMinimumSize(); size.SetToMax(gfx::Size(width, height)); args->GetNext(&animate); window_->SetSize(size, animate); } std::vector<int> BaseWindow::GetSize() { std::vector<int> result(2); gfx::Size size = window_->GetSize(); result[0] = size.width(); result[1] = size.height(); return result; } void BaseWindow::SetContentSize(int width, int height, gin_helper::Arguments* args) { bool animate = false; args->GetNext(&animate); window_->SetContentSize(gfx::Size(width, height), animate); } std::vector<int> BaseWindow::GetContentSize() { std::vector<int> result(2); gfx::Size size = window_->GetContentSize(); result[0] = size.width(); result[1] = size.height(); return result; } void BaseWindow::SetMinimumSize(int width, int height) { window_->SetMinimumSize(gfx::Size(width, height)); } std::vector<int> BaseWindow::GetMinimumSize() { std::vector<int> result(2); gfx::Size size = window_->GetMinimumSize(); result[0] = size.width(); result[1] = size.height(); return result; } void BaseWindow::SetMaximumSize(int width, int height) { window_->SetMaximumSize(gfx::Size(width, height)); } std::vector<int> BaseWindow::GetMaximumSize() { std::vector<int> result(2); gfx::Size size = window_->GetMaximumSize(); result[0] = size.width(); result[1] = size.height(); return result; } void BaseWindow::SetSheetOffset(double offsetY, gin_helper::Arguments* args) { double offsetX = 0.0; args->GetNext(&offsetX); window_->SetSheetOffset(offsetX, offsetY); } void BaseWindow::SetResizable(bool resizable) { window_->SetResizable(resizable); } bool BaseWindow::IsResizable() { return window_->IsResizable(); } void BaseWindow::SetMovable(bool movable) { window_->SetMovable(movable); } bool BaseWindow::IsMovable() { return window_->IsMovable(); } void BaseWindow::SetMinimizable(bool minimizable) { window_->SetMinimizable(minimizable); } bool BaseWindow::IsMinimizable() { return window_->IsMinimizable(); } void BaseWindow::SetMaximizable(bool maximizable) { window_->SetMaximizable(maximizable); } bool BaseWindow::IsMaximizable() { return window_->IsMaximizable(); } void BaseWindow::SetFullScreenable(bool fullscreenable) { window_->SetFullScreenable(fullscreenable); } bool BaseWindow::IsFullScreenable() { return window_->IsFullScreenable(); } void BaseWindow::SetClosable(bool closable) { window_->SetClosable(closable); } bool BaseWindow::IsClosable() { return window_->IsClosable(); } void BaseWindow::SetAlwaysOnTop(bool top, gin_helper::Arguments* args) { std::string level = "floating"; int relative_level = 0; args->GetNext(&level); args->GetNext(&relative_level); ui::ZOrderLevel z_order = top ? ui::ZOrderLevel::kFloatingWindow : ui::ZOrderLevel::kNormal; window_->SetAlwaysOnTop(z_order, level, relative_level); } bool BaseWindow::IsAlwaysOnTop() { return window_->GetZOrderLevel() != ui::ZOrderLevel::kNormal; } void BaseWindow::Center() { window_->Center(); } void BaseWindow::SetPosition(int x, int y, gin_helper::Arguments* args) { bool animate = false; args->GetNext(&animate); window_->SetPosition(gfx::Point(x, y), animate); } std::vector<int> BaseWindow::GetPosition() { std::vector<int> result(2); gfx::Point pos = window_->GetPosition(); result[0] = pos.x(); result[1] = pos.y(); return result; } void BaseWindow::MoveAbove(const std::string& sourceId, gin_helper::Arguments* args) { if (!window_->MoveAbove(sourceId)) args->ThrowError("Invalid media source id"); } void BaseWindow::MoveTop() { window_->MoveTop(); } void BaseWindow::SetTitle(const std::string& title) { window_->SetTitle(title); } std::string BaseWindow::GetTitle() { return window_->GetTitle(); } void BaseWindow::SetAccessibleTitle(const std::string& title) { window_->SetAccessibleTitle(title); } std::string BaseWindow::GetAccessibleTitle() { return window_->GetAccessibleTitle(); } void BaseWindow::FlashFrame(bool flash) { window_->FlashFrame(flash); } void BaseWindow::SetSkipTaskbar(bool skip) { window_->SetSkipTaskbar(skip); } void BaseWindow::SetExcludedFromShownWindowsMenu(bool excluded) { window_->SetExcludedFromShownWindowsMenu(excluded); } bool BaseWindow::IsExcludedFromShownWindowsMenu() { return window_->IsExcludedFromShownWindowsMenu(); } void BaseWindow::SetSimpleFullScreen(bool simple_fullscreen) { window_->SetSimpleFullScreen(simple_fullscreen); } bool BaseWindow::IsSimpleFullScreen() { return window_->IsSimpleFullScreen(); } void BaseWindow::SetKiosk(bool kiosk) { window_->SetKiosk(kiosk); } bool BaseWindow::IsKiosk() { return window_->IsKiosk(); } bool BaseWindow::IsTabletMode() const { return window_->IsTabletMode(); } void BaseWindow::SetBackgroundColor(const std::string& color_name) { SkColor color = ParseCSSColor(color_name); window_->SetBackgroundColor(color); } std::string BaseWindow::GetBackgroundColor(gin_helper::Arguments* args) { return ToRGBHex(window_->GetBackgroundColor()); } void BaseWindow::InvalidateShadow() { window_->InvalidateShadow(); } void BaseWindow::SetHasShadow(bool has_shadow) { window_->SetHasShadow(has_shadow); } bool BaseWindow::HasShadow() { return window_->HasShadow(); } void BaseWindow::SetOpacity(const double opacity) { window_->SetOpacity(opacity); } double BaseWindow::GetOpacity() { return window_->GetOpacity(); } void BaseWindow::SetShape(const std::vector<gfx::Rect>& rects) { window_->widget()->SetShape(std::make_unique<std::vector<gfx::Rect>>(rects)); } void BaseWindow::SetRepresentedFilename(const std::string& filename) { window_->SetRepresentedFilename(filename); } std::string BaseWindow::GetRepresentedFilename() { return window_->GetRepresentedFilename(); } void BaseWindow::SetDocumentEdited(bool edited) { window_->SetDocumentEdited(edited); } bool BaseWindow::IsDocumentEdited() { return window_->IsDocumentEdited(); } void BaseWindow::SetIgnoreMouseEvents(bool ignore, gin_helper::Arguments* args) { gin_helper::Dictionary options; bool forward = false; args->GetNext(&options) && options.Get("forward", &forward); return window_->SetIgnoreMouseEvents(ignore, forward); } void BaseWindow::SetContentProtection(bool enable) { return window_->SetContentProtection(enable); } void BaseWindow::SetFocusable(bool focusable) { return window_->SetFocusable(focusable); } bool BaseWindow::IsFocusable() { return window_->IsFocusable(); } void BaseWindow::SetMenu(v8::Isolate* isolate, v8::Local<v8::Value> value) { auto context = isolate->GetCurrentContext(); gin::Handle<Menu> menu; v8::Local<v8::Object> object; if (value->IsObject() && value->ToObject(context).ToLocal(&object) && gin::ConvertFromV8(isolate, value, &menu) && !menu.IsEmpty()) { // We only want to update the menu if the menu has a non-zero item count, // or we risk crashes. if (menu->model()->GetItemCount() == 0) { RemoveMenu(); } else { window_->SetMenu(menu->model()); } menu_.Reset(isolate, menu.ToV8()); } else if (value->IsNull()) { RemoveMenu(); } else { isolate->ThrowException( v8::Exception::TypeError(gin::StringToV8(isolate, "Invalid Menu"))); } } void BaseWindow::RemoveMenu() { menu_.Reset(); window_->SetMenu(nullptr); } void BaseWindow::SetParentWindow(v8::Local<v8::Value> value, gin_helper::Arguments* args) { if (IsModal()) { args->ThrowError("Can not be called for modal window"); return; } gin::Handle<BaseWindow> parent; if (value->IsNull() || value->IsUndefined()) { RemoveFromParentChildWindows(); parent_window_.Reset(); window_->SetParentWindow(nullptr); } else if (gin::ConvertFromV8(isolate(), value, &parent)) { RemoveFromParentChildWindows(); parent_window_.Reset(isolate(), value); window_->SetParentWindow(parent->window_.get()); parent->child_windows_.Set(isolate(), weak_map_id(), GetWrapper()); } else { args->ThrowError("Must pass BaseWindow instance or null"); } } void BaseWindow::SetBrowserView( absl::optional<gin::Handle<BrowserView>> browser_view) { ResetBrowserViews(); if (browser_view) AddBrowserView(*browser_view); } void BaseWindow::AddBrowserView(gin::Handle<BrowserView> browser_view) { if (!base::Contains(browser_views_, browser_view.ToV8())) { // If we're reparenting a BrowserView, ensure that it's detached from // its previous owner window. BaseWindow* owner_window = browser_view->owner_window(); if (owner_window) { // iter == browser_views_.end() should imply owner_window != this. DCHECK_NE(owner_window, this); owner_window->RemoveBrowserView(browser_view); browser_view->SetOwnerWindow(nullptr); } window_->AddBrowserView(browser_view->view()); window_->AddDraggableRegionProvider(browser_view.get()); browser_view->SetOwnerWindow(this); browser_views_.emplace_back().Reset(isolate(), browser_view.ToV8()); } } void BaseWindow::RemoveBrowserView(gin::Handle<BrowserView> browser_view) { auto iter = std::find(browser_views_.begin(), browser_views_.end(), browser_view.ToV8()); if (iter != browser_views_.end()) { window_->RemoveDraggableRegionProvider(browser_view.get()); window_->RemoveBrowserView(browser_view->view()); browser_view->SetOwnerWindow(nullptr); iter->Reset(); browser_views_.erase(iter); } } void BaseWindow::SetTopBrowserView(gin::Handle<BrowserView> browser_view, gin_helper::Arguments* args) { BaseWindow* owner_window = browser_view->owner_window(); auto iter = std::find(browser_views_.begin(), browser_views_.end(), browser_view.ToV8()); if (iter == browser_views_.end() || (owner_window && owner_window != this)) { args->ThrowError("Given BrowserView is not attached to the window"); return; } browser_views_.erase(iter); browser_views_.emplace_back().Reset(isolate(), browser_view.ToV8()); window_->SetTopBrowserView(browser_view->view()); } std::string BaseWindow::GetMediaSourceId() const { return window_->GetDesktopMediaID().ToString(); } v8::Local<v8::Value> BaseWindow::GetNativeWindowHandle() { // TODO(MarshallOfSound): Replace once // https://chromium-review.googlesource.com/c/chromium/src/+/1253094/ has // landed NativeWindowHandle handle = window_->GetNativeWindowHandle(); return ToBuffer(isolate(), &handle, sizeof(handle)); } void BaseWindow::SetProgressBar(double progress, gin_helper::Arguments* args) { gin_helper::Dictionary options; std::string mode; args->GetNext(&options) && options.Get("mode", &mode); NativeWindow::ProgressState state = NativeWindow::ProgressState::kNormal; if (mode == "error") state = NativeWindow::ProgressState::kError; else if (mode == "paused") state = NativeWindow::ProgressState::kPaused; else if (mode == "indeterminate") state = NativeWindow::ProgressState::kIndeterminate; else if (mode == "none") state = NativeWindow::ProgressState::kNone; window_->SetProgressBar(progress, state); } void BaseWindow::SetOverlayIcon(const gfx::Image& overlay, const std::string& description) { window_->SetOverlayIcon(overlay, description); } void BaseWindow::SetVisibleOnAllWorkspaces(bool visible, gin_helper::Arguments* args) { gin_helper::Dictionary options; bool visibleOnFullScreen = false; bool skipTransformProcessType = false; if (args->GetNext(&options)) { options.Get("visibleOnFullScreen", &visibleOnFullScreen); options.Get("skipTransformProcessType", &skipTransformProcessType); } return window_->SetVisibleOnAllWorkspaces(visible, visibleOnFullScreen, skipTransformProcessType); } bool BaseWindow::IsVisibleOnAllWorkspaces() { return window_->IsVisibleOnAllWorkspaces(); } void BaseWindow::SetAutoHideCursor(bool auto_hide) { window_->SetAutoHideCursor(auto_hide); } void BaseWindow::SetVibrancy(v8::Isolate* isolate, v8::Local<v8::Value> value) { std::string type = gin::V8ToString(isolate, value); window_->SetVibrancy(type); } void BaseWindow::SetBackgroundMaterial(const std::string& material_type) { window_->SetBackgroundMaterial(material_type); } #if BUILDFLAG(IS_MAC) std::string BaseWindow::GetAlwaysOnTopLevel() { return window_->GetAlwaysOnTopLevel(); } void BaseWindow::SetWindowButtonVisibility(bool visible) { window_->SetWindowButtonVisibility(visible); } bool BaseWindow::GetWindowButtonVisibility() const { return window_->GetWindowButtonVisibility(); } void BaseWindow::SetWindowButtonPosition(absl::optional<gfx::Point> position) { window_->SetWindowButtonPosition(std::move(position)); } absl::optional<gfx::Point> BaseWindow::GetWindowButtonPosition() const { return window_->GetWindowButtonPosition(); } #endif #if BUILDFLAG(IS_MAC) bool BaseWindow::IsHiddenInMissionControl() { return window_->IsHiddenInMissionControl(); } void BaseWindow::SetHiddenInMissionControl(bool hidden) { window_->SetHiddenInMissionControl(hidden); } #endif void BaseWindow::SetTouchBar( std::vector<gin_helper::PersistentDictionary> items) { window_->SetTouchBar(std::move(items)); } void BaseWindow::RefreshTouchBarItem(const std::string& item_id) { window_->RefreshTouchBarItem(item_id); } void BaseWindow::SetEscapeTouchBarItem(gin_helper::PersistentDictionary item) { window_->SetEscapeTouchBarItem(std::move(item)); } void BaseWindow::SelectPreviousTab() { window_->SelectPreviousTab(); } void BaseWindow::SelectNextTab() { window_->SelectNextTab(); } void BaseWindow::ShowAllTabs() { window_->ShowAllTabs(); } void BaseWindow::MergeAllWindows() { window_->MergeAllWindows(); } void BaseWindow::MoveTabToNewWindow() { window_->MoveTabToNewWindow(); } void BaseWindow::ToggleTabBar() { window_->ToggleTabBar(); } void BaseWindow::AddTabbedWindow(NativeWindow* window, gin_helper::Arguments* args) { if (!window_->AddTabbedWindow(window)) args->ThrowError("AddTabbedWindow cannot be called by a window on itself."); } void BaseWindow::SetAutoHideMenuBar(bool auto_hide) { window_->SetAutoHideMenuBar(auto_hide); } bool BaseWindow::IsMenuBarAutoHide() { return window_->IsMenuBarAutoHide(); } void BaseWindow::SetMenuBarVisibility(bool visible) { window_->SetMenuBarVisibility(visible); } bool BaseWindow::IsMenuBarVisible() { return window_->IsMenuBarVisible(); } void BaseWindow::SetAspectRatio(double aspect_ratio, gin_helper::Arguments* args) { gfx::Size extra_size; args->GetNext(&extra_size); window_->SetAspectRatio(aspect_ratio, extra_size); } void BaseWindow::PreviewFile(const std::string& path, gin_helper::Arguments* args) { std::string display_name; if (!args->GetNext(&display_name)) display_name = path; window_->PreviewFile(path, display_name); } void BaseWindow::CloseFilePreview() { window_->CloseFilePreview(); } void BaseWindow::SetGTKDarkThemeEnabled(bool use_dark_theme) { window_->SetGTKDarkThemeEnabled(use_dark_theme); } v8::Local<v8::Value> BaseWindow::GetContentView() const { if (content_view_.IsEmpty()) return v8::Null(isolate()); else return v8::Local<v8::Value>::New(isolate(), content_view_); } v8::Local<v8::Value> BaseWindow::GetParentWindow() const { if (parent_window_.IsEmpty()) return v8::Null(isolate()); else return v8::Local<v8::Value>::New(isolate(), parent_window_); } std::vector<v8::Local<v8::Object>> BaseWindow::GetChildWindows() const { return child_windows_.Values(isolate()); } v8::Local<v8::Value> BaseWindow::GetBrowserView( gin_helper::Arguments* args) const { if (browser_views_.empty()) { return v8::Null(isolate()); } else if (browser_views_.size() == 1) { auto first_view = browser_views_.begin(); return v8::Local<v8::Value>::New(isolate(), *first_view); } else { args->ThrowError( "BrowserWindow have multiple BrowserViews, " "Use getBrowserViews() instead"); return v8::Null(isolate()); } } std::vector<v8::Local<v8::Value>> BaseWindow::GetBrowserViews() const { std::vector<v8::Local<v8::Value>> ret; for (auto const& browser_view : browser_views_) { ret.push_back(v8::Local<v8::Value>::New(isolate(), browser_view)); } return ret; } bool BaseWindow::IsModal() const { return window_->is_modal(); } bool BaseWindow::SetThumbarButtons(gin_helper::Arguments* args) { #if BUILDFLAG(IS_WIN) std::vector<TaskbarHost::ThumbarButton> buttons; if (!args->GetNext(&buttons)) { args->ThrowError(); return false; } auto* window = static_cast<NativeWindowViews*>(window_.get()); return window->taskbar_host().SetThumbarButtons( window_->GetAcceleratedWidget(), buttons); #else return false; #endif } #if defined(TOOLKIT_VIEWS) void BaseWindow::SetIcon(v8::Isolate* isolate, v8::Local<v8::Value> icon) { SetIconImpl(isolate, icon, NativeImage::OnConvertError::kThrow); } void BaseWindow::SetIconImpl(v8::Isolate* isolate, v8::Local<v8::Value> icon, NativeImage::OnConvertError on_error) { NativeImage* native_image = nullptr; if (!NativeImage::TryConvertNativeImage(isolate, icon, &native_image, on_error)) return; #if BUILDFLAG(IS_WIN) static_cast<NativeWindowViews*>(window_.get()) ->SetIcon(native_image->GetHICON(GetSystemMetrics(SM_CXSMICON)), native_image->GetHICON(GetSystemMetrics(SM_CXICON))); #elif BUILDFLAG(IS_LINUX) static_cast<NativeWindowViews*>(window_.get()) ->SetIcon(native_image->image().AsImageSkia()); #endif } #endif #if BUILDFLAG(IS_WIN) bool BaseWindow::HookWindowMessage(UINT message, const MessageCallback& callback) { messages_callback_map_[message] = callback; return true; } void BaseWindow::UnhookWindowMessage(UINT message) { messages_callback_map_.erase(message); } bool BaseWindow::IsWindowMessageHooked(UINT message) { return base::Contains(messages_callback_map_, message); } void BaseWindow::UnhookAllWindowMessages() { messages_callback_map_.clear(); } bool BaseWindow::SetThumbnailClip(const gfx::Rect& region) { auto* window = static_cast<NativeWindowViews*>(window_.get()); return window->taskbar_host().SetThumbnailClip( window_->GetAcceleratedWidget(), region); } bool BaseWindow::SetThumbnailToolTip(const std::string& tooltip) { auto* window = static_cast<NativeWindowViews*>(window_.get()); return window->taskbar_host().SetThumbnailToolTip( window_->GetAcceleratedWidget(), tooltip); } void BaseWindow::SetAppDetails(const gin_helper::Dictionary& options) { std::wstring app_id; base::FilePath app_icon_path; int app_icon_index = 0; std::wstring relaunch_command; std::wstring relaunch_display_name; options.Get("appId", &app_id); options.Get("appIconPath", &app_icon_path); options.Get("appIconIndex", &app_icon_index); options.Get("relaunchCommand", &relaunch_command); options.Get("relaunchDisplayName", &relaunch_display_name); ui::win::SetAppDetailsForWindow(app_id, app_icon_path, app_icon_index, relaunch_command, relaunch_display_name, window_->GetAcceleratedWidget()); } #endif int32_t BaseWindow::GetID() const { return weak_map_id(); } void BaseWindow::ResetBrowserViews() { v8::HandleScope scope(isolate()); for (auto& item : browser_views_) { gin::Handle<BrowserView> browser_view; if (gin::ConvertFromV8(isolate(), v8::Local<v8::Value>::New(isolate(), item), &browser_view) && !browser_view.IsEmpty()) { // There's a chance that the BrowserView may have been reparented - only // reset if the owner window is *this* window. BaseWindow* owner_window = browser_view->owner_window(); DCHECK_EQ(owner_window, this); browser_view->SetOwnerWindow(nullptr); window_->RemoveBrowserView(browser_view->view()); window_->RemoveDraggableRegionProvider(browser_view.get()); browser_view->SetOwnerWindow(nullptr); } item.Reset(); } browser_views_.clear(); } void BaseWindow::RemoveFromParentChildWindows() { if (parent_window_.IsEmpty()) return; gin::Handle<BaseWindow> parent; if (!gin::ConvertFromV8(isolate(), GetParentWindow(), &parent) || parent.IsEmpty()) { return; } parent->child_windows_.Remove(weak_map_id()); } // static gin_helper::WrappableBase* BaseWindow::New(gin_helper::Arguments* args) { gin_helper::Dictionary options = gin::Dictionary::CreateEmpty(args->isolate()); args->GetNext(&options); return new BaseWindow(args, options); } // static void BaseWindow::BuildPrototype(v8::Isolate* isolate, v8::Local<v8::FunctionTemplate> prototype) { prototype->SetClassName(gin::StringToV8(isolate, "BaseWindow")); gin_helper::Destroyable::MakeDestroyable(isolate, prototype); gin_helper::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate()) .SetMethod("setContentView", &BaseWindow::SetContentView) .SetMethod("close", &BaseWindow::Close) .SetMethod("focus", &BaseWindow::Focus) .SetMethod("blur", &BaseWindow::Blur) .SetMethod("isFocused", &BaseWindow::IsFocused) .SetMethod("show", &BaseWindow::Show) .SetMethod("showInactive", &BaseWindow::ShowInactive) .SetMethod("hide", &BaseWindow::Hide) .SetMethod("isVisible", &BaseWindow::IsVisible) .SetMethod("isEnabled", &BaseWindow::IsEnabled) .SetMethod("setEnabled", &BaseWindow::SetEnabled) .SetMethod("maximize", &BaseWindow::Maximize) .SetMethod("unmaximize", &BaseWindow::Unmaximize) .SetMethod("isMaximized", &BaseWindow::IsMaximized) .SetMethod("minimize", &BaseWindow::Minimize) .SetMethod("restore", &BaseWindow::Restore) .SetMethod("isMinimized", &BaseWindow::IsMinimized) .SetMethod("setFullScreen", &BaseWindow::SetFullScreen) .SetMethod("isFullScreen", &BaseWindow::IsFullscreen) .SetMethod("setBounds", &BaseWindow::SetBounds) .SetMethod("getBounds", &BaseWindow::GetBounds) .SetMethod("isNormal", &BaseWindow::IsNormal) .SetMethod("getNormalBounds", &BaseWindow::GetNormalBounds) .SetMethod("setSize", &BaseWindow::SetSize) .SetMethod("getSize", &BaseWindow::GetSize) .SetMethod("setContentBounds", &BaseWindow::SetContentBounds) .SetMethod("getContentBounds", &BaseWindow::GetContentBounds) .SetMethod("setContentSize", &BaseWindow::SetContentSize) .SetMethod("getContentSize", &BaseWindow::GetContentSize) .SetMethod("setMinimumSize", &BaseWindow::SetMinimumSize) .SetMethod("getMinimumSize", &BaseWindow::GetMinimumSize) .SetMethod("setMaximumSize", &BaseWindow::SetMaximumSize) .SetMethod("getMaximumSize", &BaseWindow::GetMaximumSize) .SetMethod("setSheetOffset", &BaseWindow::SetSheetOffset) .SetMethod("moveAbove", &BaseWindow::MoveAbove) .SetMethod("moveTop", &BaseWindow::MoveTop) .SetMethod("setResizable", &BaseWindow::SetResizable) .SetMethod("isResizable", &BaseWindow::IsResizable) .SetMethod("setMovable", &BaseWindow::SetMovable) .SetMethod("isMovable", &BaseWindow::IsMovable) .SetMethod("setMinimizable", &BaseWindow::SetMinimizable) .SetMethod("isMinimizable", &BaseWindow::IsMinimizable) .SetMethod("setMaximizable", &BaseWindow::SetMaximizable) .SetMethod("isMaximizable", &BaseWindow::IsMaximizable) .SetMethod("setFullScreenable", &BaseWindow::SetFullScreenable) .SetMethod("isFullScreenable", &BaseWindow::IsFullScreenable) .SetMethod("setClosable", &BaseWindow::SetClosable) .SetMethod("isClosable", &BaseWindow::IsClosable) .SetMethod("setAlwaysOnTop", &BaseWindow::SetAlwaysOnTop) .SetMethod("isAlwaysOnTop", &BaseWindow::IsAlwaysOnTop) .SetMethod("center", &BaseWindow::Center) .SetMethod("setPosition", &BaseWindow::SetPosition) .SetMethod("getPosition", &BaseWindow::GetPosition) .SetMethod("setTitle", &BaseWindow::SetTitle) .SetMethod("getTitle", &BaseWindow::GetTitle) .SetProperty("accessibleTitle", &BaseWindow::GetAccessibleTitle, &BaseWindow::SetAccessibleTitle) .SetMethod("flashFrame", &BaseWindow::FlashFrame) .SetMethod("setSkipTaskbar", &BaseWindow::SetSkipTaskbar) .SetMethod("setSimpleFullScreen", &BaseWindow::SetSimpleFullScreen) .SetMethod("isSimpleFullScreen", &BaseWindow::IsSimpleFullScreen) .SetMethod("setKiosk", &BaseWindow::SetKiosk) .SetMethod("isKiosk", &BaseWindow::IsKiosk) .SetMethod("isTabletMode", &BaseWindow::IsTabletMode) .SetMethod("setBackgroundColor", &BaseWindow::SetBackgroundColor) .SetMethod("getBackgroundColor", &BaseWindow::GetBackgroundColor) .SetMethod("setHasShadow", &BaseWindow::SetHasShadow) .SetMethod("hasShadow", &BaseWindow::HasShadow) .SetMethod("setOpacity", &BaseWindow::SetOpacity) .SetMethod("getOpacity", &BaseWindow::GetOpacity) .SetMethod("setShape", &BaseWindow::SetShape) .SetMethod("setRepresentedFilename", &BaseWindow::SetRepresentedFilename) .SetMethod("getRepresentedFilename", &BaseWindow::GetRepresentedFilename) .SetMethod("setDocumentEdited", &BaseWindow::SetDocumentEdited) .SetMethod("isDocumentEdited", &BaseWindow::IsDocumentEdited) .SetMethod("setIgnoreMouseEvents", &BaseWindow::SetIgnoreMouseEvents) .SetMethod("setContentProtection", &BaseWindow::SetContentProtection) .SetMethod("setFocusable", &BaseWindow::SetFocusable) .SetMethod("isFocusable", &BaseWindow::IsFocusable) .SetMethod("setMenu", &BaseWindow::SetMenu) .SetMethod("removeMenu", &BaseWindow::RemoveMenu) .SetMethod("setParentWindow", &BaseWindow::SetParentWindow) .SetMethod("setBrowserView", &BaseWindow::SetBrowserView) .SetMethod("addBrowserView", &BaseWindow::AddBrowserView) .SetMethod("removeBrowserView", &BaseWindow::RemoveBrowserView) .SetMethod("setTopBrowserView", &BaseWindow::SetTopBrowserView) .SetMethod("getMediaSourceId", &BaseWindow::GetMediaSourceId) .SetMethod("getNativeWindowHandle", &BaseWindow::GetNativeWindowHandle) .SetMethod("setProgressBar", &BaseWindow::SetProgressBar) .SetMethod("setOverlayIcon", &BaseWindow::SetOverlayIcon) .SetMethod("setVisibleOnAllWorkspaces", &BaseWindow::SetVisibleOnAllWorkspaces) .SetMethod("isVisibleOnAllWorkspaces", &BaseWindow::IsVisibleOnAllWorkspaces) #if BUILDFLAG(IS_MAC) .SetMethod("invalidateShadow", &BaseWindow::InvalidateShadow) .SetMethod("_getAlwaysOnTopLevel", &BaseWindow::GetAlwaysOnTopLevel) .SetMethod("setAutoHideCursor", &BaseWindow::SetAutoHideCursor) #endif .SetMethod("setVibrancy", &BaseWindow::SetVibrancy) .SetMethod("setBackgroundMaterial", &BaseWindow::SetBackgroundMaterial) #if BUILDFLAG(IS_MAC) .SetMethod("isHiddenInMissionControl", &BaseWindow::IsHiddenInMissionControl) .SetMethod("setHiddenInMissionControl", &BaseWindow::SetHiddenInMissionControl) #endif .SetMethod("_setTouchBarItems", &BaseWindow::SetTouchBar) .SetMethod("_refreshTouchBarItem", &BaseWindow::RefreshTouchBarItem) .SetMethod("_setEscapeTouchBarItem", &BaseWindow::SetEscapeTouchBarItem) #if BUILDFLAG(IS_MAC) .SetMethod("selectPreviousTab", &BaseWindow::SelectPreviousTab) .SetMethod("selectNextTab", &BaseWindow::SelectNextTab) .SetMethod("showAllTabs", &BaseWindow::ShowAllTabs) .SetMethod("mergeAllWindows", &BaseWindow::MergeAllWindows) .SetMethod("moveTabToNewWindow", &BaseWindow::MoveTabToNewWindow) .SetMethod("toggleTabBar", &BaseWindow::ToggleTabBar) .SetMethod("addTabbedWindow", &BaseWindow::AddTabbedWindow) .SetMethod("setWindowButtonVisibility", &BaseWindow::SetWindowButtonVisibility) .SetMethod("_getWindowButtonVisibility", &BaseWindow::GetWindowButtonVisibility) .SetMethod("setWindowButtonPosition", &BaseWindow::SetWindowButtonPosition) .SetMethod("getWindowButtonPosition", &BaseWindow::GetWindowButtonPosition) .SetProperty("excludedFromShownWindowsMenu", &BaseWindow::IsExcludedFromShownWindowsMenu, &BaseWindow::SetExcludedFromShownWindowsMenu) #endif .SetMethod("setAutoHideMenuBar", &BaseWindow::SetAutoHideMenuBar) .SetMethod("isMenuBarAutoHide", &BaseWindow::IsMenuBarAutoHide) .SetMethod("setMenuBarVisibility", &BaseWindow::SetMenuBarVisibility) .SetMethod("isMenuBarVisible", &BaseWindow::IsMenuBarVisible) .SetMethod("setAspectRatio", &BaseWindow::SetAspectRatio) .SetMethod("previewFile", &BaseWindow::PreviewFile) .SetMethod("closeFilePreview", &BaseWindow::CloseFilePreview) .SetMethod("getContentView", &BaseWindow::GetContentView) .SetMethod("getParentWindow", &BaseWindow::GetParentWindow) .SetMethod("getChildWindows", &BaseWindow::GetChildWindows) .SetMethod("getBrowserView", &BaseWindow::GetBrowserView) .SetMethod("getBrowserViews", &BaseWindow::GetBrowserViews) .SetMethod("isModal", &BaseWindow::IsModal) .SetMethod("setThumbarButtons", &BaseWindow::SetThumbarButtons) #if defined(TOOLKIT_VIEWS) .SetMethod("setIcon", &BaseWindow::SetIcon) #endif #if BUILDFLAG(IS_WIN) .SetMethod("hookWindowMessage", &BaseWindow::HookWindowMessage) .SetMethod("isWindowMessageHooked", &BaseWindow::IsWindowMessageHooked) .SetMethod("unhookWindowMessage", &BaseWindow::UnhookWindowMessage) .SetMethod("unhookAllWindowMessages", &BaseWindow::UnhookAllWindowMessages) .SetMethod("setThumbnailClip", &BaseWindow::SetThumbnailClip) .SetMethod("setThumbnailToolTip", &BaseWindow::SetThumbnailToolTip) .SetMethod("setAppDetails", &BaseWindow::SetAppDetails) #endif .SetProperty("id", &BaseWindow::GetID); } } // namespace electron::api namespace { using electron::api::BaseWindow; void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused, v8::Local<v8::Context> context, void* priv) { v8::Isolate* isolate = context->GetIsolate(); BaseWindow::SetConstructor(isolate, base::BindRepeating(&BaseWindow::New)); gin_helper::Dictionary constructor(isolate, BaseWindow::GetConstructor(isolate) ->GetFunction(context) .ToLocalChecked()); constructor.SetMethod("fromId", &BaseWindow::FromWeakMapID); constructor.SetMethod("getAllWindows", &BaseWindow::GetAll); gin_helper::Dictionary dict(isolate, exports); dict.Set("BaseWindow", constructor); } } // namespace NODE_LINKED_BINDING_CONTEXT_AWARE(electron_browser_base_window, Initialize)
closed
electron/electron
https://github.com/electron/electron
39,257
[Bug]: BrowserView y-coordinate is not respected on macOS Ventura (13.4.1 and 13.5)
### 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 25.3.2 ### What operating system are you using? macOS ### Operating System Version macOS Ventura (13.4.1 and 13.5) ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version 22.3.18 ### Expected Behavior This code should place a BrowserView on top of the default BrowserWindow, respecting the indicated x and y coordinates: ``` const bwin = new BrowserWindow({ width: 300, height: 500 }) bwin.loadURL('https://electronjs.org/') const bview = new BrowserView() bview.setBounds({ x: 0, y: 0, width: 300, height: 300 }) bwin.addBrowserView(bview) bview.webContents.loadURL('https://github.com/') ``` ### Actual Behavior While the previous code works perfectly on Windows 11, on macOS the y-coordinate of the BrowserView is shifted by the same amount of pixels as the height of BrowserWindow (causing the BrowserView to disappear). So on macOS to correctly position the BrowserView you need to set its y-coordinate to -BrowserViewHeight ``` const bwin = new BrowserWindow({ width: 300, height: 500 }) bwin.loadURL('https://electronjs.org/') const bview = new BrowserView() bview.setBounds({ x: 0, y: -500, // <------- !!! width: 300, height: 300 }) bwin.addBrowserView(bview) bview.webContents.loadURL('https://github.com/') ``` ### Testcase Gist URL https://gist.github.com/360b53fa59bce4a9e49549954bc23444 ### Additional Information _No response_
https://github.com/electron/electron/issues/39257
https://github.com/electron/electron/pull/39605
522bba3dc6b4893fdcf4d1a978fec0204b50d63b
a8999bc529390e7a9a2515bfa23445b34b10860a
2023-07-27T11:07:57Z
c++
2023-08-23T13:55:31Z
shell/browser/api/electron_api_browser_view.h
// Copyright (c) 2017 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_BROWSER_VIEW_H_ #define ELECTRON_SHELL_BROWSER_API_ELECTRON_API_BROWSER_VIEW_H_ #include <memory> #include <string> #include "base/memory/raw_ptr.h" #include "content/public/browser/web_contents_observer.h" #include "gin/handle.h" #include "gin/wrappable.h" #include "shell/browser/draggable_region_provider.h" #include "shell/browser/extended_web_contents_observer.h" #include "shell/browser/native_browser_view.h" #include "shell/browser/native_window.h" #include "shell/common/api/api.mojom.h" #include "shell/common/gin_helper/constructible.h" #include "shell/common/gin_helper/error_thrower.h" #include "shell/common/gin_helper/pinnable.h" namespace gfx { class Rect; } namespace gin_helper { class Dictionary; } namespace electron::api { class WebContents; class BaseWindow; class BrowserView : public gin::Wrappable<BrowserView>, public gin_helper::Constructible<BrowserView>, public gin_helper::Pinnable<BrowserView>, public content::WebContentsObserver, public ExtendedWebContentsObserver, public DraggableRegionProvider { public: // gin_helper::Constructible static gin::Handle<BrowserView> New(gin_helper::ErrorThrower thrower, gin::Arguments* args); static void FillObjectTemplate(v8::Isolate*, v8::Local<v8::ObjectTemplate>); static const char* GetClassName() { return "BrowserView"; } // gin::Wrappable static gin::WrapperInfo kWrapperInfo; const char* GetTypeName() override; WebContents* web_contents() const { return api_web_contents_; } NativeBrowserView* view() const { return view_.get(); } BaseWindow* owner_window() const { return owner_window_.get(); } void SetOwnerWindow(BaseWindow* window); int32_t ID() const { return id_; } int NonClientHitTest(const gfx::Point& point) override; // disable copy BrowserView(const BrowserView&) = delete; BrowserView& operator=(const BrowserView&) = delete; protected: BrowserView(gin::Arguments* args, const gin_helper::Dictionary& options); ~BrowserView() override; // content::WebContentsObserver: void WebContentsDestroyed() override; // ExtendedWebContentsObserver: void OnCloseContents() override; private: void SetAutoResize(AutoResizeFlags flags); void SetBounds(const gfx::Rect& bounds); gfx::Rect GetBounds(); void SetBackgroundColor(const std::string& color_name); v8::Local<v8::Value> GetWebContents(v8::Isolate*); v8::Global<v8::Value> web_contents_; class raw_ptr<WebContents> api_web_contents_ = nullptr; std::unique_ptr<NativeBrowserView> view_; base::WeakPtr<BaseWindow> owner_window_; int32_t id_; }; } // namespace electron::api #endif // ELECTRON_SHELL_BROWSER_API_ELECTRON_API_BROWSER_VIEW_H_
closed
electron/electron
https://github.com/electron/electron
39,257
[Bug]: BrowserView y-coordinate is not respected on macOS Ventura (13.4.1 and 13.5)
### 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 25.3.2 ### What operating system are you using? macOS ### Operating System Version macOS Ventura (13.4.1 and 13.5) ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version 22.3.18 ### Expected Behavior This code should place a BrowserView on top of the default BrowserWindow, respecting the indicated x and y coordinates: ``` const bwin = new BrowserWindow({ width: 300, height: 500 }) bwin.loadURL('https://electronjs.org/') const bview = new BrowserView() bview.setBounds({ x: 0, y: 0, width: 300, height: 300 }) bwin.addBrowserView(bview) bview.webContents.loadURL('https://github.com/') ``` ### Actual Behavior While the previous code works perfectly on Windows 11, on macOS the y-coordinate of the BrowserView is shifted by the same amount of pixels as the height of BrowserWindow (causing the BrowserView to disappear). So on macOS to correctly position the BrowserView you need to set its y-coordinate to -BrowserViewHeight ``` const bwin = new BrowserWindow({ width: 300, height: 500 }) bwin.loadURL('https://electronjs.org/') const bview = new BrowserView() bview.setBounds({ x: 0, y: -500, // <------- !!! width: 300, height: 300 }) bwin.addBrowserView(bview) bview.webContents.loadURL('https://github.com/') ``` ### Testcase Gist URL https://gist.github.com/360b53fa59bce4a9e49549954bc23444 ### Additional Information _No response_
https://github.com/electron/electron/issues/39257
https://github.com/electron/electron/pull/39605
522bba3dc6b4893fdcf4d1a978fec0204b50d63b
a8999bc529390e7a9a2515bfa23445b34b10860a
2023-07-27T11:07:57Z
c++
2023-08-23T13:55:31Z
shell/browser/native_browser_view_mac.mm
// 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/browser/native_browser_view_mac.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/ui/inspectable_web_contents_view.h" #include "skia/ext/skia_utils_mac.h" #include "ui/gfx/geometry/rect.h" // Match view::Views behavior where the view sticks to the top-left origin. const NSAutoresizingMaskOptions kDefaultAutoResizingMask = NSViewMaxXMargin | NSViewMinYMargin; namespace electron { NativeBrowserViewMac::NativeBrowserViewMac( InspectableWebContents* inspectable_web_contents) : NativeBrowserView(inspectable_web_contents) { auto* iwc_view = GetInspectableWebContentsView(); if (!iwc_view) return; auto* view = iwc_view->GetNativeView().GetNativeNSView(); view.autoresizingMask = kDefaultAutoResizingMask; } NativeBrowserViewMac::~NativeBrowserViewMac() = default; void NativeBrowserViewMac::SetAutoResizeFlags(uint8_t flags) { NSAutoresizingMaskOptions autoresizing_mask = kDefaultAutoResizingMask; if (flags & kAutoResizeWidth) { autoresizing_mask |= NSViewWidthSizable; } if (flags & kAutoResizeHeight) { autoresizing_mask |= NSViewHeightSizable; } if (flags & kAutoResizeHorizontal) { autoresizing_mask |= NSViewMaxXMargin | NSViewMinXMargin | NSViewWidthSizable; } if (flags & kAutoResizeVertical) { autoresizing_mask |= NSViewMaxYMargin | NSViewMinYMargin | NSViewHeightSizable; } auto* iwc_view = GetInspectableWebContentsView(); if (!iwc_view) return; auto* view = iwc_view->GetNativeView().GetNativeNSView(); view.autoresizingMask = autoresizing_mask; } void NativeBrowserViewMac::SetBounds(const gfx::Rect& bounds) { auto* iwc_view = GetInspectableWebContentsView(); if (!iwc_view) return; auto* view = iwc_view->GetNativeView().GetNativeNSView(); auto* superview = view.superview; const auto superview_height = superview ? superview.frame.size.height : 0; view.frame = NSMakeRect(bounds.x(), superview_height - bounds.y() - bounds.height(), bounds.width(), bounds.height()); } gfx::Rect NativeBrowserViewMac::GetBounds() { auto* iwc_view = GetInspectableWebContentsView(); if (!iwc_view) return gfx::Rect(); NSView* view = iwc_view->GetNativeView().GetNativeNSView(); const int superview_height = (view.superview) ? view.superview.frame.size.height : 0; return gfx::Rect( view.frame.origin.x, superview_height - view.frame.origin.y - view.frame.size.height, view.frame.size.width, view.frame.size.height); } void NativeBrowserViewMac::SetBackgroundColor(SkColor color) { auto* iwc_view = GetInspectableWebContentsView(); if (!iwc_view) return; auto* view = iwc_view->GetNativeView().GetNativeNSView(); view.wantsLayer = YES; view.layer.backgroundColor = skia::CGColorCreateFromSkColor(color); } // static NativeBrowserView* NativeBrowserView::Create( InspectableWebContents* inspectable_web_contents) { return new NativeBrowserViewMac(inspectable_web_contents); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
39,257
[Bug]: BrowserView y-coordinate is not respected on macOS Ventura (13.4.1 and 13.5)
### 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 25.3.2 ### What operating system are you using? macOS ### Operating System Version macOS Ventura (13.4.1 and 13.5) ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version 22.3.18 ### Expected Behavior This code should place a BrowserView on top of the default BrowserWindow, respecting the indicated x and y coordinates: ``` const bwin = new BrowserWindow({ width: 300, height: 500 }) bwin.loadURL('https://electronjs.org/') const bview = new BrowserView() bview.setBounds({ x: 0, y: 0, width: 300, height: 300 }) bwin.addBrowserView(bview) bview.webContents.loadURL('https://github.com/') ``` ### Actual Behavior While the previous code works perfectly on Windows 11, on macOS the y-coordinate of the BrowserView is shifted by the same amount of pixels as the height of BrowserWindow (causing the BrowserView to disappear). So on macOS to correctly position the BrowserView you need to set its y-coordinate to -BrowserViewHeight ``` const bwin = new BrowserWindow({ width: 300, height: 500 }) bwin.loadURL('https://electronjs.org/') const bview = new BrowserView() bview.setBounds({ x: 0, y: -500, // <------- !!! width: 300, height: 300 }) bwin.addBrowserView(bview) bview.webContents.loadURL('https://github.com/') ``` ### Testcase Gist URL https://gist.github.com/360b53fa59bce4a9e49549954bc23444 ### Additional Information _No response_
https://github.com/electron/electron/issues/39257
https://github.com/electron/electron/pull/39605
522bba3dc6b4893fdcf4d1a978fec0204b50d63b
a8999bc529390e7a9a2515bfa23445b34b10860a
2023-07-27T11:07:57Z
c++
2023-08-23T13:55:31Z
spec/api-browser-view-spec.ts
import { expect } from 'chai'; import * as path from 'node:path'; import { BrowserView, BrowserWindow, screen, webContents } from 'electron/main'; import { closeWindow } from './lib/window-helpers'; import { defer, ifit, startRemoteControlApp } from './lib/spec-helpers'; import { areColorsSimilar, captureScreen, getPixelColor } from './lib/screen-helpers'; import { once } from 'node:events'; describe('BrowserView module', () => { const fixtures = path.resolve(__dirname, 'fixtures'); let w: BrowserWindow; let view: BrowserView; beforeEach(() => { expect(webContents.getAllWebContents()).to.have.length(0); w = new BrowserWindow({ show: false, width: 400, height: 400, webPreferences: { backgroundThrottling: false } }); }); afterEach(async () => { const p = once(w.webContents, 'destroyed'); await closeWindow(w); w = null as any; await p; if (view && view.webContents) { const p = once(view.webContents, 'destroyed'); view.webContents.destroy(); view = null as any; await p; } expect(webContents.getAllWebContents()).to.have.length(0); }); it('sets the correct class name on the prototype', () => { expect(BrowserView.prototype.constructor.name).to.equal('BrowserView'); }); it('can be created with an existing webContents', async () => { const wc = (webContents as typeof ElectronInternal.WebContents).create({ sandbox: true }); await wc.loadURL('about:blank'); view = new BrowserView({ webContents: wc } as any); expect(view.webContents.getURL()).to.equal('about:blank'); }); describe('BrowserView.setBackgroundColor()', () => { it('does not throw for valid args', () => { view = new BrowserView(); view.setBackgroundColor('#000'); }); it('throws for invalid args', () => { view = new BrowserView(); expect(() => { view.setBackgroundColor(null as any); }).to.throw(/conversion failure/); }); // Linux and arm64 platforms (WOA and macOS) do not return any capture sources ifit(process.platform === 'darwin' && process.arch === 'x64')('sets the background color to transparent if none is set', async () => { const display = screen.getPrimaryDisplay(); const WINDOW_BACKGROUND_COLOR = '#55ccbb'; w.show(); w.setBounds(display.bounds); w.setBackgroundColor(WINDOW_BACKGROUND_COLOR); await w.loadURL('about:blank'); view = new BrowserView(); view.setBounds(display.bounds); w.setBrowserView(view); await view.webContents.loadURL('data:text/html,hello there'); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); expect(areColorsSimilar(centerColor, WINDOW_BACKGROUND_COLOR)).to.be.true(); }); // Linux and arm64 platforms (WOA and macOS) do not return any capture sources ifit(process.platform === 'darwin' && process.arch === 'x64')('successfully applies the background color', async () => { const WINDOW_BACKGROUND_COLOR = '#55ccbb'; const VIEW_BACKGROUND_COLOR = '#ff00ff'; const display = screen.getPrimaryDisplay(); w.show(); w.setBounds(display.bounds); w.setBackgroundColor(WINDOW_BACKGROUND_COLOR); await w.loadURL('about:blank'); view = new BrowserView(); view.setBounds(display.bounds); w.setBrowserView(view); w.setBackgroundColor(VIEW_BACKGROUND_COLOR); await view.webContents.loadURL('data:text/html,hello there'); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); expect(areColorsSimilar(centerColor, VIEW_BACKGROUND_COLOR)).to.be.true(); }); }); describe('BrowserView.setAutoResize()', () => { it('does not throw for valid args', () => { view = new BrowserView(); view.setAutoResize({}); view.setAutoResize({ width: true, height: false }); }); it('throws for invalid args', () => { view = new BrowserView(); expect(() => { view.setAutoResize(null as any); }).to.throw(/conversion failure/); }); }); describe('BrowserView.setBounds()', () => { it('does not throw for valid args', () => { view = new BrowserView(); view.setBounds({ x: 0, y: 0, width: 1, height: 1 }); }); it('throws for invalid args', () => { view = new BrowserView(); expect(() => { view.setBounds(null as any); }).to.throw(/conversion failure/); expect(() => { view.setBounds({} as any); }).to.throw(/conversion failure/); }); }); describe('BrowserView.getBounds()', () => { it('returns the current bounds', () => { view = new BrowserView(); const bounds = { x: 10, y: 20, width: 30, height: 40 }; view.setBounds(bounds); expect(view.getBounds()).to.deep.equal(bounds); }); }); describe('BrowserWindow.setBrowserView()', () => { it('does not throw for valid args', () => { view = new BrowserView(); w.setBrowserView(view); }); it('does not throw if called multiple times with same view', () => { view = new BrowserView(); w.setBrowserView(view); w.setBrowserView(view); w.setBrowserView(view); }); }); describe('BrowserWindow.getBrowserView()', () => { it('returns the set view', () => { view = new BrowserView(); w.setBrowserView(view); const view2 = w.getBrowserView(); expect(view2!.webContents.id).to.equal(view.webContents.id); }); it('returns null if none is set', () => { const view = w.getBrowserView(); expect(view).to.be.null('view'); }); }); describe('BrowserWindow.addBrowserView()', () => { it('does not throw for valid args', () => { const view1 = new BrowserView(); defer(() => view1.webContents.destroy()); w.addBrowserView(view1); defer(() => w.removeBrowserView(view1)); const view2 = new BrowserView(); defer(() => view2.webContents.destroy()); w.addBrowserView(view2); defer(() => w.removeBrowserView(view2)); }); it('does not throw if called multiple times with same view', () => { view = new BrowserView(); w.addBrowserView(view); w.addBrowserView(view); w.addBrowserView(view); }); it('does not crash if the BrowserView webContents are destroyed prior to window addition', () => { expect(() => { const view1 = new BrowserView(); view1.webContents.destroy(); w.addBrowserView(view1); }).to.not.throw(); }); it('does not crash if the webContents is destroyed after a URL is loaded', () => { view = new BrowserView(); expect(async () => { view.setBounds({ x: 0, y: 0, width: 400, height: 300 }); await view.webContents.loadURL('data:text/html,hello there'); view.webContents.destroy(); }).to.not.throw(); }); it('can handle BrowserView reparenting', async () => { view = new BrowserView(); w.addBrowserView(view); view.webContents.loadURL('about:blank'); await once(view.webContents, 'did-finish-load'); const w2 = new BrowserWindow({ show: false }); w2.addBrowserView(view); w.close(); view.webContents.loadURL(`file://${fixtures}/pages/blank.html`); await once(view.webContents, 'did-finish-load'); // Clean up - the afterEach hook assumes the webContents on w is still alive. w = new BrowserWindow({ show: false }); w2.close(); w2.destroy(); }); }); describe('BrowserWindow.removeBrowserView()', () => { it('does not throw if called multiple times with same view', () => { expect(() => { view = new BrowserView(); w.addBrowserView(view); w.removeBrowserView(view); w.removeBrowserView(view); }).to.not.throw(); }); it('can be called on a BrowserView with a destroyed webContents', (done) => { view = new BrowserView(); w.addBrowserView(view); view.webContents.on('destroyed', () => { w.removeBrowserView(view); done(); }); view.webContents.loadURL('data:text/html,hello there').then(() => { view.webContents.close(); }); }); }); describe('BrowserWindow.getBrowserViews()', () => { it('returns same views as was added', () => { const view1 = new BrowserView(); defer(() => view1.webContents.destroy()); w.addBrowserView(view1); defer(() => w.removeBrowserView(view1)); const view2 = new BrowserView(); defer(() => view2.webContents.destroy()); w.addBrowserView(view2); defer(() => w.removeBrowserView(view2)); const views = w.getBrowserViews(); expect(views).to.have.lengthOf(2); expect(views[0].webContents.id).to.equal(view1.webContents.id); expect(views[1].webContents.id).to.equal(view2.webContents.id); }); it('persists ordering by z-index', () => { const view1 = new BrowserView(); defer(() => view1.webContents.destroy()); w.addBrowserView(view1); defer(() => w.removeBrowserView(view1)); const view2 = new BrowserView(); defer(() => view2.webContents.destroy()); w.addBrowserView(view2); defer(() => w.removeBrowserView(view2)); w.setTopBrowserView(view1); const views = w.getBrowserViews(); expect(views).to.have.lengthOf(2); expect(views[0].webContents.id).to.equal(view2.webContents.id); expect(views[1].webContents.id).to.equal(view1.webContents.id); }); }); describe('BrowserWindow.setTopBrowserView()', () => { it('should throw an error when a BrowserView is not attached to the window', () => { view = new BrowserView(); expect(() => { w.setTopBrowserView(view); }).to.throw(/is not attached/); }); it('should throw an error when a BrowserView is attached to some other window', () => { view = new BrowserView(); const win2 = new BrowserWindow(); w.addBrowserView(view); view.setBounds({ x: 0, y: 0, width: 100, height: 100 }); win2.addBrowserView(view); expect(() => { w.setTopBrowserView(view); }).to.throw(/is not attached/); win2.close(); win2.destroy(); }); }); describe('BrowserView.webContents.getOwnerBrowserWindow()', () => { it('points to owning window', () => { view = new BrowserView(); expect(view.webContents.getOwnerBrowserWindow()).to.be.null('owner browser window'); w.setBrowserView(view); expect(view.webContents.getOwnerBrowserWindow()).to.equal(w); w.setBrowserView(null); expect(view.webContents.getOwnerBrowserWindow()).to.be.null('owner browser window'); }); }); describe('shutdown behavior', () => { it('does not crash on exit', async () => { const rc = await startRemoteControlApp(); await rc.remotely(() => { const { BrowserView, app } = require('electron'); // eslint-disable-next-line no-new new BrowserView({}); setTimeout(() => { app.quit(); }); }); const [code] = await once(rc.process, 'exit'); expect(code).to.equal(0); }); it('does not crash on exit if added to a browser window', async () => { const rc = await startRemoteControlApp(); await rc.remotely(() => { const { app, BrowserView, BrowserWindow } = require('electron'); const bv = new BrowserView(); bv.webContents.loadURL('about:blank'); const bw = new BrowserWindow({ show: false }); bw.addBrowserView(bv); setTimeout(() => { app.quit(); }); }); const [code] = await once(rc.process, 'exit'); expect(code).to.equal(0); }); it('emits the destroyed event when webContents.close() is called', async () => { view = new BrowserView(); w.setBrowserView(view); await view.webContents.loadFile(path.join(fixtures, 'pages', 'a.html')); view.webContents.close(); await once(view.webContents, 'destroyed'); }); it('emits the destroyed event when window.close() is called', async () => { view = new BrowserView(); w.setBrowserView(view); await view.webContents.loadFile(path.join(fixtures, 'pages', 'a.html')); view.webContents.executeJavaScript('window.close()'); await once(view.webContents, 'destroyed'); }); }); describe('window.open()', () => { it('works in BrowserView', (done) => { view = new BrowserView(); w.setBrowserView(view); view.webContents.setWindowOpenHandler(({ url, frameName }) => { expect(url).to.equal('http://host/'); expect(frameName).to.equal('host'); done(); return { action: 'deny' }; }); view.webContents.loadFile(path.join(fixtures, 'pages', 'window-open.html')); }); }); describe('BrowserView.capturePage(rect)', () => { it('returns a Promise with a Buffer', async () => { view = new BrowserView({ webPreferences: { backgroundThrottling: false } }); w.addBrowserView(view); view.setBounds({ ...w.getBounds(), x: 0, y: 0 }); const image = await view.webContents.capturePage({ x: 0, y: 0, width: 100, height: 100 }); expect(image.isEmpty()).to.equal(true); }); xit('resolves after the window is hidden and capturer count is non-zero', async () => { view = new BrowserView({ webPreferences: { backgroundThrottling: false } }); w.setBrowserView(view); view.setBounds({ ...w.getBounds(), x: 0, y: 0 }); await view.webContents.loadFile(path.join(fixtures, 'pages', 'a.html')); const image = await view.webContents.capturePage(); expect(image.isEmpty()).to.equal(false); }); }); });
closed
electron/electron
https://github.com/electron/electron
39,630
[Bug]: fullscreenable in BrowserWindowConstructorOptions is ignored if resizable flag presents
### 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 25.6.0 ### What operating system are you using? macOS ### Operating System Version 12.3 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior Windows parameters corresponds to constructor options ### Actual Behavior It doesn't ### Testcase Gist URL https://gist.github.com/origin-yaropolk/8770735fda705a6bbc7d2132a30314dc ### Additional Information _No response_
https://github.com/electron/electron/issues/39630
https://github.com/electron/electron/pull/39620
2affecd4dd26b9f0cf2644ec115635559f920480
33e66b5cd02d2b258b956022c482024c74c13b4b
2023-08-23T17:00:10Z
c++
2023-08-24T20:54:08Z
shell/browser/native_window_mac.mm
// 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_mac.h" #include <AvailabilityMacros.h> #include <objc/objc-runtime.h> #include <algorithm> #include <memory> #include <string> #include <utility> #include <vector> #include "base/mac/mac_util.h" #include "base/mac/scoped_cftyperef.h" #include "base/strings/sys_string_conversions.h" #include "components/remote_cocoa/app_shim/native_widget_ns_window_bridge.h" #include "components/remote_cocoa/browser/scoped_cg_window_id.h" #include "content/public/browser/browser_accessibility_state.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/desktop_media_id.h" #include "shell/browser/browser.h" #include "shell/browser/javascript_environment.h" #include "shell/browser/native_browser_view_mac.h" #include "shell/browser/ui/cocoa/electron_native_widget_mac.h" #include "shell/browser/ui/cocoa/electron_ns_window.h" #include "shell/browser/ui/cocoa/electron_ns_window_delegate.h" #include "shell/browser/ui/cocoa/electron_preview_item.h" #include "shell/browser/ui/cocoa/electron_touch_bar.h" #include "shell/browser/ui/cocoa/root_view_mac.h" #include "shell/browser/ui/cocoa/window_buttons_proxy.h" #include "shell/browser/ui/drag_util.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/window_list.h" #include "shell/common/gin_converters/gfx_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/node_includes.h" #include "shell/common/options_switches.h" #include "shell/common/process_util.h" #include "skia/ext/skia_utils_mac.h" #include "third_party/skia/include/core/SkRegion.h" #include "third_party/webrtc/modules/desktop_capture/mac/window_list_utils.h" #include "ui/base/hit_test.h" #include "ui/display/screen.h" #include "ui/gfx/skia_util.h" #include "ui/gl/gpu_switching_manager.h" #include "ui/views/background.h" #include "ui/views/cocoa/native_widget_mac_ns_window_host.h" #include "ui/views/widget/widget.h" #include "ui/views/window/native_frame_view_mac.h" @interface ElectronProgressBar : NSProgressIndicator @end @implementation ElectronProgressBar - (void)drawRect:(NSRect)dirtyRect { if (self.style != NSProgressIndicatorStyleBar) return; // Draw edges of rounded rect. NSRect rect = NSInsetRect([self bounds], 1.0, 1.0); CGFloat radius = rect.size.height / 2; NSBezierPath* bezier_path = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [bezier_path setLineWidth:2.0]; [[NSColor grayColor] set]; [bezier_path stroke]; // Fill the rounded rect. rect = NSInsetRect(rect, 2.0, 2.0); radius = rect.size.height / 2; bezier_path = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [bezier_path setLineWidth:1.0]; [bezier_path addClip]; // Calculate the progress width. rect.size.width = floor(rect.size.width * ([self doubleValue] / [self maxValue])); // Fill the progress bar with color blue. [[NSColor colorWithSRGBRed:0.2 green:0.6 blue:1 alpha:1] set]; NSRectFill(rect); } @end namespace gin { template <> struct Converter<electron::NativeWindowMac::VisualEffectState> { static bool FromV8(v8::Isolate* isolate, v8::Handle<v8::Value> val, electron::NativeWindowMac::VisualEffectState* out) { using VisualEffectState = electron::NativeWindowMac::VisualEffectState; std::string visual_effect_state; if (!ConvertFromV8(isolate, val, &visual_effect_state)) return false; if (visual_effect_state == "followWindow") { *out = VisualEffectState::kFollowWindow; } else if (visual_effect_state == "active") { *out = VisualEffectState::kActive; } else if (visual_effect_state == "inactive") { *out = VisualEffectState::kInactive; } else { return false; } return true; } }; } // namespace gin namespace electron { namespace { bool IsFramelessWindow(NSView* view) { NSWindow* nswindow = [view window]; if (![nswindow respondsToSelector:@selector(shell)]) return false; NativeWindow* window = [static_cast<ElectronNSWindow*>(nswindow) shell]; return window && !window->has_frame(); } IMP original_set_frame_size = nullptr; IMP original_view_did_move_to_superview = nullptr; // This method is directly called by NSWindow during a window resize on OSX // 10.10.0, beta 2. We must override it to prevent the content view from // shrinking. void SetFrameSize(NSView* self, SEL _cmd, NSSize size) { if (!IsFramelessWindow(self)) { auto original = reinterpret_cast<decltype(&SetFrameSize)>(original_set_frame_size); return original(self, _cmd, size); } // For frameless window, resize the view to cover full window. if ([self superview]) size = [[self superview] bounds].size; auto super_impl = reinterpret_cast<decltype(&SetFrameSize)>( [[self superclass] instanceMethodForSelector:_cmd]); super_impl(self, _cmd, size); } // The contentView gets moved around during certain full-screen operations. // This is less than ideal, and should eventually be removed. void ViewDidMoveToSuperview(NSView* self, SEL _cmd) { if (!IsFramelessWindow(self)) { // [BridgedContentView viewDidMoveToSuperview]; auto original = reinterpret_cast<decltype(&ViewDidMoveToSuperview)>( original_view_did_move_to_superview); if (original) original(self, _cmd); return; } [self setFrame:[[self superview] bounds]]; } // -[NSWindow orderWindow] does not handle reordering for children // windows. Their order is fixed to the attachment order (the last attached // window is on the top). Therefore, work around it by re-parenting in our // desired order. void ReorderChildWindowAbove(NSWindow* child_window, NSWindow* other_window) { NSWindow* parent = [child_window parentWindow]; DCHECK(parent); // `ordered_children` sorts children windows back to front. NSArray<NSWindow*>* children = [[child_window parentWindow] childWindows]; std::vector<std::pair<NSInteger, NSWindow*>> ordered_children; for (NSWindow* child in children) ordered_children.push_back({[child orderedIndex], child}); std::sort(ordered_children.begin(), ordered_children.end(), std::greater<>()); // If `other_window` is nullptr, place `child_window` in front of // all other children windows. if (other_window == nullptr) other_window = ordered_children.back().second; if (child_window == other_window) return; for (NSWindow* child in children) [parent removeChildWindow:child]; const bool relative_to_parent = parent == other_window; if (relative_to_parent) [parent addChildWindow:child_window ordered:NSWindowAbove]; // Re-parent children windows in the desired order. for (auto [ordered_index, child] : ordered_children) { if (child != child_window && child != other_window) { [parent addChildWindow:child ordered:NSWindowAbove]; } else if (child == other_window && !relative_to_parent) { [parent addChildWindow:other_window ordered:NSWindowAbove]; [parent addChildWindow:child_window ordered:NSWindowAbove]; } } } } // namespace NativeWindowMac::NativeWindowMac(const gin_helper::Dictionary& options, NativeWindow* parent) : NativeWindow(options, parent), root_view_(new RootViewMac(this)) { ui::NativeTheme::GetInstanceForNativeUi()->AddObserver(this); display::Screen::GetScreen()->AddObserver(this); int width = 800, height = 600; options.Get(options::kWidth, &width); options.Get(options::kHeight, &height); NSRect main_screen_rect = [[[NSScreen screens] firstObject] frame]; gfx::Rect bounds(round((NSWidth(main_screen_rect) - width) / 2), round((NSHeight(main_screen_rect) - height) / 2), width, height); bool resizable = true; options.Get(options::kResizable, &resizable); options.Get(options::kZoomToPageWidth, &zoom_to_page_width_); options.Get(options::kSimpleFullScreen, &always_simple_fullscreen_); options.GetOptional(options::kTrafficLightPosition, &traffic_light_position_); options.Get(options::kVisualEffectState, &visual_effect_state_); if (options.Has(options::kFullscreenWindowTitle)) { EmitWarning( node::Environment::GetCurrent(JavascriptEnvironment::GetIsolate()), "\"fullscreenWindowTitle\" option has been deprecated and is " "no-op now.", "electron"); } bool minimizable = true; options.Get(options::kMinimizable, &minimizable); bool maximizable = true; options.Get(options::kMaximizable, &maximizable); bool closable = true; options.Get(options::kClosable, &closable); std::string tabbingIdentifier; options.Get(options::kTabbingIdentifier, &tabbingIdentifier); std::string windowType; options.Get(options::kType, &windowType); bool hiddenInMissionControl = false; options.Get(options::kHiddenInMissionControl, &hiddenInMissionControl); bool useStandardWindow = true; // eventually deprecate separate "standardWindow" option in favor of // standard / textured window types options.Get(options::kStandardWindow, &useStandardWindow); if (windowType == "textured") { useStandardWindow = false; } // The window without titlebar is treated the same with frameless window. if (title_bar_style_ != TitleBarStyle::kNormal) set_has_frame(false); NSUInteger styleMask = NSWindowStyleMaskTitled; // The NSWindowStyleMaskFullSizeContentView style removes rounded corners // for frameless window. bool rounded_corner = true; options.Get(options::kRoundedCorners, &rounded_corner); if (!rounded_corner && !has_frame()) styleMask = NSWindowStyleMaskBorderless; if (minimizable) styleMask |= NSWindowStyleMaskMiniaturizable; if (closable) styleMask |= NSWindowStyleMaskClosable; if (resizable) styleMask |= NSWindowStyleMaskResizable; if (!useStandardWindow || transparent() || !has_frame()) styleMask |= NSWindowStyleMaskTexturedBackground; // Create views::Widget and assign window_ with it. // TODO(zcbenz): Get rid of the window_ in future. 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.native_widget = new ElectronNativeWidgetMac(this, windowType, styleMask, widget()); widget()->Init(std::move(params)); SetCanResize(resizable); window_ = static_cast<ElectronNSWindow*>( widget()->GetNativeWindow().GetNativeNSWindow()); RegisterDeleteDelegateCallback(base::BindOnce( [](NativeWindowMac* window) { if (window->window_) window->window_ = nil; if (window->buttons_proxy_) window->buttons_proxy_ = nil; }, this)); [window_ setEnableLargerThanScreen:enable_larger_than_screen()]; window_delegate_ = [[ElectronNSWindowDelegate alloc] initWithShell:this]; [window_ setDelegate:window_delegate_]; // Only use native parent window for non-modal windows. if (parent && !is_modal()) { SetParentWindow(parent); } if (transparent()) { // Setting the background color to clear will also hide the shadow. [window_ setBackgroundColor:[NSColor clearColor]]; } if (windowType == "desktop") { [window_ setLevel:kCGDesktopWindowLevel - 1]; [window_ setDisableKeyOrMainWindow:YES]; [window_ setCollectionBehavior:(NSWindowCollectionBehaviorCanJoinAllSpaces | NSWindowCollectionBehaviorStationary | NSWindowCollectionBehaviorIgnoresCycle)]; } if (windowType == "panel") { [window_ setLevel:NSFloatingWindowLevel]; } bool focusable; if (options.Get(options::kFocusable, &focusable) && !focusable) [window_ setDisableKeyOrMainWindow:YES]; if (transparent() || !has_frame()) { // Don't show title bar. [window_ setTitlebarAppearsTransparent:YES]; [window_ setTitleVisibility:NSWindowTitleHidden]; // Remove non-transparent corners, see // https://github.com/electron/electron/issues/517. [window_ setOpaque:NO]; // Show window buttons if titleBarStyle is not "normal". if (title_bar_style_ == TitleBarStyle::kNormal) { InternalSetWindowButtonVisibility(false); } else { buttons_proxy_ = [[WindowButtonsProxy alloc] initWithWindow:window_]; [buttons_proxy_ setHeight:titlebar_overlay_height()]; if (traffic_light_position_) { [buttons_proxy_ setMargin:*traffic_light_position_]; } else if (title_bar_style_ == TitleBarStyle::kHiddenInset) { // For macOS >= 11, while this value does not match official macOS apps // like Safari or Notes, it matches titleBarStyle's old implementation // before Electron <= 12. [buttons_proxy_ setMargin:gfx::Point(12, 11)]; } if (title_bar_style_ == TitleBarStyle::kCustomButtonsOnHover) { [buttons_proxy_ setShowOnHover:YES]; } else { // customButtonsOnHover does not show buttons initially. InternalSetWindowButtonVisibility(true); } } } // Create a tab only if tabbing identifier is specified and window has // a native title bar. if (tabbingIdentifier.empty() || transparent() || !has_frame()) { [window_ setTabbingMode:NSWindowTabbingModeDisallowed]; } else { [window_ setTabbingIdentifier:base::SysUTF8ToNSString(tabbingIdentifier)]; } // Resize to content bounds. bool use_content_size = false; options.Get(options::kUseContentSize, &use_content_size); if (!has_frame() || use_content_size) SetContentSize(gfx::Size(width, height)); // Enable the NSView to accept first mouse event. bool acceptsFirstMouse = false; options.Get(options::kAcceptFirstMouse, &acceptsFirstMouse); [window_ setAcceptsFirstMouse:acceptsFirstMouse]; // Disable auto-hiding cursor. bool disableAutoHideCursor = false; options.Get(options::kDisableAutoHideCursor, &disableAutoHideCursor); [window_ setDisableAutoHideCursor:disableAutoHideCursor]; SetHiddenInMissionControl(hiddenInMissionControl); // Set maximizable state last to ensure zoom button does not get reset // by calls to other APIs. SetMaximizable(maximizable); // Default content view. SetContentView(new views::View()); AddContentViewLayers(); UpdateWindowOriginalFrame(); original_level_ = [window_ level]; } NativeWindowMac::~NativeWindowMac() = default; void NativeWindowMac::SetContentView(views::View* view) { views::View* root_view = GetContentsView(); if (content_view()) root_view->RemoveChildView(content_view()); set_content_view(view); root_view->AddChildView(content_view()); root_view->Layout(); } void NativeWindowMac::Close() { if (!IsClosable()) { WindowList::WindowCloseCancelled(this); return; } if (fullscreen_transition_state() != FullScreenTransitionState::kNone) { SetHasDeferredWindowClose(true); return; } // Ensure we're detached from the parent window before closing. RemoveChildFromParentWindow(); while (!child_windows_.empty()) { auto* child = child_windows_.back(); child->RemoveChildFromParentWindow(); } // If a sheet is attached to the window when we call // [window_ performClose:nil], the window won't close properly // even after the user has ended the sheet. // Ensure it's closed before calling [window_ performClose:nil]. if ([window_ attachedSheet]) [window_ endSheet:[window_ attachedSheet]]; [window_ performClose:nil]; // Closing a sheet doesn't trigger windowShouldClose, // so we need to manually call it ourselves here. if (is_modal() && parent() && IsVisible()) { NotifyWindowCloseButtonClicked(); } } void NativeWindowMac::CloseImmediately() { // Ensure we're detached from the parent window before closing. RemoveChildFromParentWindow(); while (!child_windows_.empty()) { auto* child = child_windows_.back(); child->RemoveChildFromParentWindow(); } [window_ close]; } void NativeWindowMac::Focus(bool focus) { if (!IsVisible()) return; if (focus) { [[NSApplication sharedApplication] activateIgnoringOtherApps:NO]; [window_ makeKeyAndOrderFront:nil]; } else { [window_ orderOut:nil]; [window_ orderBack:nil]; } } bool NativeWindowMac::IsFocused() { return [window_ isKeyWindow]; } void NativeWindowMac::Show() { if (is_modal() && parent()) { NSWindow* window = parent()->GetNativeWindow().GetNativeNSWindow(); if ([window_ sheetParent] == nil) [window beginSheet:window_ completionHandler:^(NSModalResponse){ }]; return; } // Reattach the window to the parent to actually show it. if (parent()) InternalSetParentWindow(parent(), true); // This method is supposed to put focus on window, however if the app does not // have focus then "makeKeyAndOrderFront" will only show the window. [NSApp activateIgnoringOtherApps:YES]; [window_ makeKeyAndOrderFront:nil]; } void NativeWindowMac::ShowInactive() { // Reattach the window to the parent to actually show it. if (parent()) InternalSetParentWindow(parent(), true); [window_ orderFrontRegardless]; } void NativeWindowMac::Hide() { // If a sheet is attached to the window when we call [window_ orderOut:nil], // the sheet won't be able to show again on the same window. // Ensure it's closed before calling [window_ orderOut:nil]. if ([window_ attachedSheet]) [window_ endSheet:[window_ attachedSheet]]; if (is_modal() && parent()) { [window_ orderOut:nil]; [parent()->GetNativeWindow().GetNativeNSWindow() endSheet:window_]; return; } DetachChildren(); // Detach the window from the parent before. if (parent()) InternalSetParentWindow(parent(), false); [window_ orderOut:nil]; } bool NativeWindowMac::IsVisible() { bool occluded = [window_ occlusionState] == NSWindowOcclusionStateVisible; return [window_ isVisible] && !occluded && !IsMinimized(); } bool NativeWindowMac::IsEnabled() { return [window_ attachedSheet] == nil; } void NativeWindowMac::SetEnabled(bool enable) { if (!enable) { NSRect frame = [window_ frame]; NSWindow* window = [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, frame.size.width, frame.size.height) styleMask:NSWindowStyleMaskTitled backing:NSBackingStoreBuffered defer:NO]; [window setAlphaValue:0.5]; [window_ beginSheet:window completionHandler:^(NSModalResponse returnCode) { NSLog(@"main window disabled"); return; }]; } else if ([window_ attachedSheet]) { [window_ endSheet:[window_ attachedSheet]]; } } void NativeWindowMac::Maximize() { const bool is_visible = [window_ isVisible]; if (IsMaximized()) { if (!is_visible) ShowInactive(); return; } // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); [window_ zoom:nil]; if (!is_visible) { ShowInactive(); NotifyWindowMaximize(); } } void NativeWindowMac::Unmaximize() { // Bail if the last user set bounds were the same size as the window // screen (e.g. the user set the window to maximized via setBounds) // // Per docs during zoom: // > If there’s no saved user state because there has been no previous // > zoom,the size and location of the window don’t change. // // However, in classic Apple fashion, this is not the case in practice, // and the frame inexplicably becomes very tiny. We should prevent // zoom from being called if the window is being unmaximized and its // unmaximized window bounds are themselves functionally maximized. if (!IsMaximized() || user_set_bounds_maximized_) return; [window_ zoom:nil]; } bool NativeWindowMac::IsMaximized() { // It's possible for [window_ isZoomed] to be true // when the window is minimized or fullscreened. if (IsMinimized() || IsFullscreen()) return false; if (HasStyleMask(NSWindowStyleMaskResizable) != 0) return [window_ isZoomed]; NSRect rectScreen = GetAspectRatio() > 0.0 ? default_frame_for_zoom() : [[NSScreen mainScreen] visibleFrame]; return NSEqualRects([window_ frame], rectScreen); } void NativeWindowMac::Minimize() { if (IsMinimized()) return; // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); [window_ miniaturize:nil]; } void NativeWindowMac::Restore() { [window_ deminiaturize:nil]; } bool NativeWindowMac::IsMinimized() { return [window_ isMiniaturized]; } bool NativeWindowMac::HandleDeferredClose() { if (has_deferred_window_close_) { SetHasDeferredWindowClose(false); Close(); return true; } return false; } void NativeWindowMac::RemoveChildWindow(NativeWindow* child) { child_windows_.remove_if([&child](NativeWindow* w) { return (w == child); }); [window_ removeChildWindow:child->GetNativeWindow().GetNativeNSWindow()]; } void NativeWindowMac::RemoveChildFromParentWindow() { if (parent() && !is_modal()) { parent()->RemoveChildWindow(this); NativeWindow::SetParentWindow(nullptr); } } void NativeWindowMac::AttachChildren() { for (auto* child : child_windows_) { auto* child_nswindow = child->GetNativeWindow().GetNativeNSWindow(); if ([child_nswindow parentWindow] == window_) continue; // Attaching a window as a child window resets its window level, so // save and restore it afterwards. NSInteger level = window_.level; [window_ addChildWindow:child_nswindow ordered:NSWindowAbove]; [window_ setLevel:level]; } } void NativeWindowMac::DetachChildren() { DCHECK(child_windows_.size() == [[window_ childWindows] count]); // Hide all children before hiding/minimizing the window. // NativeWidgetNSWindowBridge::NotifyVisibilityChangeDown() // will DCHECK otherwise. for (auto* child : child_windows_) { [child->GetNativeWindow().GetNativeNSWindow() orderOut:nil]; } } void NativeWindowMac::SetFullScreen(bool fullscreen) { if (!has_frame() && !HasStyleMask(NSWindowStyleMaskTitled)) return; // [NSWindow -toggleFullScreen] is an asynchronous operation, which means // that it's possible to call it while a fullscreen transition is currently // in process. This can create weird behavior (incl. phantom windows), // so we want to schedule a transition for when the current one has completed. if (fullscreen_transition_state() != FullScreenTransitionState::kNone) { if (!pending_transitions_.empty()) { bool last_pending = pending_transitions_.back(); // Only push new transitions if they're different than the last transition // in the queue. if (last_pending != fullscreen) pending_transitions_.push(fullscreen); } else { pending_transitions_.push(fullscreen); } return; } if (fullscreen == IsFullscreen() || !IsFullScreenable()) return; // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); // This needs to be set here because it can be the case that // SetFullScreen is called by a user before windowWillEnterFullScreen // or windowWillExitFullScreen are invoked, and so a potential transition // could be dropped. fullscreen_transition_state_ = fullscreen ? FullScreenTransitionState::kEntering : FullScreenTransitionState::kExiting; [window_ toggleFullScreenMode:nil]; } bool NativeWindowMac::IsFullscreen() const { return HasStyleMask(NSWindowStyleMaskFullScreen); } void NativeWindowMac::SetBounds(const gfx::Rect& bounds, bool animate) { // Do nothing if in fullscreen mode. if (IsFullscreen()) return; // Check size constraints since setFrame does not check it. gfx::Size size = bounds.size(); size.SetToMax(GetMinimumSize()); gfx::Size max_size = GetMaximumSize(); if (!max_size.IsEmpty()) size.SetToMin(max_size); NSRect cocoa_bounds = NSMakeRect(bounds.x(), 0, size.width(), size.height()); // Flip coordinates based on the primary screen. NSScreen* screen = [[NSScreen screens] firstObject]; cocoa_bounds.origin.y = NSHeight([screen frame]) - size.height() - bounds.y(); [window_ setFrame:cocoa_bounds display:YES animate:animate]; user_set_bounds_maximized_ = IsMaximized() ? true : false; UpdateWindowOriginalFrame(); } gfx::Rect NativeWindowMac::GetBounds() { NSRect frame = [window_ frame]; gfx::Rect bounds(frame.origin.x, 0, NSWidth(frame), NSHeight(frame)); NSScreen* screen = [[NSScreen screens] firstObject]; bounds.set_y(NSHeight([screen frame]) - NSMaxY(frame)); return bounds; } bool NativeWindowMac::IsNormal() { return NativeWindow::IsNormal() && !IsSimpleFullScreen(); } gfx::Rect NativeWindowMac::GetNormalBounds() { if (IsNormal()) { return GetBounds(); } NSRect frame = original_frame_; gfx::Rect bounds(frame.origin.x, 0, NSWidth(frame), NSHeight(frame)); NSScreen* screen = [[NSScreen screens] firstObject]; bounds.set_y(NSHeight([screen frame]) - NSMaxY(frame)); return bounds; // Works on OS_WIN ! // return widget()->GetRestoredBounds(); } void NativeWindowMac::SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints) { auto convertSize = [this](const gfx::Size& size) { // Our frameless window still has titlebar attached, so setting contentSize // will result in actual content size being larger. if (!has_frame()) { NSRect frame = NSMakeRect(0, 0, size.width(), size.height()); NSRect content = [window_ originalContentRectForFrameRect:frame]; return content.size; } else { return NSMakeSize(size.width(), size.height()); } }; NSView* content = [window_ contentView]; if (size_constraints.HasMinimumSize()) { NSSize min_size = convertSize(size_constraints.GetMinimumSize()); [window_ setContentMinSize:[content convertSize:min_size toView:nil]]; } if (size_constraints.HasMaximumSize()) { NSSize max_size = convertSize(size_constraints.GetMaximumSize()); [window_ setContentMaxSize:[content convertSize:max_size toView:nil]]; } NativeWindow::SetContentSizeConstraints(size_constraints); } bool NativeWindowMac::MoveAbove(const std::string& sourceId) { const content::DesktopMediaID id = content::DesktopMediaID::Parse(sourceId); if (id.type != content::DesktopMediaID::TYPE_WINDOW) return false; // Check if the window source is valid. const CGWindowID window_id = id.id; if (!webrtc::GetWindowOwnerPid(window_id)) return false; if (!parent() || is_modal()) { [window_ orderWindow:NSWindowAbove relativeTo:window_id]; } else { NSWindow* other_window = [NSApp windowWithWindowNumber:window_id]; ReorderChildWindowAbove(window_, other_window); } return true; } void NativeWindowMac::MoveTop() { if (!parent() || is_modal()) { [window_ orderWindow:NSWindowAbove relativeTo:0]; } else { ReorderChildWindowAbove(window_, nullptr); } } void NativeWindowMac::SetResizable(bool resizable) { ScopedDisableResize disable_resize; SetStyleMask(resizable, NSWindowStyleMaskResizable); // Right now, resizable and fullscreenable are decoupled in // documentation and on Windows/Linux. Chromium disables // fullscreenability if resizability is false on macOS as well // as disabling the maximize traffic light unless the window // is both resizable and maximizable. To work around this, we want // to match behavior on other platforms by disabiliting the maximize // button but keeping fullscreenability enabled. // TODO(codebytere): refactor this once we have a better solution. SetCanResize(resizable); if (!resizable) { SetFullScreenable(true); [[window_ standardWindowButton:NSWindowZoomButton] setEnabled:false]; } else { SetFullScreenable(true); [[window_ standardWindowButton:NSWindowZoomButton] setEnabled:IsFullScreenable()]; } } bool NativeWindowMac::IsResizable() { bool in_fs_transition = fullscreen_transition_state() != FullScreenTransitionState::kNone; bool has_rs_mask = HasStyleMask(NSWindowStyleMaskResizable); return has_rs_mask && !IsFullscreen() && !in_fs_transition; } void NativeWindowMac::SetMovable(bool movable) { [window_ setMovable:movable]; } bool NativeWindowMac::IsMovable() { return [window_ isMovable]; } void NativeWindowMac::SetMinimizable(bool minimizable) { SetStyleMask(minimizable, NSWindowStyleMaskMiniaturizable); } bool NativeWindowMac::IsMinimizable() { return HasStyleMask(NSWindowStyleMaskMiniaturizable); } void NativeWindowMac::SetMaximizable(bool maximizable) { maximizable_ = maximizable; [[window_ standardWindowButton:NSWindowZoomButton] setEnabled:maximizable]; } bool NativeWindowMac::IsMaximizable() { return [[window_ standardWindowButton:NSWindowZoomButton] isEnabled]; } void NativeWindowMac::SetFullScreenable(bool fullscreenable) { SetCollectionBehavior(fullscreenable, NSWindowCollectionBehaviorFullScreenPrimary); // On EL Capitan this flag is required to hide fullscreen button. SetCollectionBehavior(!fullscreenable, NSWindowCollectionBehaviorFullScreenAuxiliary); } bool NativeWindowMac::IsFullScreenable() { NSUInteger collectionBehavior = [window_ collectionBehavior]; return collectionBehavior & NSWindowCollectionBehaviorFullScreenPrimary; } void NativeWindowMac::SetClosable(bool closable) { SetStyleMask(closable, NSWindowStyleMaskClosable); } bool NativeWindowMac::IsClosable() { return HasStyleMask(NSWindowStyleMaskClosable); } void NativeWindowMac::SetAlwaysOnTop(ui::ZOrderLevel z_order, const std::string& level_name, int relative_level) { if (z_order == ui::ZOrderLevel::kNormal) { SetWindowLevel(NSNormalWindowLevel); return; } int level = NSNormalWindowLevel; if (level_name == "floating") { level = NSFloatingWindowLevel; } else if (level_name == "torn-off-menu") { level = NSTornOffMenuWindowLevel; } else if (level_name == "modal-panel") { level = NSModalPanelWindowLevel; } else if (level_name == "main-menu") { level = NSMainMenuWindowLevel; } else if (level_name == "status") { level = NSStatusWindowLevel; } else if (level_name == "pop-up-menu") { level = NSPopUpMenuWindowLevel; } else if (level_name == "screen-saver") { level = NSScreenSaverWindowLevel; } SetWindowLevel(level + relative_level); } std::string NativeWindowMac::GetAlwaysOnTopLevel() { std::string level_name = "normal"; int level = [window_ level]; if (level == NSFloatingWindowLevel) { level_name = "floating"; } else if (level == NSTornOffMenuWindowLevel) { level_name = "torn-off-menu"; } else if (level == NSModalPanelWindowLevel) { level_name = "modal-panel"; } else if (level == NSMainMenuWindowLevel) { level_name = "main-menu"; } else if (level == NSStatusWindowLevel) { level_name = "status"; } else if (level == NSPopUpMenuWindowLevel) { level_name = "pop-up-menu"; } else if (level == NSScreenSaverWindowLevel) { level_name = "screen-saver"; } return level_name; } void NativeWindowMac::SetWindowLevel(int unbounded_level) { int level = std::min( std::max(unbounded_level, CGWindowLevelForKey(kCGMinimumWindowLevelKey)), CGWindowLevelForKey(kCGMaximumWindowLevelKey)); ui::ZOrderLevel z_order_level = level == NSNormalWindowLevel ? ui::ZOrderLevel::kNormal : ui::ZOrderLevel::kFloatingWindow; bool did_z_order_level_change = z_order_level != GetZOrderLevel(); was_maximizable_ = IsMaximizable(); // We need to explicitly keep the NativeWidget up to date, since it stores the // window level in a local variable, rather than reading it from the NSWindow. // Unfortunately, it results in a second setLevel call. It's not ideal, but we // don't expect this to cause any user-visible jank. widget()->SetZOrderLevel(z_order_level); [window_ setLevel:level]; // Set level will make the zoom button revert to default, probably // a bug of Cocoa or macOS. SetMaximizable(was_maximizable_); // This must be notified at the very end or IsAlwaysOnTop // will not yet have been updated to reflect the new status if (did_z_order_level_change) NativeWindow::NotifyWindowAlwaysOnTopChanged(); } ui::ZOrderLevel NativeWindowMac::GetZOrderLevel() { return widget()->GetZOrderLevel(); } void NativeWindowMac::Center() { [window_ center]; } void NativeWindowMac::Invalidate() { [[window_ contentView] setNeedsDisplay:YES]; } void NativeWindowMac::SetTitle(const std::string& title) { [window_ setTitle:base::SysUTF8ToNSString(title)]; if (buttons_proxy_) [buttons_proxy_ redraw]; } std::string NativeWindowMac::GetTitle() { return base::SysNSStringToUTF8([window_ title]); } void NativeWindowMac::FlashFrame(bool flash) { if (flash) { attention_request_id_ = [NSApp requestUserAttention:NSInformationalRequest]; } else { [NSApp cancelUserAttentionRequest:attention_request_id_]; attention_request_id_ = 0; } } void NativeWindowMac::SetSkipTaskbar(bool skip) {} bool NativeWindowMac::IsExcludedFromShownWindowsMenu() { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); return [window isExcludedFromWindowsMenu]; } void NativeWindowMac::SetExcludedFromShownWindowsMenu(bool excluded) { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); [window setExcludedFromWindowsMenu:excluded]; } void NativeWindowMac::OnDisplayMetricsChanged(const display::Display& display, uint32_t changed_metrics) { // We only want to force screen recalibration if we're in simpleFullscreen // mode. if (!is_simple_fullscreen_) return; content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&NativeWindow::UpdateFrame, GetWeakPtr())); } void NativeWindowMac::SetSimpleFullScreen(bool simple_fullscreen) { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); if (simple_fullscreen && !is_simple_fullscreen_) { is_simple_fullscreen_ = true; // Take note of the current window size and level if (IsNormal()) { UpdateWindowOriginalFrame(); original_level_ = [window_ level]; } simple_fullscreen_options_ = [NSApp currentSystemPresentationOptions]; simple_fullscreen_mask_ = [window styleMask]; // We can simulate the pre-Lion fullscreen by auto-hiding the dock and menu // bar NSApplicationPresentationOptions options = NSApplicationPresentationAutoHideDock | NSApplicationPresentationAutoHideMenuBar; [NSApp setPresentationOptions:options]; was_maximizable_ = IsMaximizable(); was_movable_ = IsMovable(); NSRect fullscreenFrame = [window.screen frame]; // If our app has dock hidden, set the window level higher so another app's // menu bar doesn't appear on top of our fullscreen app. if ([[NSRunningApplication currentApplication] activationPolicy] != NSApplicationActivationPolicyRegular) { window.level = NSPopUpMenuWindowLevel; } // Always hide the titlebar in simple fullscreen mode. // // Note that we must remove the NSWindowStyleMaskTitled style instead of // using the [window_ setTitleVisibility:], as the latter would leave the // window with rounded corners. SetStyleMask(false, NSWindowStyleMaskTitled); if (!window_button_visibility_.has_value()) { // Lets keep previous behaviour - hide window controls in titled // fullscreen mode when not specified otherwise. InternalSetWindowButtonVisibility(false); } [window setFrame:fullscreenFrame display:YES animate:YES]; // Fullscreen windows can't be resized, minimized, maximized, or moved SetMinimizable(false); SetResizable(false); SetMaximizable(false); SetMovable(false); } else if (!simple_fullscreen && is_simple_fullscreen_) { is_simple_fullscreen_ = false; [window setFrame:original_frame_ display:YES animate:YES]; window.level = original_level_; [NSApp setPresentationOptions:simple_fullscreen_options_]; // Restore original style mask ScopedDisableResize disable_resize; [window_ setStyleMask:simple_fullscreen_mask_]; // Restore window manipulation abilities SetMaximizable(was_maximizable_); SetMovable(was_movable_); // Restore default window controls visibility state. if (!window_button_visibility_.has_value()) { bool visibility; if (has_frame()) visibility = true; else visibility = title_bar_style_ != TitleBarStyle::kNormal; InternalSetWindowButtonVisibility(visibility); } if (buttons_proxy_) [buttons_proxy_ redraw]; } } bool NativeWindowMac::IsSimpleFullScreen() { return is_simple_fullscreen_; } void NativeWindowMac::SetKiosk(bool kiosk) { if (kiosk && !is_kiosk_) { kiosk_options_ = [NSApp currentSystemPresentationOptions]; NSApplicationPresentationOptions options = NSApplicationPresentationHideDock | NSApplicationPresentationHideMenuBar | NSApplicationPresentationDisableAppleMenu | NSApplicationPresentationDisableProcessSwitching | NSApplicationPresentationDisableForceQuit | NSApplicationPresentationDisableSessionTermination | NSApplicationPresentationDisableHideApplication; [NSApp setPresentationOptions:options]; is_kiosk_ = true; fullscreen_before_kiosk_ = IsFullscreen(); if (!fullscreen_before_kiosk_) SetFullScreen(true); } else if (!kiosk && is_kiosk_) { is_kiosk_ = false; if (!fullscreen_before_kiosk_) SetFullScreen(false); // Set presentation options *after* asynchronously exiting // fullscreen to ensure they take effect. [NSApp setPresentationOptions:kiosk_options_]; } } bool NativeWindowMac::IsKiosk() { return is_kiosk_; } void NativeWindowMac::SetBackgroundColor(SkColor color) { base::ScopedCFTypeRef<CGColorRef> cgcolor( skia::CGColorCreateFromSkColor(color)); [[[window_ contentView] layer] setBackgroundColor:cgcolor]; } SkColor NativeWindowMac::GetBackgroundColor() { CGColorRef color = [[[window_ contentView] layer] backgroundColor]; if (!color) return SK_ColorTRANSPARENT; return skia::CGColorRefToSkColor(color); } void NativeWindowMac::SetHasShadow(bool has_shadow) { [window_ setHasShadow:has_shadow]; } bool NativeWindowMac::HasShadow() { return [window_ hasShadow]; } void NativeWindowMac::InvalidateShadow() { [window_ invalidateShadow]; } void NativeWindowMac::SetOpacity(const double opacity) { const double boundedOpacity = std::clamp(opacity, 0.0, 1.0); [window_ setAlphaValue:boundedOpacity]; } double NativeWindowMac::GetOpacity() { return [window_ alphaValue]; } void NativeWindowMac::SetRepresentedFilename(const std::string& filename) { [window_ setRepresentedFilename:base::SysUTF8ToNSString(filename)]; if (buttons_proxy_) [buttons_proxy_ redraw]; } std::string NativeWindowMac::GetRepresentedFilename() { return base::SysNSStringToUTF8([window_ representedFilename]); } void NativeWindowMac::SetDocumentEdited(bool edited) { [window_ setDocumentEdited:edited]; if (buttons_proxy_) [buttons_proxy_ redraw]; } bool NativeWindowMac::IsDocumentEdited() { return [window_ isDocumentEdited]; } bool NativeWindowMac::IsHiddenInMissionControl() { NSUInteger collectionBehavior = [window_ collectionBehavior]; return collectionBehavior & NSWindowCollectionBehaviorTransient; } void NativeWindowMac::SetHiddenInMissionControl(bool hidden) { SetCollectionBehavior(hidden, NSWindowCollectionBehaviorTransient); } void NativeWindowMac::SetIgnoreMouseEvents(bool ignore, bool forward) { [window_ setIgnoresMouseEvents:ignore]; if (!ignore) { SetForwardMouseMessages(NO); } else { SetForwardMouseMessages(forward); } } void NativeWindowMac::SetContentProtection(bool enable) { [window_ setSharingType:enable ? NSWindowSharingNone : NSWindowSharingReadOnly]; } void NativeWindowMac::SetFocusable(bool focusable) { // No known way to unfocus the window if it had the focus. Here we do not // want to call Focus(false) because it moves the window to the back, i.e. // at the bottom in term of z-order. [window_ setDisableKeyOrMainWindow:!focusable]; } bool NativeWindowMac::IsFocusable() { return ![window_ disableKeyOrMainWindow]; } void NativeWindowMac::AddBrowserView(NativeBrowserView* view) { [CATransaction begin]; [CATransaction setDisableActions:YES]; if (!view) { [CATransaction commit]; return; } add_browser_view(view); if (view->GetInspectableWebContentsView()) { auto* native_view = view->GetInspectableWebContentsView() ->GetNativeView() .GetNativeNSView(); [[window_ contentView] addSubview:native_view positioned:NSWindowAbove relativeTo:nil]; native_view.hidden = NO; } [CATransaction commit]; } void NativeWindowMac::RemoveBrowserView(NativeBrowserView* view) { [CATransaction begin]; [CATransaction setDisableActions:YES]; if (!view) { [CATransaction commit]; return; } if (view->GetInspectableWebContentsView()) [view->GetInspectableWebContentsView()->GetNativeView().GetNativeNSView() removeFromSuperview]; remove_browser_view(view); [CATransaction commit]; } void NativeWindowMac::SetTopBrowserView(NativeBrowserView* view) { [CATransaction begin]; [CATransaction setDisableActions:YES]; if (!view) { [CATransaction commit]; return; } remove_browser_view(view); add_browser_view(view); if (view->GetInspectableWebContentsView()) { auto* native_view = view->GetInspectableWebContentsView() ->GetNativeView() .GetNativeNSView(); [[window_ contentView] addSubview:native_view positioned:NSWindowAbove relativeTo:nil]; native_view.hidden = NO; } [CATransaction commit]; } void NativeWindowMac::SetParentWindow(NativeWindow* parent) { InternalSetParentWindow(parent, IsVisible()); } gfx::NativeView NativeWindowMac::GetNativeView() const { return [window_ contentView]; } gfx::NativeWindow NativeWindowMac::GetNativeWindow() const { return window_; } gfx::AcceleratedWidget NativeWindowMac::GetAcceleratedWidget() const { return [window_ windowNumber]; } content::DesktopMediaID NativeWindowMac::GetDesktopMediaID() const { auto desktop_media_id = content::DesktopMediaID( content::DesktopMediaID::TYPE_WINDOW, GetAcceleratedWidget()); // c.f. // https://source.chromium.org/chromium/chromium/src/+/main:chrome/browser/media/webrtc/native_desktop_media_list.cc;l=775-780;drc=79502ab47f61bff351426f57f576daef02b1a8dc // Refs https://github.com/electron/electron/pull/30507 // TODO(deepak1556): Match upstream for `kWindowCaptureMacV2` #if 0 if (remote_cocoa::ScopedCGWindowID::Get(desktop_media_id.id)) { desktop_media_id.window_id = desktop_media_id.id; } #endif return desktop_media_id; } NativeWindowHandle NativeWindowMac::GetNativeWindowHandle() const { return [window_ contentView]; } void NativeWindowMac::SetProgressBar(double progress, const NativeWindow::ProgressState state) { NSDockTile* dock_tile = [NSApp dockTile]; // Sometimes macOS would install a default contentView for dock, we must // verify whether NSProgressIndicator has been installed. bool first_time = !dock_tile.contentView || [[dock_tile.contentView subviews] count] == 0 || ![[[dock_tile.contentView subviews] lastObject] isKindOfClass:[NSProgressIndicator class]]; // For the first time API invoked, we need to create a ContentView in // DockTile. if (first_time) { NSImageView* image_view = [[NSImageView alloc] init]; [image_view setImage:[NSApp applicationIconImage]]; [dock_tile setContentView:image_view]; NSRect frame = NSMakeRect(0.0f, 0.0f, dock_tile.size.width, 15.0); NSProgressIndicator* progress_indicator = [[ElectronProgressBar alloc] initWithFrame:frame]; [progress_indicator setStyle:NSProgressIndicatorStyleBar]; [progress_indicator setIndeterminate:NO]; [progress_indicator setBezeled:YES]; [progress_indicator setMinValue:0]; [progress_indicator setMaxValue:1]; [progress_indicator setHidden:NO]; [dock_tile.contentView addSubview:progress_indicator]; } NSProgressIndicator* progress_indicator = static_cast<NSProgressIndicator*>( [[[dock_tile contentView] subviews] lastObject]); if (progress < 0) { [progress_indicator setHidden:YES]; } else if (progress > 1) { [progress_indicator setHidden:NO]; [progress_indicator setIndeterminate:YES]; [progress_indicator setDoubleValue:1]; } else { [progress_indicator setHidden:NO]; [progress_indicator setDoubleValue:progress]; } [dock_tile display]; } void NativeWindowMac::SetOverlayIcon(const gfx::Image& overlay, const std::string& description) {} void NativeWindowMac::SetVisibleOnAllWorkspaces(bool visible, bool visibleOnFullScreen, bool skipTransformProcessType) { // In order for NSWindows to be visible on fullscreen we need to invoke // app.dock.hide() since Apple changed the underlying functionality of // NSWindows starting with 10.14 to disallow NSWindows from floating on top of // fullscreen apps. if (!skipTransformProcessType) { if (visibleOnFullScreen) { Browser::Get()->DockHide(); } else { Browser::Get()->DockShow(JavascriptEnvironment::GetIsolate()); } } SetCollectionBehavior(visible, NSWindowCollectionBehaviorCanJoinAllSpaces); SetCollectionBehavior(visibleOnFullScreen, NSWindowCollectionBehaviorFullScreenAuxiliary); } bool NativeWindowMac::IsVisibleOnAllWorkspaces() { NSUInteger collectionBehavior = [window_ collectionBehavior]; return collectionBehavior & NSWindowCollectionBehaviorCanJoinAllSpaces; } void NativeWindowMac::SetAutoHideCursor(bool auto_hide) { [window_ setDisableAutoHideCursor:!auto_hide]; } void NativeWindowMac::UpdateVibrancyRadii(bool fullscreen) { NSVisualEffectView* vibrantView = [window_ vibrantView]; if (vibrantView != nil && !vibrancy_type_.empty()) { const bool no_rounded_corner = !HasStyleMask(NSWindowStyleMaskTitled); if (!has_frame() && !is_modal() && !no_rounded_corner) { CGFloat radius; if (fullscreen) { radius = 0.0f; } else if (@available(macOS 11.0, *)) { radius = 9.0f; } else { // Smaller corner radius on versions prior to Big Sur. radius = 5.0f; } CGFloat dimension = 2 * radius + 1; NSSize size = NSMakeSize(dimension, dimension); NSImage* maskImage = [NSImage imageWithSize:size flipped:NO drawingHandler:^BOOL(NSRect rect) { NSBezierPath* bezierPath = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [[NSColor blackColor] set]; [bezierPath fill]; return YES; }]; [maskImage setCapInsets:NSEdgeInsetsMake(radius, radius, radius, radius)]; [maskImage setResizingMode:NSImageResizingModeStretch]; [vibrantView setMaskImage:maskImage]; [window_ setCornerMask:maskImage]; } } } void NativeWindowMac::UpdateWindowOriginalFrame() { original_frame_ = [window_ frame]; } void NativeWindowMac::SetVibrancy(const std::string& type) { NSVisualEffectView* vibrantView = [window_ vibrantView]; if (type.empty()) { if (vibrantView == nil) return; [vibrantView removeFromSuperview]; [window_ setVibrantView:nil]; return; } NSVisualEffectMaterial vibrancyType{}; if (type == "titlebar") { vibrancyType = NSVisualEffectMaterialTitlebar; } else if (type == "selection") { vibrancyType = NSVisualEffectMaterialSelection; } else if (type == "menu") { vibrancyType = NSVisualEffectMaterialMenu; } else if (type == "popover") { vibrancyType = NSVisualEffectMaterialPopover; } else if (type == "sidebar") { vibrancyType = NSVisualEffectMaterialSidebar; } else if (type == "header") { vibrancyType = NSVisualEffectMaterialHeaderView; } else if (type == "sheet") { vibrancyType = NSVisualEffectMaterialSheet; } else if (type == "window") { vibrancyType = NSVisualEffectMaterialWindowBackground; } else if (type == "hud") { vibrancyType = NSVisualEffectMaterialHUDWindow; } else if (type == "fullscreen-ui") { vibrancyType = NSVisualEffectMaterialFullScreenUI; } else if (type == "tooltip") { vibrancyType = NSVisualEffectMaterialToolTip; } else if (type == "content") { vibrancyType = NSVisualEffectMaterialContentBackground; } else if (type == "under-window") { vibrancyType = NSVisualEffectMaterialUnderWindowBackground; } else if (type == "under-page") { vibrancyType = NSVisualEffectMaterialUnderPageBackground; } if (vibrancyType) { vibrancy_type_ = type; if (vibrantView == nil) { vibrantView = [[NSVisualEffectView alloc] initWithFrame:[[window_ contentView] bounds]]; [window_ setVibrantView:vibrantView]; [vibrantView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable]; [vibrantView setBlendingMode:NSVisualEffectBlendingModeBehindWindow]; if (visual_effect_state_ == VisualEffectState::kActive) { [vibrantView setState:NSVisualEffectStateActive]; } else if (visual_effect_state_ == VisualEffectState::kInactive) { [vibrantView setState:NSVisualEffectStateInactive]; } else { [vibrantView setState:NSVisualEffectStateFollowsWindowActiveState]; } [[window_ contentView] addSubview:vibrantView positioned:NSWindowBelow relativeTo:nil]; UpdateVibrancyRadii(IsFullscreen()); } [vibrantView setMaterial:vibrancyType]; } } void NativeWindowMac::SetWindowButtonVisibility(bool visible) { window_button_visibility_ = visible; if (buttons_proxy_) { if (visible) [buttons_proxy_ redraw]; [buttons_proxy_ setVisible:visible]; } if (title_bar_style_ != TitleBarStyle::kCustomButtonsOnHover) InternalSetWindowButtonVisibility(visible); NotifyLayoutWindowControlsOverlay(); } bool NativeWindowMac::GetWindowButtonVisibility() const { return ![window_ standardWindowButton:NSWindowZoomButton].hidden || ![window_ standardWindowButton:NSWindowMiniaturizeButton].hidden || ![window_ standardWindowButton:NSWindowCloseButton].hidden; } void NativeWindowMac::SetWindowButtonPosition( absl::optional<gfx::Point> position) { traffic_light_position_ = std::move(position); if (buttons_proxy_) { [buttons_proxy_ setMargin:traffic_light_position_]; NotifyLayoutWindowControlsOverlay(); } } absl::optional<gfx::Point> NativeWindowMac::GetWindowButtonPosition() const { return traffic_light_position_; } void NativeWindowMac::RedrawTrafficLights() { if (buttons_proxy_ && !IsFullscreen()) [buttons_proxy_ redraw]; } // In simpleFullScreen mode, update the frame for new bounds. void NativeWindowMac::UpdateFrame() { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); NSRect fullscreenFrame = [window.screen frame]; [window setFrame:fullscreenFrame display:YES animate:YES]; } void NativeWindowMac::SetTouchBar( std::vector<gin_helper::PersistentDictionary> items) { touch_bar_ = [[ElectronTouchBar alloc] initWithDelegate:window_delegate_ window:this settings:std::move(items)]; [window_ setTouchBar:nil]; } void NativeWindowMac::RefreshTouchBarItem(const std::string& item_id) { if (touch_bar_ && [window_ touchBar]) [touch_bar_ refreshTouchBarItem:[window_ touchBar] id:item_id]; } void NativeWindowMac::SetEscapeTouchBarItem( gin_helper::PersistentDictionary item) { if (touch_bar_ && [window_ touchBar]) [touch_bar_ setEscapeTouchBarItem:std::move(item) forTouchBar:[window_ touchBar]]; } void NativeWindowMac::SelectPreviousTab() { [window_ selectPreviousTab:nil]; } void NativeWindowMac::SelectNextTab() { [window_ selectNextTab:nil]; } void NativeWindowMac::ShowAllTabs() { [window_ toggleTabOverview:nil]; } void NativeWindowMac::MergeAllWindows() { [window_ mergeAllWindows:nil]; } void NativeWindowMac::MoveTabToNewWindow() { [window_ moveTabToNewWindow:nil]; } void NativeWindowMac::ToggleTabBar() { [window_ toggleTabBar:nil]; } bool NativeWindowMac::AddTabbedWindow(NativeWindow* window) { if (window_ == window->GetNativeWindow().GetNativeNSWindow()) { return false; } else { [window_ addTabbedWindow:window->GetNativeWindow().GetNativeNSWindow() ordered:NSWindowAbove]; } return true; } void NativeWindowMac::SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) { NativeWindow::SetAspectRatio(aspect_ratio, extra_size); // Reset the behaviour to default if aspect_ratio is set to 0 or less. if (aspect_ratio > 0.0) { NSSize aspect_ratio_size = NSMakeSize(aspect_ratio, 1.0); if (has_frame()) [window_ setContentAspectRatio:aspect_ratio_size]; else [window_ setAspectRatio:aspect_ratio_size]; } else { [window_ setResizeIncrements:NSMakeSize(1.0, 1.0)]; } } void NativeWindowMac::PreviewFile(const std::string& path, const std::string& display_name) { preview_item_ = [[ElectronPreviewItem alloc] initWithURL:[NSURL fileURLWithPath:base::SysUTF8ToNSString(path)] title:base::SysUTF8ToNSString(display_name)]; [[QLPreviewPanel sharedPreviewPanel] makeKeyAndOrderFront:nil]; } void NativeWindowMac::CloseFilePreview() { if ([QLPreviewPanel sharedPreviewPanelExists]) { [[QLPreviewPanel sharedPreviewPanel] close]; } } gfx::Rect NativeWindowMac::ContentBoundsToWindowBounds( const gfx::Rect& bounds) const { if (has_frame()) { gfx::Rect window_bounds( [window_ frameRectForContentRect:bounds.ToCGRect()]); int frame_height = window_bounds.height() - bounds.height(); window_bounds.set_y(window_bounds.y() - frame_height); return window_bounds; } else { return bounds; } } gfx::Rect NativeWindowMac::WindowBoundsToContentBounds( const gfx::Rect& bounds) const { if (has_frame()) { gfx::Rect content_bounds( [window_ contentRectForFrameRect:bounds.ToCGRect()]); int frame_height = bounds.height() - content_bounds.height(); content_bounds.set_y(content_bounds.y() + frame_height); return content_bounds; } else { return bounds; } } void NativeWindowMac::NotifyWindowEnterFullScreen() { NativeWindow::NotifyWindowEnterFullScreen(); // Restore the window title under fullscreen mode. if (buttons_proxy_) [window_ setTitleVisibility:NSWindowTitleVisible]; } void NativeWindowMac::NotifyWindowLeaveFullScreen() { NativeWindow::NotifyWindowLeaveFullScreen(); // Restore window buttons. if (buttons_proxy_ && window_button_visibility_.value_or(true)) { [buttons_proxy_ redraw]; [buttons_proxy_ setVisible:YES]; } } void NativeWindowMac::NotifyWindowWillEnterFullScreen() { UpdateVibrancyRadii(true); } void NativeWindowMac::NotifyWindowWillLeaveFullScreen() { if (buttons_proxy_) { // Hide window title when leaving fullscreen. [window_ setTitleVisibility:NSWindowTitleHidden]; // Hide the container otherwise traffic light buttons jump. [buttons_proxy_ setVisible:NO]; } UpdateVibrancyRadii(false); } void NativeWindowMac::SetActive(bool is_key) { is_active_ = is_key; } bool NativeWindowMac::IsActive() const { return is_active_; } void NativeWindowMac::Cleanup() { DCHECK(!IsClosed()); ui::NativeTheme::GetInstanceForNativeUi()->RemoveObserver(this); display::Screen::GetScreen()->RemoveObserver(this); } class NativeAppWindowFrameViewMac : public views::NativeFrameViewMac { public: NativeAppWindowFrameViewMac(views::Widget* frame, NativeWindowMac* window) : views::NativeFrameViewMac(frame), native_window_(window) {} NativeAppWindowFrameViewMac(const NativeAppWindowFrameViewMac&) = delete; NativeAppWindowFrameViewMac& operator=(const NativeAppWindowFrameViewMac&) = delete; ~NativeAppWindowFrameViewMac() override = default; // NonClientFrameView: int NonClientHitTest(const gfx::Point& point) override { if (!bounds().Contains(point)) return HTNOWHERE; if (GetWidget()->IsFullscreen()) return HTCLIENT; // Check for possible draggable region in the client area for the frameless // window. int contents_hit_test = native_window_->NonClientHitTest(point); if (contents_hit_test != HTNOWHERE) return contents_hit_test; return HTCLIENT; } private: // Weak. raw_ptr<NativeWindowMac> const native_window_; }; std::unique_ptr<views::NonClientFrameView> NativeWindowMac::CreateNonClientFrameView(views::Widget* widget) { return std::make_unique<NativeAppWindowFrameViewMac>(widget, this); } bool NativeWindowMac::HasStyleMask(NSUInteger flag) const { return [window_ styleMask] & flag; } void NativeWindowMac::SetStyleMask(bool on, NSUInteger flag) { // Changing the styleMask of a frameless windows causes it to change size so // we explicitly disable resizing while setting it. ScopedDisableResize disable_resize; if (on) [window_ setStyleMask:[window_ styleMask] | flag]; else [window_ setStyleMask:[window_ styleMask] & (~flag)]; // Change style mask will make the zoom button revert to default, probably // a bug of Cocoa or macOS. SetMaximizable(maximizable_); } void NativeWindowMac::SetCollectionBehavior(bool on, NSUInteger flag) { if (on) [window_ setCollectionBehavior:[window_ collectionBehavior] | flag]; else [window_ setCollectionBehavior:[window_ collectionBehavior] & (~flag)]; // Change collectionBehavior will make the zoom button revert to default, // probably a bug of Cocoa or macOS. SetMaximizable(maximizable_); } views::View* NativeWindowMac::GetContentsView() { return root_view_.get(); } bool NativeWindowMac::CanMaximize() const { return maximizable_; } void NativeWindowMac::OnNativeThemeUpdated(ui::NativeTheme* observed_theme) { content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&NativeWindow::RedrawTrafficLights, GetWeakPtr())); } void NativeWindowMac::AddContentViewLayers() { // Make sure the bottom corner is rounded for non-modal windows: // http://crbug.com/396264. if (!is_modal()) { // For normal window, we need to explicitly set layer for contentView to // make setBackgroundColor work correctly. // There is no need to do so for frameless window, and doing so would make // titleBarStyle stop working. if (has_frame()) { CALayer* background_layer = [[CALayer alloc] init]; [background_layer setAutoresizingMask:kCALayerWidthSizable | kCALayerHeightSizable]; [[window_ contentView] setLayer:background_layer]; } [[window_ contentView] setWantsLayer:YES]; } } void NativeWindowMac::InternalSetWindowButtonVisibility(bool visible) { [[window_ standardWindowButton:NSWindowCloseButton] setHidden:!visible]; [[window_ standardWindowButton:NSWindowMiniaturizeButton] setHidden:!visible]; [[window_ standardWindowButton:NSWindowZoomButton] setHidden:!visible]; } void NativeWindowMac::InternalSetParentWindow(NativeWindow* new_parent, bool attach) { if (is_modal()) return; // Do not remove/add if we are already properly attached. if (attach && new_parent && [window_ parentWindow] == new_parent->GetNativeWindow().GetNativeNSWindow()) return; // Remove current parent window. RemoveChildFromParentWindow(); // Set new parent window. if (new_parent) { new_parent->add_child_window(this); if (attach) new_parent->AttachChildren(); } NativeWindow::SetParentWindow(new_parent); } void NativeWindowMac::SetForwardMouseMessages(bool forward) { [window_ setAcceptsMouseMovedEvents:forward]; } gfx::Rect NativeWindowMac::GetWindowControlsOverlayRect() { if (titlebar_overlay_ && buttons_proxy_ && window_button_visibility_.value_or(true)) { NSRect buttons = [buttons_proxy_ getButtonsContainerBounds]; gfx::Rect overlay; overlay.set_width(GetContentSize().width() - NSWidth(buttons)); if ([buttons_proxy_ useCustomHeight]) { overlay.set_height(titlebar_overlay_height()); } else { overlay.set_height(NSHeight(buttons)); } if (!base::i18n::IsRTL()) overlay.set_x(NSMaxX(buttons)); return overlay; } return gfx::Rect(); } // static NativeWindow* NativeWindow::Create(const gin_helper::Dictionary& options, NativeWindow* parent) { return new NativeWindowMac(options, parent); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
39,630
[Bug]: fullscreenable in BrowserWindowConstructorOptions is ignored if resizable flag presents
### 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 25.6.0 ### What operating system are you using? macOS ### Operating System Version 12.3 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior Windows parameters corresponds to constructor options ### Actual Behavior It doesn't ### Testcase Gist URL https://gist.github.com/origin-yaropolk/8770735fda705a6bbc7d2132a30314dc ### Additional Information _No response_
https://github.com/electron/electron/issues/39630
https://github.com/electron/electron/pull/39620
2affecd4dd26b9f0cf2644ec115635559f920480
33e66b5cd02d2b258b956022c482024c74c13b4b
2023-08-23T17:00:10Z
c++
2023-08-24T20:54:08Z
spec/api-browser-window-spec.ts
import { expect } from 'chai'; import * as childProcess from 'node:child_process'; import * as path from 'node:path'; import * as fs from 'node:fs'; import * as qs from 'node:querystring'; import * as http from 'node:http'; import * as os from 'node:os'; import { AddressInfo } from 'node:net'; import { app, BrowserWindow, BrowserView, dialog, ipcMain, OnBeforeSendHeadersListenerDetails, protocol, screen, webContents, webFrameMain, session, WebContents, WebFrameMain } from 'electron/main'; import { emittedUntil, emittedNTimes } from './lib/events-helpers'; import { ifit, ifdescribe, defer, listen } from './lib/spec-helpers'; import { closeWindow, closeAllWindows } from './lib/window-helpers'; import { areColorsSimilar, captureScreen, HexColors, getPixelColor } from './lib/screen-helpers'; import { once } from 'node:events'; import { setTimeout } from 'node:timers/promises'; const fixtures = path.resolve(__dirname, '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', () => { it('sets the correct class name on the prototype', () => { expect(BrowserWindow.prototype.constructor.name).to.equal('BrowserWindow'); }); 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(fixtures, 'apps', 'xwindow-icon'); const appProcess = childProcess.spawn(process.execPath, [appPath]); await once(appProcess, 'exit'); }); 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. const wr = new WeakRef(w); await setTimeout(); // 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 setTimeout(); expect(wr.deref()).to.not.be.undefined(); }); }); describe('BrowserWindow.close()', () => { let w: 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 = once(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 = once(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 allow access to id after destruction', async () => { const closed = once(w, 'closed'); w.destroy(); await closed; expect(w.id).to.be.a('number'); }); it('should emit unload handler', async () => { await w.loadFile(path.join(fixtures, 'api', 'unload.html')); const closed = once(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 once(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 = once(w, 'closed'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' }); w.close(); await closed; }); describe('when invoked synchronously inside navigation observer', () => { let server: http.Server; let url: string; before(async () => { 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}`); } }); url = (await listen(server)).url; }); 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 = once(w.webContents, 'destroyed'); w.webContents.loadURL(url + path); await destroyed; }); } }); }); describe('window.close()', () => { let w: 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 once(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 once(w.webContents, 'before-unload-fired'); }); }); describe('BrowserWindow.destroy()', () => { let w: 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: 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: http.Server; let url: string; let postData = null as any; before(async () => { 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(req.url && req.url.includes('slow') ? 200 : 0).then(respond); }); url = (await listen(server)).url; }); after(() => { server.close(); }); it('should emit did-start-loading event', async () => { const didStartLoading = once(w.webContents, 'did-start-loading'); w.loadURL('about:blank'); await didStartLoading; }); it('should emit ready-to-show event', async () => { const readyToShow = once(w, 'ready-to-show'); w.loadURL('about:blank'); await readyToShow; }); // DISABLED-FIXME(deepak1556): The error code now seems to be `ERR_FAILED`, verify what // changed and adjust the test. it('should emit did-fail-load event for files that do not exist', async () => { const didFailLoad = once(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 = once(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 not emit did-fail-load for a successfully loaded media file', async () => { w.webContents.on('did-fail-load', () => { expect.fail('did-fail-load should not emit on media file loads'); }); const mediaStarted = once(w.webContents, 'media-started-playing'); w.loadFile(path.join(fixtures, 'cat-spin.mp4')); await mediaStarted; }); it('should set `mainFrame = false` on did-fail-load events in iframes', async () => { const didFailLoad = once(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 = once(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: 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: http.Server; let url: string; before(async () => { server = http.createServer((req, res) => { if (req.url === '/navigate-top') { res.end('<a target=_top href="/">navigate _top</a>'); } else { res.end(''); } }); url = (await listen(server)).url; }); after(() => { server.close(); }); it('allows the window to be closed from the event listener', async () => { const event = once(w.webContents, 'will-navigate'); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); await event; w.close(); }); 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 () => { w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-top"></iframe>`); await emittedUntil(w.webContents, 'did-frame-finish-load', (e: any, isMainFrame: boolean) => !isMainFrame); let initiator: WebFrameMain | undefined; w.webContents.on('will-navigate', (e) => { initiator = e.initiator; }); const subframe = w.webContents.mainFrame.frames[0]; subframe.executeJavaScript('document.getElementsByTagName("a")[0].click()', true); await once(w.webContents, 'did-navigate'); expect(initiator).not.to.be.undefined(); expect(initiator).to.equal(subframe); }); }); describe('will-frame-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 if (req.url === '/navigate-iframe') { res.end('<a href="/test">navigate iframe</a>'); } else if (req.url === '/navigate-iframe?navigated') { res.end('Successfully navigated'); } else if (req.url === '/navigate-iframe-immediately') { res.end(` <script type="text/javascript" charset="utf-8"> location.href += '?navigated' </script> `); } else if (req.url === '/navigate-iframe-immediately?navigated') { res.end('Successfully navigated'); } 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-frame-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-frame-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('can be prevented when navigating subframe', (done) => { let willNavigate = false; w.webContents.on('did-frame-navigate', (_event, _url, _httpResponseCode, _httpStatusText, isMainFrame, frameProcessId, frameRoutingId) => { if (isMainFrame) return; w.webContents.once('will-frame-navigate', (e) => { willNavigate = true; e.preventDefault(); }); w.webContents.on('did-stop-loading', () => { const frame = webFrameMain.fromId(frameProcessId, frameRoutingId); expect(frame).to.not.be.undefined(); if (willNavigate) { // i.e. it shouldn't have had '?navigated' appended to it. try { expect(frame!.url.endsWith('/navigate-iframe-immediately')).to.be.true(); done(); } catch (e) { done(e); } } }); }); w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-iframe-immediately"></iframe>`); }); 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-frame-navigate', (e) => { e.preventDefault(); resolve(e.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-frame-navigate', (e) => { e.preventDefault(); resolve(e.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 setTimeout(1000); let willFrameNavigateEmitted = false; let isMainFrameValue; w.webContents.on('will-frame-navigate', (event) => { willFrameNavigateEmitted = true; isMainFrameValue = event.isMainFrame; }); const didNavigatePromise = once(w.webContents, 'did-navigate'); 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); await didNavigatePromise; expect(willFrameNavigateEmitted).to.be.true(); expect(isMainFrameValue).to.be.true(); }); it('is triggered when a cross-origin iframe navigates itself', async () => { await w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-iframe"></iframe>`); await setTimeout(1000); let willNavigateEmitted = false; let isMainFrameValue; w.webContents.on('will-frame-navigate', (event) => { willNavigateEmitted = true; isMainFrameValue = event.isMainFrame; }); const didNavigatePromise = once(w.webContents, 'did-frame-navigate'); 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); await didNavigatePromise; expect(willNavigateEmitted).to.be.true(); expect(isMainFrameValue).to.be.false(); }); it('can cancel when a cross-origin iframe navigates itself', async () => { }); }); describe('will-redirect event', () => { let server: http.Server; let url: string; before(async () => { 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(); } }); url = (await listen(server)).url; }); after(() => { server.close(); }); it('is emitted on redirects', async () => { const willRedirect = once(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 = once(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 = once(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', async () => { const event = once(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await event; w.close(); }); 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('ordering', () => { let server = null as unknown as http.Server; let url = null as unknown as string; const navigationEvents = [ 'did-start-navigation', 'did-navigate-in-page', 'will-frame-navigate', 'will-navigate', 'will-redirect', 'did-redirect-navigation', 'did-frame-navigate', 'did-navigate' ]; before((done) => { server = http.createServer((req, res) => { if (req.url === '/navigate') { res.end('<a href="/">navigate</a>'); } else if (req.url === '/redirect') { res.end('<a href="/redirect2">redirect</a>'); } else if (req.url === '/redirect2') { res.statusCode = 302; res.setHeader('location', url); res.end(); } else if (req.url === '/in-page') { res.end('<a href="#in-page">redirect</a><div id="in-page"></div>'); } else { res.end(''); } }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/`; done(); }); }); it('for initial navigation, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'did-frame-navigate', 'did-navigate' ]; const allEvents = Promise.all(navigationEvents.map(event => once(w.webContents, event).then(() => firedEvents.push(event)) )); const timeout = setTimeout(1000); w.loadURL(url); await Promise.race([allEvents, timeout]); expect(firedEvents).to.deep.equal(expectedEventOrder); }); it('for second navigation, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'will-frame-navigate', 'will-navigate', 'did-frame-navigate', 'did-navigate' ]; w.loadURL(`${url}navigate`); await once(w.webContents, 'did-navigate'); await setTimeout(2000); Promise.all(navigationEvents.map(event => once(w.webContents, event).then(() => firedEvents.push(event)) )); const navigationFinished = once(w.webContents, 'did-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: pageTarget.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); await navigationFinished; expect(firedEvents).to.deep.equal(expectedEventOrder); }); it('when navigating with redirection, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'will-frame-navigate', 'will-navigate', 'will-redirect', 'did-redirect-navigation', 'did-frame-navigate', 'did-navigate' ]; w.loadURL(`${url}redirect`); await once(w.webContents, 'did-navigate'); await setTimeout(2000); Promise.all(navigationEvents.map(event => once(w.webContents, event).then(() => firedEvents.push(event)) )); const navigationFinished = once(w.webContents, 'did-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: pageTarget.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); await navigationFinished; expect(firedEvents).to.deep.equal(expectedEventOrder); }); it('when navigating in-page, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'did-navigate-in-page' ]; w.loadURL(`${url}in-page`); await once(w.webContents, 'did-navigate'); await setTimeout(2000); Promise.all(navigationEvents.map(event => once(w.webContents, event).then(() => firedEvents.push(event)) )); const navigationFinished = once(w.webContents, 'did-navigate-in-page'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: pageTarget.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); await navigationFinished; expect(firedEvents).to.deep.equal(expectedEventOrder); }); }); }); } describe('focus and visibility', () => { let w: 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', async () => { const p = once(w, 'focus'); w.show(); await p; expect(w.isFocused()).to.equal(true); }); it('should make the window visible', async () => { const p = once(w, 'focus'); w.show(); await p; expect(w.isVisible()).to.equal(true); }); it('emits when window is shown', async () => { const show = once(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 = once(w, 'show'); w.show(); await shown; const hidden = once(w, 'hide'); w.hide(); await hidden; expect(w.isVisible()).to.equal(false); }); }); describe('BrowserWindow.minimize()', () => { // TODO(codebytere): Enable for Linux once maximize/minimize events work in CI. ifit(process.platform !== 'linux')('should not be visible when the window is minimized', async () => { const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMinimized()).to.equal(true); 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 = once(w, 'maximize'); const shown = once(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 setTimeout(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); }); ifit(process.platform !== 'win32')('focuses a blurred window', async () => { { const isBlurred = once(w, 'blur'); const isShown = once(w, 'show'); w.show(); w.blur(); await isShown; await isBlurred; } expect(w.isFocused()).to.equal(false); w.focus(); expect(w.isFocused()).to.equal(true); }); ifit(process.platform !== 'linux')('acquires focus status from the other windows', async () => { const w1 = new BrowserWindow({ show: false }); const w2 = new BrowserWindow({ show: false }); const w3 = new BrowserWindow({ show: false }); { const isFocused3 = once(w3, 'focus'); const isShown1 = once(w1, 'show'); const isShown2 = once(w2, 'show'); const isShown3 = once(w3, 'show'); w1.show(); w2.show(); w3.show(); await isShown1; await isShown2; await isShown3; await isFocused3; } // TODO(RaisinTen): Investigate why this assertion fails only on Linux. expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); w1.focus(); expect(w1.isFocused()).to.equal(true); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(false); w2.focus(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(true); expect(w3.isFocused()).to.equal(false); w3.focus(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); { const isClosed1 = once(w1, 'closed'); const isClosed2 = once(w2, 'closed'); const isClosed3 = once(w3, 'closed'); w1.destroy(); w2.destroy(); w3.destroy(); await isClosed1; await isClosed2; await isClosed3; } }); }); // TODO(RaisinTen): Make this work on Windows too. // Refs: https://github.com/electron/electron/issues/20464. ifdescribe(process.platform !== 'win32')('BrowserWindow.blur()', () => { it('removes focus from window', async () => { { const isFocused = once(w, 'focus'); const isShown = once(w, 'show'); w.show(); await isShown; await isFocused; } expect(w.isFocused()).to.equal(true); w.blur(); expect(w.isFocused()).to.equal(false); }); ifit(process.platform !== 'linux')('transfers focus status to the next window', async () => { const w1 = new BrowserWindow({ show: false }); const w2 = new BrowserWindow({ show: false }); const w3 = new BrowserWindow({ show: false }); { const isFocused3 = once(w3, 'focus'); const isShown1 = once(w1, 'show'); const isShown2 = once(w2, 'show'); const isShown3 = once(w3, 'show'); w1.show(); w2.show(); w3.show(); await isShown1; await isShown2; await isShown3; await isFocused3; } // TODO(RaisinTen): Investigate why this assertion fails only on Linux. expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); w3.blur(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(true); expect(w3.isFocused()).to.equal(false); w2.blur(); expect(w1.isFocused()).to.equal(true); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(false); w1.blur(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); { const isClosed1 = once(w1, 'closed'); const isClosed2 = once(w2, 'closed'); const isClosed3 = once(w3, 'closed'); w1.destroy(); w2.destroy(); w3.destroy(); await isClosed1; await isClosed2; await isClosed3; } }); }); describe('BrowserWindow.getFocusedWindow()', () => { it('returns the opener window when dev tools window is focused', async () => { const p = once(w, 'focus'); w.show(); await p; w.webContents.openDevTools({ mode: 'undocked' }); await once(w.webContents, 'devtools-focused'); expect(BrowserWindow.getFocusedWindow()).to.equal(w); }); }); describe('BrowserWindow.moveTop()', () => { afterEach(closeAllWindows); it('should not steal focus', async () => { const posDelta = 50; const wShownInactive = once(w, 'show'); w.showInactive(); await wShownInactive; expect(w.isFocused()).to.equal(false); const otherWindow = new BrowserWindow({ show: false, title: 'otherWindow' }); const otherWindowShown = once(otherWindow, 'show'); const otherWindowFocused = once(otherWindow, 'focus'); otherWindow.show(); await otherWindowShown; await otherWindowFocused; expect(otherWindow.isFocused()).to.equal(true); w.moveTop(); const wPos = w.getPosition(); const wMoving = once(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 = once(w, 'focus'); const otherWindowBlurred = once(otherWindow, 'blur'); w.focus(); await wFocused; await otherWindowBlurred; expect(w.isFocused()).to.equal(true); otherWindow.moveTop(); const otherWindowPos = otherWindow.getPosition(); const otherWindowMoving = once(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); }); it('should not crash when called on a modal child window', async () => { const shown = once(w, 'show'); w.show(); await shown; const child = new BrowserWindow({ modal: true, parent: w }); expect(() => { child.moveTop(); }).to.not.throw(); }); }); describe('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 = once(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 = once(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: 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 = { ...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(once(w, 'resized')).to.eventually.be.fulfilled(); }); }); }); describe('BrowserWindow.setSize(width, height)', () => { it('sets the window size', async () => { const size = [300, 400]; const resized = once(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(once(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 = once(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 = once(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 = once(w, 'resize'); w.setContentBounds(bounds); await resize; await setTimeout(); 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 = once(w, 'resize'); w.setContentBounds(bounds); await resize; await setTimeout(); 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); }); it('returns correct color with multiple passed formats', () => { w.destroy(); w = new BrowserWindow({}); w.setBackgroundColor('#AABBFF'); expect(w.getBackgroundColor()).to.equal('#AABBFF'); w.setBackgroundColor('blueviolet'); expect(w.getBackgroundColor()).to.equal('#8A2BE2'); w.setBackgroundColor('rgb(255, 0, 185)'); expect(w.getBackgroundColor()).to.equal('#FF00B9'); w.setBackgroundColor('rgba(245, 40, 145, 0.8)'); expect(w.getBackgroundColor()).to.equal('#F52891'); w.setBackgroundColor('hsl(155, 100%, 50%)'); expect(w.getBackgroundColor()).to.equal('#00FF95'); }); }); describe('BrowserWindow.getNormalBounds()', () => { describe('Normal state', () => { it('checks normal bounds after resize', async () => { const size = [300, 400]; const resize = once(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 = once(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 = once(w, 'maximize'); w.show(); w.maximize(); await maximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after resize and maximize', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('updates normal bounds after move and maximize', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('checks normal bounds when unmaximized', async () => { const bounds = w.getBounds(); w.once('maximize', () => { w.unmaximize(); }); const unmaximize = once(w, 'unmaximize'); w.show(); w.maximize(); await unmaximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('correctly reports maximized state after maximizing then minimizing', async () => { w.destroy(); w = new BrowserWindow({ show: false }); w.show(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMaximized()).to.equal(false); expect(w.isMinimized()).to.equal(true); }); it('correctly reports maximized state after maximizing then fullscreening', async () => { w.destroy(); w = new BrowserWindow({ show: false }); w.show(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; expect(w.isMaximized()).to.equal(false); expect(w.isFullScreen()).to.equal(true); }); it('checks normal bounds for maximized transparent window', async () => { w.destroy(); w = new BrowserWindow({ transparent: true, show: false }); w.show(); const bounds = w.getNormalBounds(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; 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 = once(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 = once(w, 'maximize'); w.show(); w.maximize(); await maximize; expect(w.isMaximized()).to.equal(true); const unmaximize = once(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 = once(w, 'maximize'); 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 = once(w, 'minimize'); w.show(); w.minimize(); await minimize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after move and minimize', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const minimize = once(w, 'minimize'); w.minimize(); await minimize; const normal = w.getNormalBounds(); expect(original).to.deep.equal(normal); expectBoundsEqual(normal, w.getBounds()); }); it('updates normal bounds after resize and minimize', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const minimize = once(w, 'minimize'); w.minimize(); await minimize; const normal = w.getNormalBounds(); expect(original).to.deep.equal(normal); expectBoundsEqual(normal, w.getBounds()); }); it('checks normal bounds when restored', async () => { const bounds = w.getBounds(); w.once('minimize', () => { w.restore(); }); const restore = once(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 = once(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('does not go fullscreen if roundedCorners are enabled', async () => { w = new BrowserWindow({ frame: false, roundedCorners: false, fullscreen: true }); expect(w.fullScreen).to.be.false(); }); 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 = once(w, 'enter-full-screen'); w.show(); w.fullScreen = true; await enterFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after resize and fullscreen', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.fullScreen = true; await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('updates normal bounds after move and fullscreen', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.fullScreen = true; await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('checks normal bounds when unfullscreen\'ed', async () => { const bounds = w.getBounds(); w.once('enter-full-screen', () => { w.fullScreen = false; }); const leaveFullScreen = once(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 = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after resize and fullscreen', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.setFullScreen(true); await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('updates normal bounds after move and fullscreen', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.setFullScreen(true); await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('checks normal bounds when unfullscreen\'ed', async () => { const bounds = w.getBounds(); w.show(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); }); }); }); ifdescribe(process.platform === 'darwin')('tabbed windows', () => { let w: 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.showAllTabs()', () => { it('does not throw', () => { expect(() => { w.showAllTabs(); }).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); }); ifit(process.platform === 'darwin')('honors the stayHidden argument', async () => { const w = new BrowserWindow({ webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.hide(); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } await w.capturePage({ x: 0, y: 0, width: 0, height: 0 }, { stayHidden: true }); const visible = await w.webContents.executeJavaScript('document.visibilityState'); expect(visible).to.equal('hidden'); }); it('resolves after the window is hidden', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixtures, 'pages', 'a.html')); await once(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('resolves after the window is hidden and capturer count is non-zero', async () => { const w = new BrowserWindow({ show: false }); w.webContents.setBackgroundThrottling(false); w.loadFile(path.join(fixtures, 'pages', 'a.html')); await once(w, 'ready-to-show'); const image = await w.capturePage(); expect(image.isEmpty()).to.equal(false); }); it('preserves transparency', async () => { const w = new BrowserWindow({ show: false, transparent: true }); w.loadFile(path.join(fixtures, 'pages', 'theme-color.html')); await once(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: 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: 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', async () => { expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); const minimized = once(w, 'minimize'); w.minimize(); await minimized; expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); const restored = once(w, 'restore'); w.restore(); await restored; 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 = once(w, 'always-on-top-changed') as Promise<[any, boolean]>; 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: BrowserWindow; let server: http.Server; let url: 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++; }); url = (await listen(server)).url; }); 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 = once(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: 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); }); it('correctly updates when entering/exiting fullscreen for hidden style', async () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hidden' }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; const leaveFS = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFS; w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); it('correctly updates when entering/exiting fullscreen for hiddenInset style', async () => { 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); const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; const leaveFS = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFS; w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setVibrancy(type)', () => { afterEach(closeAllWindows); it('allows setting, changing, and removing the vibrancy', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setVibrancy('titlebar'); w.setVibrancy('selection'); w.setVibrancy(null); w.setVibrancy('menu'); 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(); }); }); ifdescribe(process.platform === 'darwin')('trafficLightPosition', () => { const pos = { x: 10, y: 10 }; afterEach(closeAllWindows); describe('BrowserWindow.getWindowButtonPosition(pos)', () => { it('returns null when there is no custom position', () => { const w = new BrowserWindow({ show: false }); expect(w.getWindowButtonPosition()).to.be.null('getWindowButtonPosition'); }); it('gets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); expect(w.getWindowButtonPosition()).to.deep.equal(pos); }); it('gets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); expect(w.getWindowButtonPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setWindowButtonPosition(pos)', () => { it('resets the position when null is passed', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); w.setWindowButtonPosition(null); expect(w.getWindowButtonPosition()).to.be.null('setWindowButtonPosition'); }); it('sets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setWindowButtonPosition(newPos); expect(w.getWindowButtonPosition()).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.setWindowButtonPosition(newPos); expect(w.getWindowButtonPosition()).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('Opening a BrowserWindow from a link', () => { let appProcess: childProcess.ChildProcessWithoutNullStreams | undefined; afterEach(() => { if (appProcess && !appProcess.killed) { appProcess.kill(); appProcess = undefined; } }); it('can properly open and load a new window from a link', async () => { const appPath = path.join(__dirname, 'fixtures', 'apps', 'open-new-window-from-link'); appProcess = childProcess.spawn(process.execPath, [appPath]); const [code] = await once(appProcess, 'exit'); expect(code).to.equal(0); }); }); 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 typeof ElectronInternal.WebContents).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.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 = once(w.webContents, 'did-attach-webview'); const [, webviewContents] = await once(app, 'web-contents-created') as [any, WebContents]; expect(BrowserWindow.fromWebContents(webviewContents)!.id).to.equal(w.id); await p; }); it('is usable immediately on browser-window-created', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.executeJavaScript('window.open(""); null'); const [win, winFromWebContents] = await new Promise<any>((resolve) => { app.once('browser-window-created', (e, win) => { resolve([win, BrowserWindow.fromWebContents(win.webContents)]); }); }); expect(winFromWebContents).to.equal(win); }); }); 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.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.destroy(); bv2.webContents.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.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(['win32', 'darwin'].includes(process.platform))('"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 = once(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 = once(ipcMain, 'geometrychange'); w.setBounds({ width: 800 }); const [, newOverlayRect] = await geometryChange; expect(newOverlayRect.width).to.equal(overlayRect.width + 400); }; afterEach(async () => { await closeAllWindows(); 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')('when an invalid titleBarStyle is initially set', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { color: '#0000f0', symbolColor: '#ffffff' }, titleBarStyle: 'hiddenInset' }); }); afterEach(async () => { await closeAllWindows(); }); it('does not crash changing minimizability ', () => { expect(() => { w.setMinimizable(false); }).to.not.throw(); }); it('does not crash changing maximizability', () => { expect(() => { w.setMaximizable(false); }).to.not.throw(); }); }); }); ifdescribe(['win32', 'darwin'].includes(process.platform))('"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 = once(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()'); if (!w.isMaximized()) { const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; } expect(w.isMaximized()).to.be.true('not maximized'); 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(async () => { await closeAllWindows(); ipcMain.removeAllListeners('geometrychange'); }); it('sets Window Control Overlay with title bar height of 40', async () => { await testWindowsOverlayHeight(40); }); }); ifdescribe(process.platform === 'win32')('BrowserWindow.setTitlebarOverlay', () => { afterEach(async () => { await closeAllWindows(); ipcMain.removeAllListeners('geometrychange'); }); it('does not crash when an invalid titleBarStyle was initially set', () => { const win = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { color: '#0000f0', symbolColor: '#ffffff' }, titleBarStyle: 'hiddenInset' }); expect(() => { win.setTitleBarOverlay({ color: '#000000' }); }).to.not.throw(); }); it('correctly updates the height of the overlay', async () => { const testOverlay = async (w: BrowserWindow, size: Number, firstRun: boolean) => { const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); const overlayReady = once(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); if (firstRun) { await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const { height: preMaxHeight } = await w.webContents.executeJavaScript('getJSOverlayProperties()'); if (!w.isMaximized()) { const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; } expect(w.isMaximized()).to.be.true('not maximized'); const { x, y, width, height } = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(x).to.equal(0); expect(y).to.equal(0); expect(width).to.be.greaterThan(0); expect(height).to.equal(size); expect(preMaxHeight).to.equal(size); }; const INITIAL_SIZE = 40; const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden', webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { height: INITIAL_SIZE } }); await testOverlay(w, INITIAL_SIZE, true); w.setTitleBarOverlay({ height: INITIAL_SIZE + 10 }); await testOverlay(w, INITIAL_SIZE + 10, false); }); }); 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-next-line no-new */ new BrowserWindow({ tabbingIdentifier: 'group1' }); /* eslint-disable-next-line no-new */ new BrowserWindow({ tabbingIdentifier: 'group2', frame: false }); }).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 once(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 once(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 once(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-isolated 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 once(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 once(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 once(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 once(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 once(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 once(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; let serverUrl: string; before(async () => { 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}`); } }); serverUrl = (await listen(server)).url; }); 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 once(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 once(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 once(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 once(ipcMain, 'answer'); const expectedUrl = process.platform === 'win32' ? 'file:///' + htmlPath.replace(/\\/g, '/') : pageUrl; expect(url).to.equal(expectedUrl); }); it('exposes full EventEmitter object to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload: path.join(fixtures, 'module', 'preload-eventemitter.js') } }); w.loadURL('about:blank'); const [, rendererEventEmitterProperties] = await once(ipcMain, 'answer'); const { EventEmitter } = require('node:events'); const emitter = new EventEmitter(); const browserEventEmitterProperties = []; let currentObj = emitter; do { browserEventEmitterProperties.push(...Object.getOwnPropertyNames(currentObj)); } while ((currentObj = Object.getPrototypeOf(currentObj))); expect(rendererEventEmitterProperties).to.deep.equal(browserEventEmitterProperties); }); 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 = once(ipcMain, 'answer'); w.loadURL(pageUrl); const [, { url, frameName, options }] = await once(w.webContents, 'did-create-window') as [BrowserWindow, Electron.DidCreateWindowDetails]; 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 once(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 once(app, 'browser-window-created') as [any, BrowserWindow]; // Ask the popup window for details. const detailsAnswer = once(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 = once(ipcMain, 'answer'); w.webContents.send('touch-the-popup'); const [, popupAccessMessage] = await touchPopupResult; // Ask the popup to access the opener. const touchOpenerResult = once(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 once(ipcMain, 'answer'); expect(argv).to.include('--enable-sandbox'); }); it('should open windows with the options configured via setWindowOpenHandler handlers', 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([ once(app, 'web-contents-created') as Promise<[any, WebContents]>, once(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 => once(ipcMain, name))); w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'verify-ipc-sender' }); await done; }); describe('event handling', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); }); it('works for window events', async () => { const pageTitleUpdated = once(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 => once(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 => once(w.webContents, name))); w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'webcontents-events' }); await done; }); }); 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 once(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'); expect(test.nodeEvents).to.equal(true); expect(test.nodeTimers).to.equal(true); expect(test.nodeUrl).to.equal(true); 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 = once(w.webContents, 'did-attach-webview') as Promise<[any, WebContents]>; const webviewDomReady = once(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; 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 = once(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 = once(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 = once(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 = once(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 once(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 once(ipcMain, 'answer'); expect(content).to.equal('function'); } w.reload(); { const [, content] = await once(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, preload } } })); const webviewLoaded = once(ipcMain, 'webview-loaded'); w.loadFile(path.join(fixtures, 'api', 'new-window-webview.html')); await webviewLoaded; }); it('should open windows with the options configured via setWindowOpenHandler handlers', 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([ once(app, 'web-contents-created') as Promise<[any, WebContents]>, once(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 once(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 once(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 = once(w.webContents, 'enter-html-full-screen'); w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true); await enterHtmlFullScreen; expect(w.getSize()).to.deep.equal(size); }); }); describe('"defaultFontFamily" option', () => { it('can change the standard font family', async () => { const w = new BrowserWindow({ show: false, webPreferences: { defaultFontFamily: { standard: 'Impact' } } }); await w.loadFile(path.join(fixtures, 'pages', 'content.html')); const fontFamily = await w.webContents.executeJavaScript("window.getComputedStyle(document.getElementsByTagName('p')[0])['font-family']", true); expect(fontFamily).to.equal('Impact'); }); }); }); describe('beforeunload handler', function () { let w: 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 = once(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 once(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 once(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 once(w.webContents, 'console-message'); w.close(); await once(w.webContents, 'before-unload-fired'); w.close(); await once(w.webContents, 'before-unload-fired'); w.webContents.removeListener('destroyed', destroyListener); const wait = once(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 once(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 once(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 once(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'); }); }); // TODO(codebytere): figure out how to make these pass in CI on Windows. ifdescribe(process.platform !== 'win32')('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 once(ipcMain, 'pong'); expect(readyToShow).to.be.false('ready to show'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); }); it('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 once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.hide(); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } }); it('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 once(w, 'show'); } w.hide(); w.show(); const [, visibilityState] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); }); it('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 once(w, 'show'); } w.hide(); w.showInactive(); const [, visibilityState] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); }); 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 once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.minimize(); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } }); it('visibilityState remains visible if backgroundThrottling is disabled', async () => { const w = new BrowserWindow({ show: false, width: 100, height: 100, webPreferences: { backgroundThrottling: false, nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await once(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 = once(w, 'show'); w.show(); await shown1; const hidden = once(w, 'hide'); w.hide(); await hidden; const shown2 = once(w, 'show'); w.show(); await shown2; } finally { ipcMain.removeAllListeners('pong'); } }); }); 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 = once(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 = once(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 = once(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 = once(w, 'maximize'); const unmaximize = once(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 = once(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 }); let called = false; w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); w.webContents.on('dom-ready', () => { w.webContents.beginFrameSubscription(function () { // This callback might be called twice. if (called) return; called = true; // Pending endFrameSubscription to next tick can reliably reproduce // a crash which happens when nothing is returned in the callback. setTimeout().then(() => { 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 () => { /* Use temp directory for saving MHTML file since the write handle * gets passed to untrusted process and chromium will deny exec access to * the path. To perform this task, chromium requires that the path is one * of the browser controlled paths, refs https://chromium-review.googlesource.com/c/chromium/src/+/3774416 */ const tmpDir = await fs.promises.mkdtemp(path.resolve(os.tmpdir(), 'electron-mhtml-save-')); const savePageMHTMLPath = path.join(tmpDir, 'save_page.html'); const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageMHTMLPath, 'MHTML'); expect(fs.existsSync(savePageMHTMLPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.false('js path'); expect(fs.existsSync(savePageCssPath)).to.be.false('css path'); try { await fs.promises.unlink(savePageMHTMLPath); await fs.promises.rmdir(tmpDir); } catch {} }); 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(); }); // TODO(zcbenz): // This test does not run on Linux CI. See: // https://github.com/electron/electron/issues/28699 ifit(process.platform === 'linux' && !process.env.CI)('should bring a minimized maximized window back to maximized state', async () => { const w = new BrowserWindow({}); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMaximized()).to.equal(false); const restore = once(w, 'restore'); w.restore(); await restore; expect(w.isMaximized()).to.equal(true); }); }); // TODO(dsanders11): Enable once maximize event works on Linux again on CI ifdescribe(process.platform !== 'linux')('BrowserWindow.maximize()', () => { afterEach(closeAllWindows); it('should show the window if it is not currently shown', async () => { const w = new BrowserWindow({ show: false }); const hidden = once(w, 'hide'); let shown = once(w, 'show'); const maximize = once(w, 'maximize'); expect(w.isVisible()).to.be.false('visible'); w.maximize(); await maximize; await shown; expect(w.isMaximized()).to.be.true('maximized'); expect(w.isVisible()).to.be.true('visible'); // Even if the window is already maximized w.hide(); await hidden; expect(w.isVisible()).to.be.false('visible'); shown = once(w, 'show'); w.maximize(); await shown; expect(w.isVisible()).to.be.true('visible'); }); }); 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 = once(w, 'minimize'); w.minimize(); await minimize; w.unmaximize(); await setTimeout(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 setTimeout(1000); expectBoundsEqual(w.getSize(), initialSize); expectBoundsEqual(w.getPosition(), initialPosition); }); ifit(process.platform === 'darwin')('should not change size or position of a window which is functionally maximized', async () => { const { workArea } = screen.getPrimaryDisplay(); const bounds = { x: workArea.x, y: workArea.y, width: workArea.width, height: workArea.height }; const w = new BrowserWindow(bounds); w.unmaximize(); await setTimeout(1000); expectBoundsEqual(w.getBounds(), bounds); }); }); 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 = once(w, 'show'); // start fullscreen and hidden w.setFullScreen(true); w.show(); await shown; const leftFullScreen = once(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 = once(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 once(w, 'enter-full-screen'); // Wait a tick for the full-screen state to 'stick' await setTimeout(); w.setFullScreen(false); await once(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 = once(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 = once(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 = once(c, 'closed'); c.close(); await closed; // The child window list is not immediately cleared, so wait a tick until it's ready. await setTimeout(); expect(w.getChildWindows().length).to.equal(0); }); it('can handle child window close and reparent multiple times', async () => { const w = new BrowserWindow({ show: false }); let c: BrowserWindow | null; for (let i = 0; i < 5; i++) { c = new BrowserWindow({ show: false, parent: w }); const closed = once(c, 'closed'); c.close(); await closed; } await setTimeout(); expect(w.getChildWindows().length).to.equal(0); }); ifit(process.platform === 'darwin')('child window matches visibility when visibility changes', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); const wShow = once(w, 'show'); const cShow = once(c, 'show'); w.show(); c.show(); await Promise.all([wShow, cShow]); const minimized = once(w, 'minimize'); w.minimize(); await minimized; expect(w.isVisible()).to.be.false('parent is visible'); expect(c.isVisible()).to.be.false('child is visible'); const restored = once(w, 'restore'); w.restore(); await restored; expect(w.isVisible()).to.be.true('parent is visible'); expect(c.isVisible()).to.be.true('child is visible'); }); ifit(process.platform === 'darwin')('matches child window visibility when visibility changes', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); const wShow = once(w, 'show'); const cShow = once(c, 'show'); w.show(); c.show(); await Promise.all([wShow, cShow]); const minimized = once(c, 'minimize'); c.minimize(); await minimized; expect(c.isVisible()).to.be.false('child is visible'); const restored = once(c, 'restore'); c.restore(); await restored; expect(w.isVisible()).to.be.true('parent is visible'); expect(c.isVisible()).to.be.true('child is visible'); }); it('closes a grandchild window when a middle child window is destroyed', (done) => { const w = new BrowserWindow(); w.loadFile(path.join(fixtures, 'pages', 'base-page.html')); w.webContents.executeJavaScript('window.open("")'); w.webContents.on('did-create-window', async (window) => { const childWindow = new BrowserWindow({ parent: window }); await setTimeout(); window.close(); childWindow.on('closed', () => { expect(() => { BrowserWindow.getFocusedWindow(); }).to.not.throw(); done(); }); }); }); 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 = once(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 setTimeout(); expect(w.getChildWindows().length).to.equal(0); }); ifit(process.platform === 'darwin')('can reparent when the first parent is destroyed', async () => { const w1 = new BrowserWindow({ show: false }); const w2 = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); c.setParentWindow(w1); expect(w1.getChildWindows().length).to.equal(1); const closed = once(w1, 'closed'); w1.destroy(); await closed; c.setParentWindow(w2); await setTimeout(); const children = w2.getChildWindows(); expect(children[0]).to.equal(c); }); }); 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 = once(two, 'show'); two.show(); await twoShown; setTimeout(500).then(() => two.close()); await once(two, 'closed'); }; const one = new BrowserWindow({ width: 600, height: 400, parent: parentWindow, modal: true, show: false }); const oneShown = once(one, 'show'); one.show(); await oneShown; setTimeout(500).then(() => one.destroy()); await once(one, 'closed'); await createTwo(); }); ifit(process.platform !== 'darwin')('can disable and enable a window', () => { const w = new BrowserWindow({ show: false }); w.setEnabled(false); expect(w.isEnabled()).to.be.false('w.isEnabled()'); w.setEnabled(true); expect(w.isEnabled()).to.be.true('!w.isEnabled()'); }); 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 = once(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 = once(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; let serverUrl: string; before(async () => { server = http.createServer((request, response) => { response.end(); }); serverUrl = (await listen(server)).url; }); after(() => { server.close(); }); it('is true when the main frame is loading', async () => { const w = new BrowserWindow({ show: false }); const didStartLoading = once(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 = once(w.webContents, 'did-stop-loading'); w.webContents.loadURL(serverUrl); await didStopLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); const didStartLoading = once(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 = once(w.webContents, 'did-stop-loading'); w.webContents.loadURL(serverUrl); await didStopLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); const didStartLoading = once(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')('when fullscreen state is changed', () => { it('correctly remembers state prior to fullscreen change', async () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); w.setMenuBarVisibility(false); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; expect(w.fullScreen).to.be.true('not fullscreen'); const exitFS = once(w, 'leave-full-screen'); w.setFullScreen(false); await exitFS; expect(w.fullScreen).to.be.false('not fullscreen'); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); }); it('correctly remembers state prior to fullscreen change with autoHide', async () => { const w = new BrowserWindow({ show: false }); expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); w.autoHideMenuBar = true; expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); w.setMenuBarVisibility(false); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; expect(w.fullScreen).to.be.true('not fullscreen'); const exitFS = once(w, 'leave-full-screen'); w.setFullScreen(false); await exitFS; expect(w.fullScreen).to.be.false('not fullscreen'); expect(w.isMenuBarVisible()).to.be.false('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'); }); }); }); ifdescribe(process.platform === 'darwin')('isHiddenInMissionControl state', () => { it('with functions', () => { it('can be set with ignoreMissionControl constructor option', () => { const w = new BrowserWindow({ show: false, hiddenInMissionControl: true }); expect(w.isHiddenInMissionControl()).to.be.true('isHiddenInMissionControl'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isHiddenInMissionControl()).to.be.false('isHiddenInMissionControl'); w.setHiddenInMissionControl(true); expect(w.isHiddenInMissionControl()).to.be.true('isHiddenInMissionControl'); w.setHiddenInMissionControl(false); expect(w.isHiddenInMissionControl()).to.be.false('isHiddenInMissionControl'); }); }); }); // 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 = once(w, 'enter-full-screen'); w.kiosk = true; expect(w.isKiosk()).to.be.true('isKiosk'); await enterFullScreen; await setTimeout(); const leaveFullScreen = once(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 = once(w, 'enter-full-screen'); w.setKiosk(true); expect(w.isKiosk()).to.be.true('isKiosk'); await enterFullScreen; await setTimeout(); const leaveFullScreen = once(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 false and restored', async () => { const w = new BrowserWindow({ resizable: false }); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.resizable).to.be.false('resizable'); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.resizable).to.be.false('resizable'); }); it('default resizable flag should be restored after entering/exiting fullscreen', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.resizable).to.be.false('resizable'); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.resizable).to.be.true('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 = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; }); it('should be able to load a URL while transitioning to fullscreen', async () => { const w = new BrowserWindow({ fullscreen: true }); w.loadFile(path.join(fixtures, 'pages', 'c.html')); const load = once(w.webContents, 'did-finish-load'); const enterFS = once(w, 'enter-full-screen'); await Promise.all([enterFS, load]); expect(w.fullScreen).to.be.true(); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; }); it('can be changed with setFullScreen method', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await setTimeout(); const leaveFullScreen = once(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 setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); }); it('handles several HTML fullscreen transitions', async () => { const w = new BrowserWindow(); await w.loadFile(path.join(fixtures, 'pages', 'a.html')); expect(w.isFullScreen()).to.be.false('is fullscreen'); const enterFullScreen = once(w, 'enter-full-screen'); const leaveFullScreen = once(w, 'leave-full-screen'); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await enterFullScreen; await w.webContents.executeJavaScript('document.exitFullscreen()', true); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); await setTimeout(); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await enterFullScreen; await w.webContents.executeJavaScript('document.exitFullscreen()', true); 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'); const enterFS = emittedNTimes(w, 'enter-full-screen', 2); const leaveFS = emittedNTimes(w, 'leave-full-screen', 2); w.setFullScreen(true); w.setFullScreen(false); w.setFullScreen(true); w.setFullScreen(false); await Promise.all([enterFS, leaveFS]); expect(w.isFullScreen()).to.be.false('not fullscreen'); }); it('handles several chromium-initiated transitions in close proximity', async () => { const w = new BrowserWindow(); await w.loadFile(path.join(fixtures, 'pages', 'a.html')); expect(w.isFullScreen()).to.be.false('is fullscreen'); let enterCount = 0; let exitCount = 0; const done = new Promise<void>(resolve => { const checkDone = () => { if (enterCount === 2 && exitCount === 2) resolve(); }; w.webContents.on('enter-html-full-screen', () => { enterCount++; checkDone(); }); w.webContents.on('leave-html-full-screen', () => { exitCount++; checkDone(); }); }); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await done; }); it('handles HTML fullscreen transitions when fullscreenable is false', async () => { const w = new BrowserWindow({ fullscreenable: false }); await w.loadFile(path.join(fixtures, 'pages', 'a.html')); expect(w.isFullScreen()).to.be.false('is fullscreen'); let enterCount = 0; let exitCount = 0; const done = new Promise<void>((resolve, reject) => { const checkDone = () => { if (enterCount === 2 && exitCount === 2) resolve(); }; w.webContents.on('enter-html-full-screen', async () => { enterCount++; if (w.isFullScreen()) reject(new Error('w.isFullScreen should be false')); const isFS = await w.webContents.executeJavaScript('!!document.fullscreenElement'); if (!isFS) reject(new Error('Document should have fullscreen element')); checkDone(); }); w.webContents.on('leave-html-full-screen', () => { exitCount++; if (w.isFullScreen()) reject(new Error('w.isFullScreen should be false')); checkDone(); }); }); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await expect(done).to.eventually.be.fulfilled(); }); it('does not crash when exiting simpleFullScreen (properties)', async () => { const w = new BrowserWindow(); w.setSimpleFullScreen(true); await setTimeout(1000); w.setFullScreen(!w.isFullScreen()); }); it('does not crash when exiting simpleFullScreen (functions)', async () => { const w = new BrowserWindow(); w.simpleFullScreen = true; await setTimeout(1000); w.setFullScreen(!w.isFullScreen()); }); it('should not be changed by setKiosk method', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setKiosk(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); const leaveFullScreen = once(w, 'leave-full-screen'); w.setKiosk(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('isFullScreen'); }); it('should stay fullscreen if fullscreen before kiosk', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); w.setKiosk(true); w.setKiosk(false); // Wait enough time for a fullscreen change to take effect. await setTimeout(2000); expect(w.isFullScreen()).to.be.true('isFullScreen'); }); it('multiple windows inherit correct fullscreen state', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await setTimeout(1000); const w2 = new BrowserWindow({ show: false }); const enterFullScreen2 = once(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 = once(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(); }); it('should not call BrowserWindow show event', async () => { const w = new BrowserWindow({ show: false }); const shown = once(w, 'show'); w.show(); await shown; let showCalled = false; w.on('show', () => { showCalled = true; }); w.previewFile(__filename); await setTimeout(500); expect(showCalled).to.equal(false, 'should not have called show twice'); }); }); // TODO (jkleinsc) renable these tests on mas arm64 ifdescribe(!process.mas || process.arch !== 'arm64')('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 = once(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 = once(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 = once(app, 'browser-window-created') as Promise<[any, BrowserWindow]>; 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 = once(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 = once(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 = once(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 = once(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 = once(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 = once(w1, 'focus'); w1.webContents.focus(); await w1Focused; expect(w1.webContents.isFocused()).to.be.true('focuses window'); }); }); describe('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 = once(w.webContents, 'paint') as Promise<[any, Electron.Rectangle, Electron.NativeImage]>; 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 = once(w.webContents, 'paint') as Promise<[any, Electron.Rectangle, Electron.NativeImage]>; 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 = once(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 = once(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.stopPainting(); w.webContents.startPainting(); await once(w.webContents, 'paint') as [any, Electron.Rectangle, Electron.NativeImage]; 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 once(w.webContents, 'paint') as [any, Electron.Rectangle, Electron.NativeImage]; expect(w.webContents.getFrameRate()).to.equal(60); }); it('has default frame rate (property)', async () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await once(w.webContents, 'paint') as [any, Electron.Rectangle, Electron.NativeImage]; expect(w.webContents.frameRate).to.equal(60); }); it('sets custom frame rate (function)', async () => { const domReady = once(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.setFrameRate(30); await once(w.webContents, 'paint') as [any, Electron.Rectangle, Electron.NativeImage]; expect(w.webContents.getFrameRate()).to.equal(30); }); it('sets custom frame rate (property)', async () => { const domReady = once(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.frameRate = 30; await once(w.webContents, 'paint') as [any, Electron.Rectangle, Electron.NativeImage]; expect(w.webContents.frameRate).to.equal(30); }); }); }); describe('"transparent" option', () => { afterEach(closeAllWindows); ifit(process.platform !== 'linux')('correctly returns isMaximized() when the window is maximized then minimized', async () => { const w = new BrowserWindow({ frame: false, transparent: true }); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMaximized()).to.be.false(); expect(w.isMinimized()).to.be.true(); }); // 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 once(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 === 'darwin' && process.arch === 'x64')('should not display a visible background', async () => { const display = screen.getPrimaryDisplay(); const backgroundWindow = new BrowserWindow({ ...display.bounds, frame: false, backgroundColor: HexColors.GREEN, hasShadow: false }); await backgroundWindow.loadURL('about:blank'); const foregroundWindow = new BrowserWindow({ ...display.bounds, show: true, transparent: true, frame: false, hasShadow: false }); const colorFile = path.join(__dirname, 'fixtures', 'pages', 'half-background-color.html'); await foregroundWindow.loadFile(colorFile); await setTimeout(1000); 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, HexColors.GREEN)).to.be.true(); expect(areColorsSimilar(rightHalfColor, HexColors.RED)).to.be.true(); }); ifit(process.platform === 'darwin')('Allows setting a transparent window via CSS', async () => { const display = screen.getPrimaryDisplay(); const backgroundWindow = new BrowserWindow({ ...display.bounds, frame: false, backgroundColor: HexColors.PURPLE, hasShadow: false }); await backgroundWindow.loadURL('about:blank'); const foregroundWindow = new BrowserWindow({ ...display.bounds, frame: false, transparent: true, hasShadow: false, webPreferences: { contextIsolation: false, nodeIntegration: true } }); foregroundWindow.loadFile(path.join(__dirname, 'fixtures', 'pages', 'css-transparent.html')); await once(ipcMain, 'set-transparent'); await setTimeout(); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); expect(areColorsSimilar(centerColor, HexColors.PURPLE)).to.be.true(); }); // Linux and arm64 platforms (WOA and macOS) do not return any capture sources ifit(process.platform === 'darwin' && process.arch === 'x64')('should not make background transparent if falsy', async () => { const display = screen.getPrimaryDisplay(); for (const transparent of [false, undefined]) { const window = new BrowserWindow({ ...display.bounds, transparent }); await once(window, 'show'); await window.webContents.loadURL('data:text/html,<head><meta name="color-scheme" content="dark"></head>'); await setTimeout(500); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); window.close(); // color-scheme is set to dark so background should not be white expect(areColorsSimilar(centerColor, HexColors.WHITE)).to.be.false(); } }); }); describe('"backgroundColor" option', () => { afterEach(closeAllWindows); // Linux/WOA doesn't return any capture sources. ifit(process.platform === 'darwin')('should display the set color', async () => { const display = screen.getPrimaryDisplay(); const w = new BrowserWindow({ ...display.bounds, show: true, backgroundColor: HexColors.BLUE }); w.loadURL('about:blank'); await once(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, HexColors.BLUE)).to.be.true(); }); }); });
closed
electron/electron
https://github.com/electron/electron
39,614
[Bug]: non-fullscreenable, non-resizable child windows get fullscreened when being shown if the parent window is fullscreened
### 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 26.0.0 ### What operating system are you using? macOS ### Operating System Version macOS Ventura 13.2.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior I expect that if a child window that's configured to be non-fullscreenable is shown while the parent window is fullscreened, the child window won't get fullscreened. ### Actual Behavior Child window opens fullscreened for some reason and the main window crashes when the child is closed. ### Testcase Gist URL https://gist.github.com/pushkin-/3b4bcdb219eee85789e95f6d94ec8a92 ### Additional Information 1. full screen main window 2. click open window 3. notice that child window is fullscreened even though it shouldn't be able to get fullscreen 4. closing the window makes the parent window go black seems like the invocation of `BrowserWindow::show()` causes the `enter-full-screen` event to get emitted for some reason. https://github.com/electron/electron/assets/6374473/f96e2680-4938-4de6-b562-94f80c46ecfb
https://github.com/electron/electron/issues/39614
https://github.com/electron/electron/pull/39620
2affecd4dd26b9f0cf2644ec115635559f920480
33e66b5cd02d2b258b956022c482024c74c13b4b
2023-08-22T22:41:12Z
c++
2023-08-24T20:54:08Z
shell/browser/native_window_mac.mm
// 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_mac.h" #include <AvailabilityMacros.h> #include <objc/objc-runtime.h> #include <algorithm> #include <memory> #include <string> #include <utility> #include <vector> #include "base/mac/mac_util.h" #include "base/mac/scoped_cftyperef.h" #include "base/strings/sys_string_conversions.h" #include "components/remote_cocoa/app_shim/native_widget_ns_window_bridge.h" #include "components/remote_cocoa/browser/scoped_cg_window_id.h" #include "content/public/browser/browser_accessibility_state.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/desktop_media_id.h" #include "shell/browser/browser.h" #include "shell/browser/javascript_environment.h" #include "shell/browser/native_browser_view_mac.h" #include "shell/browser/ui/cocoa/electron_native_widget_mac.h" #include "shell/browser/ui/cocoa/electron_ns_window.h" #include "shell/browser/ui/cocoa/electron_ns_window_delegate.h" #include "shell/browser/ui/cocoa/electron_preview_item.h" #include "shell/browser/ui/cocoa/electron_touch_bar.h" #include "shell/browser/ui/cocoa/root_view_mac.h" #include "shell/browser/ui/cocoa/window_buttons_proxy.h" #include "shell/browser/ui/drag_util.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/window_list.h" #include "shell/common/gin_converters/gfx_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/node_includes.h" #include "shell/common/options_switches.h" #include "shell/common/process_util.h" #include "skia/ext/skia_utils_mac.h" #include "third_party/skia/include/core/SkRegion.h" #include "third_party/webrtc/modules/desktop_capture/mac/window_list_utils.h" #include "ui/base/hit_test.h" #include "ui/display/screen.h" #include "ui/gfx/skia_util.h" #include "ui/gl/gpu_switching_manager.h" #include "ui/views/background.h" #include "ui/views/cocoa/native_widget_mac_ns_window_host.h" #include "ui/views/widget/widget.h" #include "ui/views/window/native_frame_view_mac.h" @interface ElectronProgressBar : NSProgressIndicator @end @implementation ElectronProgressBar - (void)drawRect:(NSRect)dirtyRect { if (self.style != NSProgressIndicatorStyleBar) return; // Draw edges of rounded rect. NSRect rect = NSInsetRect([self bounds], 1.0, 1.0); CGFloat radius = rect.size.height / 2; NSBezierPath* bezier_path = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [bezier_path setLineWidth:2.0]; [[NSColor grayColor] set]; [bezier_path stroke]; // Fill the rounded rect. rect = NSInsetRect(rect, 2.0, 2.0); radius = rect.size.height / 2; bezier_path = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [bezier_path setLineWidth:1.0]; [bezier_path addClip]; // Calculate the progress width. rect.size.width = floor(rect.size.width * ([self doubleValue] / [self maxValue])); // Fill the progress bar with color blue. [[NSColor colorWithSRGBRed:0.2 green:0.6 blue:1 alpha:1] set]; NSRectFill(rect); } @end namespace gin { template <> struct Converter<electron::NativeWindowMac::VisualEffectState> { static bool FromV8(v8::Isolate* isolate, v8::Handle<v8::Value> val, electron::NativeWindowMac::VisualEffectState* out) { using VisualEffectState = electron::NativeWindowMac::VisualEffectState; std::string visual_effect_state; if (!ConvertFromV8(isolate, val, &visual_effect_state)) return false; if (visual_effect_state == "followWindow") { *out = VisualEffectState::kFollowWindow; } else if (visual_effect_state == "active") { *out = VisualEffectState::kActive; } else if (visual_effect_state == "inactive") { *out = VisualEffectState::kInactive; } else { return false; } return true; } }; } // namespace gin namespace electron { namespace { bool IsFramelessWindow(NSView* view) { NSWindow* nswindow = [view window]; if (![nswindow respondsToSelector:@selector(shell)]) return false; NativeWindow* window = [static_cast<ElectronNSWindow*>(nswindow) shell]; return window && !window->has_frame(); } IMP original_set_frame_size = nullptr; IMP original_view_did_move_to_superview = nullptr; // This method is directly called by NSWindow during a window resize on OSX // 10.10.0, beta 2. We must override it to prevent the content view from // shrinking. void SetFrameSize(NSView* self, SEL _cmd, NSSize size) { if (!IsFramelessWindow(self)) { auto original = reinterpret_cast<decltype(&SetFrameSize)>(original_set_frame_size); return original(self, _cmd, size); } // For frameless window, resize the view to cover full window. if ([self superview]) size = [[self superview] bounds].size; auto super_impl = reinterpret_cast<decltype(&SetFrameSize)>( [[self superclass] instanceMethodForSelector:_cmd]); super_impl(self, _cmd, size); } // The contentView gets moved around during certain full-screen operations. // This is less than ideal, and should eventually be removed. void ViewDidMoveToSuperview(NSView* self, SEL _cmd) { if (!IsFramelessWindow(self)) { // [BridgedContentView viewDidMoveToSuperview]; auto original = reinterpret_cast<decltype(&ViewDidMoveToSuperview)>( original_view_did_move_to_superview); if (original) original(self, _cmd); return; } [self setFrame:[[self superview] bounds]]; } // -[NSWindow orderWindow] does not handle reordering for children // windows. Their order is fixed to the attachment order (the last attached // window is on the top). Therefore, work around it by re-parenting in our // desired order. void ReorderChildWindowAbove(NSWindow* child_window, NSWindow* other_window) { NSWindow* parent = [child_window parentWindow]; DCHECK(parent); // `ordered_children` sorts children windows back to front. NSArray<NSWindow*>* children = [[child_window parentWindow] childWindows]; std::vector<std::pair<NSInteger, NSWindow*>> ordered_children; for (NSWindow* child in children) ordered_children.push_back({[child orderedIndex], child}); std::sort(ordered_children.begin(), ordered_children.end(), std::greater<>()); // If `other_window` is nullptr, place `child_window` in front of // all other children windows. if (other_window == nullptr) other_window = ordered_children.back().second; if (child_window == other_window) return; for (NSWindow* child in children) [parent removeChildWindow:child]; const bool relative_to_parent = parent == other_window; if (relative_to_parent) [parent addChildWindow:child_window ordered:NSWindowAbove]; // Re-parent children windows in the desired order. for (auto [ordered_index, child] : ordered_children) { if (child != child_window && child != other_window) { [parent addChildWindow:child ordered:NSWindowAbove]; } else if (child == other_window && !relative_to_parent) { [parent addChildWindow:other_window ordered:NSWindowAbove]; [parent addChildWindow:child_window ordered:NSWindowAbove]; } } } } // namespace NativeWindowMac::NativeWindowMac(const gin_helper::Dictionary& options, NativeWindow* parent) : NativeWindow(options, parent), root_view_(new RootViewMac(this)) { ui::NativeTheme::GetInstanceForNativeUi()->AddObserver(this); display::Screen::GetScreen()->AddObserver(this); int width = 800, height = 600; options.Get(options::kWidth, &width); options.Get(options::kHeight, &height); NSRect main_screen_rect = [[[NSScreen screens] firstObject] frame]; gfx::Rect bounds(round((NSWidth(main_screen_rect) - width) / 2), round((NSHeight(main_screen_rect) - height) / 2), width, height); bool resizable = true; options.Get(options::kResizable, &resizable); options.Get(options::kZoomToPageWidth, &zoom_to_page_width_); options.Get(options::kSimpleFullScreen, &always_simple_fullscreen_); options.GetOptional(options::kTrafficLightPosition, &traffic_light_position_); options.Get(options::kVisualEffectState, &visual_effect_state_); if (options.Has(options::kFullscreenWindowTitle)) { EmitWarning( node::Environment::GetCurrent(JavascriptEnvironment::GetIsolate()), "\"fullscreenWindowTitle\" option has been deprecated and is " "no-op now.", "electron"); } bool minimizable = true; options.Get(options::kMinimizable, &minimizable); bool maximizable = true; options.Get(options::kMaximizable, &maximizable); bool closable = true; options.Get(options::kClosable, &closable); std::string tabbingIdentifier; options.Get(options::kTabbingIdentifier, &tabbingIdentifier); std::string windowType; options.Get(options::kType, &windowType); bool hiddenInMissionControl = false; options.Get(options::kHiddenInMissionControl, &hiddenInMissionControl); bool useStandardWindow = true; // eventually deprecate separate "standardWindow" option in favor of // standard / textured window types options.Get(options::kStandardWindow, &useStandardWindow); if (windowType == "textured") { useStandardWindow = false; } // The window without titlebar is treated the same with frameless window. if (title_bar_style_ != TitleBarStyle::kNormal) set_has_frame(false); NSUInteger styleMask = NSWindowStyleMaskTitled; // The NSWindowStyleMaskFullSizeContentView style removes rounded corners // for frameless window. bool rounded_corner = true; options.Get(options::kRoundedCorners, &rounded_corner); if (!rounded_corner && !has_frame()) styleMask = NSWindowStyleMaskBorderless; if (minimizable) styleMask |= NSWindowStyleMaskMiniaturizable; if (closable) styleMask |= NSWindowStyleMaskClosable; if (resizable) styleMask |= NSWindowStyleMaskResizable; if (!useStandardWindow || transparent() || !has_frame()) styleMask |= NSWindowStyleMaskTexturedBackground; // Create views::Widget and assign window_ with it. // TODO(zcbenz): Get rid of the window_ in future. 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.native_widget = new ElectronNativeWidgetMac(this, windowType, styleMask, widget()); widget()->Init(std::move(params)); SetCanResize(resizable); window_ = static_cast<ElectronNSWindow*>( widget()->GetNativeWindow().GetNativeNSWindow()); RegisterDeleteDelegateCallback(base::BindOnce( [](NativeWindowMac* window) { if (window->window_) window->window_ = nil; if (window->buttons_proxy_) window->buttons_proxy_ = nil; }, this)); [window_ setEnableLargerThanScreen:enable_larger_than_screen()]; window_delegate_ = [[ElectronNSWindowDelegate alloc] initWithShell:this]; [window_ setDelegate:window_delegate_]; // Only use native parent window for non-modal windows. if (parent && !is_modal()) { SetParentWindow(parent); } if (transparent()) { // Setting the background color to clear will also hide the shadow. [window_ setBackgroundColor:[NSColor clearColor]]; } if (windowType == "desktop") { [window_ setLevel:kCGDesktopWindowLevel - 1]; [window_ setDisableKeyOrMainWindow:YES]; [window_ setCollectionBehavior:(NSWindowCollectionBehaviorCanJoinAllSpaces | NSWindowCollectionBehaviorStationary | NSWindowCollectionBehaviorIgnoresCycle)]; } if (windowType == "panel") { [window_ setLevel:NSFloatingWindowLevel]; } bool focusable; if (options.Get(options::kFocusable, &focusable) && !focusable) [window_ setDisableKeyOrMainWindow:YES]; if (transparent() || !has_frame()) { // Don't show title bar. [window_ setTitlebarAppearsTransparent:YES]; [window_ setTitleVisibility:NSWindowTitleHidden]; // Remove non-transparent corners, see // https://github.com/electron/electron/issues/517. [window_ setOpaque:NO]; // Show window buttons if titleBarStyle is not "normal". if (title_bar_style_ == TitleBarStyle::kNormal) { InternalSetWindowButtonVisibility(false); } else { buttons_proxy_ = [[WindowButtonsProxy alloc] initWithWindow:window_]; [buttons_proxy_ setHeight:titlebar_overlay_height()]; if (traffic_light_position_) { [buttons_proxy_ setMargin:*traffic_light_position_]; } else if (title_bar_style_ == TitleBarStyle::kHiddenInset) { // For macOS >= 11, while this value does not match official macOS apps // like Safari or Notes, it matches titleBarStyle's old implementation // before Electron <= 12. [buttons_proxy_ setMargin:gfx::Point(12, 11)]; } if (title_bar_style_ == TitleBarStyle::kCustomButtonsOnHover) { [buttons_proxy_ setShowOnHover:YES]; } else { // customButtonsOnHover does not show buttons initially. InternalSetWindowButtonVisibility(true); } } } // Create a tab only if tabbing identifier is specified and window has // a native title bar. if (tabbingIdentifier.empty() || transparent() || !has_frame()) { [window_ setTabbingMode:NSWindowTabbingModeDisallowed]; } else { [window_ setTabbingIdentifier:base::SysUTF8ToNSString(tabbingIdentifier)]; } // Resize to content bounds. bool use_content_size = false; options.Get(options::kUseContentSize, &use_content_size); if (!has_frame() || use_content_size) SetContentSize(gfx::Size(width, height)); // Enable the NSView to accept first mouse event. bool acceptsFirstMouse = false; options.Get(options::kAcceptFirstMouse, &acceptsFirstMouse); [window_ setAcceptsFirstMouse:acceptsFirstMouse]; // Disable auto-hiding cursor. bool disableAutoHideCursor = false; options.Get(options::kDisableAutoHideCursor, &disableAutoHideCursor); [window_ setDisableAutoHideCursor:disableAutoHideCursor]; SetHiddenInMissionControl(hiddenInMissionControl); // Set maximizable state last to ensure zoom button does not get reset // by calls to other APIs. SetMaximizable(maximizable); // Default content view. SetContentView(new views::View()); AddContentViewLayers(); UpdateWindowOriginalFrame(); original_level_ = [window_ level]; } NativeWindowMac::~NativeWindowMac() = default; void NativeWindowMac::SetContentView(views::View* view) { views::View* root_view = GetContentsView(); if (content_view()) root_view->RemoveChildView(content_view()); set_content_view(view); root_view->AddChildView(content_view()); root_view->Layout(); } void NativeWindowMac::Close() { if (!IsClosable()) { WindowList::WindowCloseCancelled(this); return; } if (fullscreen_transition_state() != FullScreenTransitionState::kNone) { SetHasDeferredWindowClose(true); return; } // Ensure we're detached from the parent window before closing. RemoveChildFromParentWindow(); while (!child_windows_.empty()) { auto* child = child_windows_.back(); child->RemoveChildFromParentWindow(); } // If a sheet is attached to the window when we call // [window_ performClose:nil], the window won't close properly // even after the user has ended the sheet. // Ensure it's closed before calling [window_ performClose:nil]. if ([window_ attachedSheet]) [window_ endSheet:[window_ attachedSheet]]; [window_ performClose:nil]; // Closing a sheet doesn't trigger windowShouldClose, // so we need to manually call it ourselves here. if (is_modal() && parent() && IsVisible()) { NotifyWindowCloseButtonClicked(); } } void NativeWindowMac::CloseImmediately() { // Ensure we're detached from the parent window before closing. RemoveChildFromParentWindow(); while (!child_windows_.empty()) { auto* child = child_windows_.back(); child->RemoveChildFromParentWindow(); } [window_ close]; } void NativeWindowMac::Focus(bool focus) { if (!IsVisible()) return; if (focus) { [[NSApplication sharedApplication] activateIgnoringOtherApps:NO]; [window_ makeKeyAndOrderFront:nil]; } else { [window_ orderOut:nil]; [window_ orderBack:nil]; } } bool NativeWindowMac::IsFocused() { return [window_ isKeyWindow]; } void NativeWindowMac::Show() { if (is_modal() && parent()) { NSWindow* window = parent()->GetNativeWindow().GetNativeNSWindow(); if ([window_ sheetParent] == nil) [window beginSheet:window_ completionHandler:^(NSModalResponse){ }]; return; } // Reattach the window to the parent to actually show it. if (parent()) InternalSetParentWindow(parent(), true); // This method is supposed to put focus on window, however if the app does not // have focus then "makeKeyAndOrderFront" will only show the window. [NSApp activateIgnoringOtherApps:YES]; [window_ makeKeyAndOrderFront:nil]; } void NativeWindowMac::ShowInactive() { // Reattach the window to the parent to actually show it. if (parent()) InternalSetParentWindow(parent(), true); [window_ orderFrontRegardless]; } void NativeWindowMac::Hide() { // If a sheet is attached to the window when we call [window_ orderOut:nil], // the sheet won't be able to show again on the same window. // Ensure it's closed before calling [window_ orderOut:nil]. if ([window_ attachedSheet]) [window_ endSheet:[window_ attachedSheet]]; if (is_modal() && parent()) { [window_ orderOut:nil]; [parent()->GetNativeWindow().GetNativeNSWindow() endSheet:window_]; return; } DetachChildren(); // Detach the window from the parent before. if (parent()) InternalSetParentWindow(parent(), false); [window_ orderOut:nil]; } bool NativeWindowMac::IsVisible() { bool occluded = [window_ occlusionState] == NSWindowOcclusionStateVisible; return [window_ isVisible] && !occluded && !IsMinimized(); } bool NativeWindowMac::IsEnabled() { return [window_ attachedSheet] == nil; } void NativeWindowMac::SetEnabled(bool enable) { if (!enable) { NSRect frame = [window_ frame]; NSWindow* window = [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, frame.size.width, frame.size.height) styleMask:NSWindowStyleMaskTitled backing:NSBackingStoreBuffered defer:NO]; [window setAlphaValue:0.5]; [window_ beginSheet:window completionHandler:^(NSModalResponse returnCode) { NSLog(@"main window disabled"); return; }]; } else if ([window_ attachedSheet]) { [window_ endSheet:[window_ attachedSheet]]; } } void NativeWindowMac::Maximize() { const bool is_visible = [window_ isVisible]; if (IsMaximized()) { if (!is_visible) ShowInactive(); return; } // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); [window_ zoom:nil]; if (!is_visible) { ShowInactive(); NotifyWindowMaximize(); } } void NativeWindowMac::Unmaximize() { // Bail if the last user set bounds were the same size as the window // screen (e.g. the user set the window to maximized via setBounds) // // Per docs during zoom: // > If there’s no saved user state because there has been no previous // > zoom,the size and location of the window don’t change. // // However, in classic Apple fashion, this is not the case in practice, // and the frame inexplicably becomes very tiny. We should prevent // zoom from being called if the window is being unmaximized and its // unmaximized window bounds are themselves functionally maximized. if (!IsMaximized() || user_set_bounds_maximized_) return; [window_ zoom:nil]; } bool NativeWindowMac::IsMaximized() { // It's possible for [window_ isZoomed] to be true // when the window is minimized or fullscreened. if (IsMinimized() || IsFullscreen()) return false; if (HasStyleMask(NSWindowStyleMaskResizable) != 0) return [window_ isZoomed]; NSRect rectScreen = GetAspectRatio() > 0.0 ? default_frame_for_zoom() : [[NSScreen mainScreen] visibleFrame]; return NSEqualRects([window_ frame], rectScreen); } void NativeWindowMac::Minimize() { if (IsMinimized()) return; // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); [window_ miniaturize:nil]; } void NativeWindowMac::Restore() { [window_ deminiaturize:nil]; } bool NativeWindowMac::IsMinimized() { return [window_ isMiniaturized]; } bool NativeWindowMac::HandleDeferredClose() { if (has_deferred_window_close_) { SetHasDeferredWindowClose(false); Close(); return true; } return false; } void NativeWindowMac::RemoveChildWindow(NativeWindow* child) { child_windows_.remove_if([&child](NativeWindow* w) { return (w == child); }); [window_ removeChildWindow:child->GetNativeWindow().GetNativeNSWindow()]; } void NativeWindowMac::RemoveChildFromParentWindow() { if (parent() && !is_modal()) { parent()->RemoveChildWindow(this); NativeWindow::SetParentWindow(nullptr); } } void NativeWindowMac::AttachChildren() { for (auto* child : child_windows_) { auto* child_nswindow = child->GetNativeWindow().GetNativeNSWindow(); if ([child_nswindow parentWindow] == window_) continue; // Attaching a window as a child window resets its window level, so // save and restore it afterwards. NSInteger level = window_.level; [window_ addChildWindow:child_nswindow ordered:NSWindowAbove]; [window_ setLevel:level]; } } void NativeWindowMac::DetachChildren() { DCHECK(child_windows_.size() == [[window_ childWindows] count]); // Hide all children before hiding/minimizing the window. // NativeWidgetNSWindowBridge::NotifyVisibilityChangeDown() // will DCHECK otherwise. for (auto* child : child_windows_) { [child->GetNativeWindow().GetNativeNSWindow() orderOut:nil]; } } void NativeWindowMac::SetFullScreen(bool fullscreen) { if (!has_frame() && !HasStyleMask(NSWindowStyleMaskTitled)) return; // [NSWindow -toggleFullScreen] is an asynchronous operation, which means // that it's possible to call it while a fullscreen transition is currently // in process. This can create weird behavior (incl. phantom windows), // so we want to schedule a transition for when the current one has completed. if (fullscreen_transition_state() != FullScreenTransitionState::kNone) { if (!pending_transitions_.empty()) { bool last_pending = pending_transitions_.back(); // Only push new transitions if they're different than the last transition // in the queue. if (last_pending != fullscreen) pending_transitions_.push(fullscreen); } else { pending_transitions_.push(fullscreen); } return; } if (fullscreen == IsFullscreen() || !IsFullScreenable()) return; // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); // This needs to be set here because it can be the case that // SetFullScreen is called by a user before windowWillEnterFullScreen // or windowWillExitFullScreen are invoked, and so a potential transition // could be dropped. fullscreen_transition_state_ = fullscreen ? FullScreenTransitionState::kEntering : FullScreenTransitionState::kExiting; [window_ toggleFullScreenMode:nil]; } bool NativeWindowMac::IsFullscreen() const { return HasStyleMask(NSWindowStyleMaskFullScreen); } void NativeWindowMac::SetBounds(const gfx::Rect& bounds, bool animate) { // Do nothing if in fullscreen mode. if (IsFullscreen()) return; // Check size constraints since setFrame does not check it. gfx::Size size = bounds.size(); size.SetToMax(GetMinimumSize()); gfx::Size max_size = GetMaximumSize(); if (!max_size.IsEmpty()) size.SetToMin(max_size); NSRect cocoa_bounds = NSMakeRect(bounds.x(), 0, size.width(), size.height()); // Flip coordinates based on the primary screen. NSScreen* screen = [[NSScreen screens] firstObject]; cocoa_bounds.origin.y = NSHeight([screen frame]) - size.height() - bounds.y(); [window_ setFrame:cocoa_bounds display:YES animate:animate]; user_set_bounds_maximized_ = IsMaximized() ? true : false; UpdateWindowOriginalFrame(); } gfx::Rect NativeWindowMac::GetBounds() { NSRect frame = [window_ frame]; gfx::Rect bounds(frame.origin.x, 0, NSWidth(frame), NSHeight(frame)); NSScreen* screen = [[NSScreen screens] firstObject]; bounds.set_y(NSHeight([screen frame]) - NSMaxY(frame)); return bounds; } bool NativeWindowMac::IsNormal() { return NativeWindow::IsNormal() && !IsSimpleFullScreen(); } gfx::Rect NativeWindowMac::GetNormalBounds() { if (IsNormal()) { return GetBounds(); } NSRect frame = original_frame_; gfx::Rect bounds(frame.origin.x, 0, NSWidth(frame), NSHeight(frame)); NSScreen* screen = [[NSScreen screens] firstObject]; bounds.set_y(NSHeight([screen frame]) - NSMaxY(frame)); return bounds; // Works on OS_WIN ! // return widget()->GetRestoredBounds(); } void NativeWindowMac::SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints) { auto convertSize = [this](const gfx::Size& size) { // Our frameless window still has titlebar attached, so setting contentSize // will result in actual content size being larger. if (!has_frame()) { NSRect frame = NSMakeRect(0, 0, size.width(), size.height()); NSRect content = [window_ originalContentRectForFrameRect:frame]; return content.size; } else { return NSMakeSize(size.width(), size.height()); } }; NSView* content = [window_ contentView]; if (size_constraints.HasMinimumSize()) { NSSize min_size = convertSize(size_constraints.GetMinimumSize()); [window_ setContentMinSize:[content convertSize:min_size toView:nil]]; } if (size_constraints.HasMaximumSize()) { NSSize max_size = convertSize(size_constraints.GetMaximumSize()); [window_ setContentMaxSize:[content convertSize:max_size toView:nil]]; } NativeWindow::SetContentSizeConstraints(size_constraints); } bool NativeWindowMac::MoveAbove(const std::string& sourceId) { const content::DesktopMediaID id = content::DesktopMediaID::Parse(sourceId); if (id.type != content::DesktopMediaID::TYPE_WINDOW) return false; // Check if the window source is valid. const CGWindowID window_id = id.id; if (!webrtc::GetWindowOwnerPid(window_id)) return false; if (!parent() || is_modal()) { [window_ orderWindow:NSWindowAbove relativeTo:window_id]; } else { NSWindow* other_window = [NSApp windowWithWindowNumber:window_id]; ReorderChildWindowAbove(window_, other_window); } return true; } void NativeWindowMac::MoveTop() { if (!parent() || is_modal()) { [window_ orderWindow:NSWindowAbove relativeTo:0]; } else { ReorderChildWindowAbove(window_, nullptr); } } void NativeWindowMac::SetResizable(bool resizable) { ScopedDisableResize disable_resize; SetStyleMask(resizable, NSWindowStyleMaskResizable); // Right now, resizable and fullscreenable are decoupled in // documentation and on Windows/Linux. Chromium disables // fullscreenability if resizability is false on macOS as well // as disabling the maximize traffic light unless the window // is both resizable and maximizable. To work around this, we want // to match behavior on other platforms by disabiliting the maximize // button but keeping fullscreenability enabled. // TODO(codebytere): refactor this once we have a better solution. SetCanResize(resizable); if (!resizable) { SetFullScreenable(true); [[window_ standardWindowButton:NSWindowZoomButton] setEnabled:false]; } else { SetFullScreenable(true); [[window_ standardWindowButton:NSWindowZoomButton] setEnabled:IsFullScreenable()]; } } bool NativeWindowMac::IsResizable() { bool in_fs_transition = fullscreen_transition_state() != FullScreenTransitionState::kNone; bool has_rs_mask = HasStyleMask(NSWindowStyleMaskResizable); return has_rs_mask && !IsFullscreen() && !in_fs_transition; } void NativeWindowMac::SetMovable(bool movable) { [window_ setMovable:movable]; } bool NativeWindowMac::IsMovable() { return [window_ isMovable]; } void NativeWindowMac::SetMinimizable(bool minimizable) { SetStyleMask(minimizable, NSWindowStyleMaskMiniaturizable); } bool NativeWindowMac::IsMinimizable() { return HasStyleMask(NSWindowStyleMaskMiniaturizable); } void NativeWindowMac::SetMaximizable(bool maximizable) { maximizable_ = maximizable; [[window_ standardWindowButton:NSWindowZoomButton] setEnabled:maximizable]; } bool NativeWindowMac::IsMaximizable() { return [[window_ standardWindowButton:NSWindowZoomButton] isEnabled]; } void NativeWindowMac::SetFullScreenable(bool fullscreenable) { SetCollectionBehavior(fullscreenable, NSWindowCollectionBehaviorFullScreenPrimary); // On EL Capitan this flag is required to hide fullscreen button. SetCollectionBehavior(!fullscreenable, NSWindowCollectionBehaviorFullScreenAuxiliary); } bool NativeWindowMac::IsFullScreenable() { NSUInteger collectionBehavior = [window_ collectionBehavior]; return collectionBehavior & NSWindowCollectionBehaviorFullScreenPrimary; } void NativeWindowMac::SetClosable(bool closable) { SetStyleMask(closable, NSWindowStyleMaskClosable); } bool NativeWindowMac::IsClosable() { return HasStyleMask(NSWindowStyleMaskClosable); } void NativeWindowMac::SetAlwaysOnTop(ui::ZOrderLevel z_order, const std::string& level_name, int relative_level) { if (z_order == ui::ZOrderLevel::kNormal) { SetWindowLevel(NSNormalWindowLevel); return; } int level = NSNormalWindowLevel; if (level_name == "floating") { level = NSFloatingWindowLevel; } else if (level_name == "torn-off-menu") { level = NSTornOffMenuWindowLevel; } else if (level_name == "modal-panel") { level = NSModalPanelWindowLevel; } else if (level_name == "main-menu") { level = NSMainMenuWindowLevel; } else if (level_name == "status") { level = NSStatusWindowLevel; } else if (level_name == "pop-up-menu") { level = NSPopUpMenuWindowLevel; } else if (level_name == "screen-saver") { level = NSScreenSaverWindowLevel; } SetWindowLevel(level + relative_level); } std::string NativeWindowMac::GetAlwaysOnTopLevel() { std::string level_name = "normal"; int level = [window_ level]; if (level == NSFloatingWindowLevel) { level_name = "floating"; } else if (level == NSTornOffMenuWindowLevel) { level_name = "torn-off-menu"; } else if (level == NSModalPanelWindowLevel) { level_name = "modal-panel"; } else if (level == NSMainMenuWindowLevel) { level_name = "main-menu"; } else if (level == NSStatusWindowLevel) { level_name = "status"; } else if (level == NSPopUpMenuWindowLevel) { level_name = "pop-up-menu"; } else if (level == NSScreenSaverWindowLevel) { level_name = "screen-saver"; } return level_name; } void NativeWindowMac::SetWindowLevel(int unbounded_level) { int level = std::min( std::max(unbounded_level, CGWindowLevelForKey(kCGMinimumWindowLevelKey)), CGWindowLevelForKey(kCGMaximumWindowLevelKey)); ui::ZOrderLevel z_order_level = level == NSNormalWindowLevel ? ui::ZOrderLevel::kNormal : ui::ZOrderLevel::kFloatingWindow; bool did_z_order_level_change = z_order_level != GetZOrderLevel(); was_maximizable_ = IsMaximizable(); // We need to explicitly keep the NativeWidget up to date, since it stores the // window level in a local variable, rather than reading it from the NSWindow. // Unfortunately, it results in a second setLevel call. It's not ideal, but we // don't expect this to cause any user-visible jank. widget()->SetZOrderLevel(z_order_level); [window_ setLevel:level]; // Set level will make the zoom button revert to default, probably // a bug of Cocoa or macOS. SetMaximizable(was_maximizable_); // This must be notified at the very end or IsAlwaysOnTop // will not yet have been updated to reflect the new status if (did_z_order_level_change) NativeWindow::NotifyWindowAlwaysOnTopChanged(); } ui::ZOrderLevel NativeWindowMac::GetZOrderLevel() { return widget()->GetZOrderLevel(); } void NativeWindowMac::Center() { [window_ center]; } void NativeWindowMac::Invalidate() { [[window_ contentView] setNeedsDisplay:YES]; } void NativeWindowMac::SetTitle(const std::string& title) { [window_ setTitle:base::SysUTF8ToNSString(title)]; if (buttons_proxy_) [buttons_proxy_ redraw]; } std::string NativeWindowMac::GetTitle() { return base::SysNSStringToUTF8([window_ title]); } void NativeWindowMac::FlashFrame(bool flash) { if (flash) { attention_request_id_ = [NSApp requestUserAttention:NSInformationalRequest]; } else { [NSApp cancelUserAttentionRequest:attention_request_id_]; attention_request_id_ = 0; } } void NativeWindowMac::SetSkipTaskbar(bool skip) {} bool NativeWindowMac::IsExcludedFromShownWindowsMenu() { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); return [window isExcludedFromWindowsMenu]; } void NativeWindowMac::SetExcludedFromShownWindowsMenu(bool excluded) { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); [window setExcludedFromWindowsMenu:excluded]; } void NativeWindowMac::OnDisplayMetricsChanged(const display::Display& display, uint32_t changed_metrics) { // We only want to force screen recalibration if we're in simpleFullscreen // mode. if (!is_simple_fullscreen_) return; content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&NativeWindow::UpdateFrame, GetWeakPtr())); } void NativeWindowMac::SetSimpleFullScreen(bool simple_fullscreen) { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); if (simple_fullscreen && !is_simple_fullscreen_) { is_simple_fullscreen_ = true; // Take note of the current window size and level if (IsNormal()) { UpdateWindowOriginalFrame(); original_level_ = [window_ level]; } simple_fullscreen_options_ = [NSApp currentSystemPresentationOptions]; simple_fullscreen_mask_ = [window styleMask]; // We can simulate the pre-Lion fullscreen by auto-hiding the dock and menu // bar NSApplicationPresentationOptions options = NSApplicationPresentationAutoHideDock | NSApplicationPresentationAutoHideMenuBar; [NSApp setPresentationOptions:options]; was_maximizable_ = IsMaximizable(); was_movable_ = IsMovable(); NSRect fullscreenFrame = [window.screen frame]; // If our app has dock hidden, set the window level higher so another app's // menu bar doesn't appear on top of our fullscreen app. if ([[NSRunningApplication currentApplication] activationPolicy] != NSApplicationActivationPolicyRegular) { window.level = NSPopUpMenuWindowLevel; } // Always hide the titlebar in simple fullscreen mode. // // Note that we must remove the NSWindowStyleMaskTitled style instead of // using the [window_ setTitleVisibility:], as the latter would leave the // window with rounded corners. SetStyleMask(false, NSWindowStyleMaskTitled); if (!window_button_visibility_.has_value()) { // Lets keep previous behaviour - hide window controls in titled // fullscreen mode when not specified otherwise. InternalSetWindowButtonVisibility(false); } [window setFrame:fullscreenFrame display:YES animate:YES]; // Fullscreen windows can't be resized, minimized, maximized, or moved SetMinimizable(false); SetResizable(false); SetMaximizable(false); SetMovable(false); } else if (!simple_fullscreen && is_simple_fullscreen_) { is_simple_fullscreen_ = false; [window setFrame:original_frame_ display:YES animate:YES]; window.level = original_level_; [NSApp setPresentationOptions:simple_fullscreen_options_]; // Restore original style mask ScopedDisableResize disable_resize; [window_ setStyleMask:simple_fullscreen_mask_]; // Restore window manipulation abilities SetMaximizable(was_maximizable_); SetMovable(was_movable_); // Restore default window controls visibility state. if (!window_button_visibility_.has_value()) { bool visibility; if (has_frame()) visibility = true; else visibility = title_bar_style_ != TitleBarStyle::kNormal; InternalSetWindowButtonVisibility(visibility); } if (buttons_proxy_) [buttons_proxy_ redraw]; } } bool NativeWindowMac::IsSimpleFullScreen() { return is_simple_fullscreen_; } void NativeWindowMac::SetKiosk(bool kiosk) { if (kiosk && !is_kiosk_) { kiosk_options_ = [NSApp currentSystemPresentationOptions]; NSApplicationPresentationOptions options = NSApplicationPresentationHideDock | NSApplicationPresentationHideMenuBar | NSApplicationPresentationDisableAppleMenu | NSApplicationPresentationDisableProcessSwitching | NSApplicationPresentationDisableForceQuit | NSApplicationPresentationDisableSessionTermination | NSApplicationPresentationDisableHideApplication; [NSApp setPresentationOptions:options]; is_kiosk_ = true; fullscreen_before_kiosk_ = IsFullscreen(); if (!fullscreen_before_kiosk_) SetFullScreen(true); } else if (!kiosk && is_kiosk_) { is_kiosk_ = false; if (!fullscreen_before_kiosk_) SetFullScreen(false); // Set presentation options *after* asynchronously exiting // fullscreen to ensure they take effect. [NSApp setPresentationOptions:kiosk_options_]; } } bool NativeWindowMac::IsKiosk() { return is_kiosk_; } void NativeWindowMac::SetBackgroundColor(SkColor color) { base::ScopedCFTypeRef<CGColorRef> cgcolor( skia::CGColorCreateFromSkColor(color)); [[[window_ contentView] layer] setBackgroundColor:cgcolor]; } SkColor NativeWindowMac::GetBackgroundColor() { CGColorRef color = [[[window_ contentView] layer] backgroundColor]; if (!color) return SK_ColorTRANSPARENT; return skia::CGColorRefToSkColor(color); } void NativeWindowMac::SetHasShadow(bool has_shadow) { [window_ setHasShadow:has_shadow]; } bool NativeWindowMac::HasShadow() { return [window_ hasShadow]; } void NativeWindowMac::InvalidateShadow() { [window_ invalidateShadow]; } void NativeWindowMac::SetOpacity(const double opacity) { const double boundedOpacity = std::clamp(opacity, 0.0, 1.0); [window_ setAlphaValue:boundedOpacity]; } double NativeWindowMac::GetOpacity() { return [window_ alphaValue]; } void NativeWindowMac::SetRepresentedFilename(const std::string& filename) { [window_ setRepresentedFilename:base::SysUTF8ToNSString(filename)]; if (buttons_proxy_) [buttons_proxy_ redraw]; } std::string NativeWindowMac::GetRepresentedFilename() { return base::SysNSStringToUTF8([window_ representedFilename]); } void NativeWindowMac::SetDocumentEdited(bool edited) { [window_ setDocumentEdited:edited]; if (buttons_proxy_) [buttons_proxy_ redraw]; } bool NativeWindowMac::IsDocumentEdited() { return [window_ isDocumentEdited]; } bool NativeWindowMac::IsHiddenInMissionControl() { NSUInteger collectionBehavior = [window_ collectionBehavior]; return collectionBehavior & NSWindowCollectionBehaviorTransient; } void NativeWindowMac::SetHiddenInMissionControl(bool hidden) { SetCollectionBehavior(hidden, NSWindowCollectionBehaviorTransient); } void NativeWindowMac::SetIgnoreMouseEvents(bool ignore, bool forward) { [window_ setIgnoresMouseEvents:ignore]; if (!ignore) { SetForwardMouseMessages(NO); } else { SetForwardMouseMessages(forward); } } void NativeWindowMac::SetContentProtection(bool enable) { [window_ setSharingType:enable ? NSWindowSharingNone : NSWindowSharingReadOnly]; } void NativeWindowMac::SetFocusable(bool focusable) { // No known way to unfocus the window if it had the focus. Here we do not // want to call Focus(false) because it moves the window to the back, i.e. // at the bottom in term of z-order. [window_ setDisableKeyOrMainWindow:!focusable]; } bool NativeWindowMac::IsFocusable() { return ![window_ disableKeyOrMainWindow]; } void NativeWindowMac::AddBrowserView(NativeBrowserView* view) { [CATransaction begin]; [CATransaction setDisableActions:YES]; if (!view) { [CATransaction commit]; return; } add_browser_view(view); if (view->GetInspectableWebContentsView()) { auto* native_view = view->GetInspectableWebContentsView() ->GetNativeView() .GetNativeNSView(); [[window_ contentView] addSubview:native_view positioned:NSWindowAbove relativeTo:nil]; native_view.hidden = NO; } [CATransaction commit]; } void NativeWindowMac::RemoveBrowserView(NativeBrowserView* view) { [CATransaction begin]; [CATransaction setDisableActions:YES]; if (!view) { [CATransaction commit]; return; } if (view->GetInspectableWebContentsView()) [view->GetInspectableWebContentsView()->GetNativeView().GetNativeNSView() removeFromSuperview]; remove_browser_view(view); [CATransaction commit]; } void NativeWindowMac::SetTopBrowserView(NativeBrowserView* view) { [CATransaction begin]; [CATransaction setDisableActions:YES]; if (!view) { [CATransaction commit]; return; } remove_browser_view(view); add_browser_view(view); if (view->GetInspectableWebContentsView()) { auto* native_view = view->GetInspectableWebContentsView() ->GetNativeView() .GetNativeNSView(); [[window_ contentView] addSubview:native_view positioned:NSWindowAbove relativeTo:nil]; native_view.hidden = NO; } [CATransaction commit]; } void NativeWindowMac::SetParentWindow(NativeWindow* parent) { InternalSetParentWindow(parent, IsVisible()); } gfx::NativeView NativeWindowMac::GetNativeView() const { return [window_ contentView]; } gfx::NativeWindow NativeWindowMac::GetNativeWindow() const { return window_; } gfx::AcceleratedWidget NativeWindowMac::GetAcceleratedWidget() const { return [window_ windowNumber]; } content::DesktopMediaID NativeWindowMac::GetDesktopMediaID() const { auto desktop_media_id = content::DesktopMediaID( content::DesktopMediaID::TYPE_WINDOW, GetAcceleratedWidget()); // c.f. // https://source.chromium.org/chromium/chromium/src/+/main:chrome/browser/media/webrtc/native_desktop_media_list.cc;l=775-780;drc=79502ab47f61bff351426f57f576daef02b1a8dc // Refs https://github.com/electron/electron/pull/30507 // TODO(deepak1556): Match upstream for `kWindowCaptureMacV2` #if 0 if (remote_cocoa::ScopedCGWindowID::Get(desktop_media_id.id)) { desktop_media_id.window_id = desktop_media_id.id; } #endif return desktop_media_id; } NativeWindowHandle NativeWindowMac::GetNativeWindowHandle() const { return [window_ contentView]; } void NativeWindowMac::SetProgressBar(double progress, const NativeWindow::ProgressState state) { NSDockTile* dock_tile = [NSApp dockTile]; // Sometimes macOS would install a default contentView for dock, we must // verify whether NSProgressIndicator has been installed. bool first_time = !dock_tile.contentView || [[dock_tile.contentView subviews] count] == 0 || ![[[dock_tile.contentView subviews] lastObject] isKindOfClass:[NSProgressIndicator class]]; // For the first time API invoked, we need to create a ContentView in // DockTile. if (first_time) { NSImageView* image_view = [[NSImageView alloc] init]; [image_view setImage:[NSApp applicationIconImage]]; [dock_tile setContentView:image_view]; NSRect frame = NSMakeRect(0.0f, 0.0f, dock_tile.size.width, 15.0); NSProgressIndicator* progress_indicator = [[ElectronProgressBar alloc] initWithFrame:frame]; [progress_indicator setStyle:NSProgressIndicatorStyleBar]; [progress_indicator setIndeterminate:NO]; [progress_indicator setBezeled:YES]; [progress_indicator setMinValue:0]; [progress_indicator setMaxValue:1]; [progress_indicator setHidden:NO]; [dock_tile.contentView addSubview:progress_indicator]; } NSProgressIndicator* progress_indicator = static_cast<NSProgressIndicator*>( [[[dock_tile contentView] subviews] lastObject]); if (progress < 0) { [progress_indicator setHidden:YES]; } else if (progress > 1) { [progress_indicator setHidden:NO]; [progress_indicator setIndeterminate:YES]; [progress_indicator setDoubleValue:1]; } else { [progress_indicator setHidden:NO]; [progress_indicator setDoubleValue:progress]; } [dock_tile display]; } void NativeWindowMac::SetOverlayIcon(const gfx::Image& overlay, const std::string& description) {} void NativeWindowMac::SetVisibleOnAllWorkspaces(bool visible, bool visibleOnFullScreen, bool skipTransformProcessType) { // In order for NSWindows to be visible on fullscreen we need to invoke // app.dock.hide() since Apple changed the underlying functionality of // NSWindows starting with 10.14 to disallow NSWindows from floating on top of // fullscreen apps. if (!skipTransformProcessType) { if (visibleOnFullScreen) { Browser::Get()->DockHide(); } else { Browser::Get()->DockShow(JavascriptEnvironment::GetIsolate()); } } SetCollectionBehavior(visible, NSWindowCollectionBehaviorCanJoinAllSpaces); SetCollectionBehavior(visibleOnFullScreen, NSWindowCollectionBehaviorFullScreenAuxiliary); } bool NativeWindowMac::IsVisibleOnAllWorkspaces() { NSUInteger collectionBehavior = [window_ collectionBehavior]; return collectionBehavior & NSWindowCollectionBehaviorCanJoinAllSpaces; } void NativeWindowMac::SetAutoHideCursor(bool auto_hide) { [window_ setDisableAutoHideCursor:!auto_hide]; } void NativeWindowMac::UpdateVibrancyRadii(bool fullscreen) { NSVisualEffectView* vibrantView = [window_ vibrantView]; if (vibrantView != nil && !vibrancy_type_.empty()) { const bool no_rounded_corner = !HasStyleMask(NSWindowStyleMaskTitled); if (!has_frame() && !is_modal() && !no_rounded_corner) { CGFloat radius; if (fullscreen) { radius = 0.0f; } else if (@available(macOS 11.0, *)) { radius = 9.0f; } else { // Smaller corner radius on versions prior to Big Sur. radius = 5.0f; } CGFloat dimension = 2 * radius + 1; NSSize size = NSMakeSize(dimension, dimension); NSImage* maskImage = [NSImage imageWithSize:size flipped:NO drawingHandler:^BOOL(NSRect rect) { NSBezierPath* bezierPath = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [[NSColor blackColor] set]; [bezierPath fill]; return YES; }]; [maskImage setCapInsets:NSEdgeInsetsMake(radius, radius, radius, radius)]; [maskImage setResizingMode:NSImageResizingModeStretch]; [vibrantView setMaskImage:maskImage]; [window_ setCornerMask:maskImage]; } } } void NativeWindowMac::UpdateWindowOriginalFrame() { original_frame_ = [window_ frame]; } void NativeWindowMac::SetVibrancy(const std::string& type) { NSVisualEffectView* vibrantView = [window_ vibrantView]; if (type.empty()) { if (vibrantView == nil) return; [vibrantView removeFromSuperview]; [window_ setVibrantView:nil]; return; } NSVisualEffectMaterial vibrancyType{}; if (type == "titlebar") { vibrancyType = NSVisualEffectMaterialTitlebar; } else if (type == "selection") { vibrancyType = NSVisualEffectMaterialSelection; } else if (type == "menu") { vibrancyType = NSVisualEffectMaterialMenu; } else if (type == "popover") { vibrancyType = NSVisualEffectMaterialPopover; } else if (type == "sidebar") { vibrancyType = NSVisualEffectMaterialSidebar; } else if (type == "header") { vibrancyType = NSVisualEffectMaterialHeaderView; } else if (type == "sheet") { vibrancyType = NSVisualEffectMaterialSheet; } else if (type == "window") { vibrancyType = NSVisualEffectMaterialWindowBackground; } else if (type == "hud") { vibrancyType = NSVisualEffectMaterialHUDWindow; } else if (type == "fullscreen-ui") { vibrancyType = NSVisualEffectMaterialFullScreenUI; } else if (type == "tooltip") { vibrancyType = NSVisualEffectMaterialToolTip; } else if (type == "content") { vibrancyType = NSVisualEffectMaterialContentBackground; } else if (type == "under-window") { vibrancyType = NSVisualEffectMaterialUnderWindowBackground; } else if (type == "under-page") { vibrancyType = NSVisualEffectMaterialUnderPageBackground; } if (vibrancyType) { vibrancy_type_ = type; if (vibrantView == nil) { vibrantView = [[NSVisualEffectView alloc] initWithFrame:[[window_ contentView] bounds]]; [window_ setVibrantView:vibrantView]; [vibrantView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable]; [vibrantView setBlendingMode:NSVisualEffectBlendingModeBehindWindow]; if (visual_effect_state_ == VisualEffectState::kActive) { [vibrantView setState:NSVisualEffectStateActive]; } else if (visual_effect_state_ == VisualEffectState::kInactive) { [vibrantView setState:NSVisualEffectStateInactive]; } else { [vibrantView setState:NSVisualEffectStateFollowsWindowActiveState]; } [[window_ contentView] addSubview:vibrantView positioned:NSWindowBelow relativeTo:nil]; UpdateVibrancyRadii(IsFullscreen()); } [vibrantView setMaterial:vibrancyType]; } } void NativeWindowMac::SetWindowButtonVisibility(bool visible) { window_button_visibility_ = visible; if (buttons_proxy_) { if (visible) [buttons_proxy_ redraw]; [buttons_proxy_ setVisible:visible]; } if (title_bar_style_ != TitleBarStyle::kCustomButtonsOnHover) InternalSetWindowButtonVisibility(visible); NotifyLayoutWindowControlsOverlay(); } bool NativeWindowMac::GetWindowButtonVisibility() const { return ![window_ standardWindowButton:NSWindowZoomButton].hidden || ![window_ standardWindowButton:NSWindowMiniaturizeButton].hidden || ![window_ standardWindowButton:NSWindowCloseButton].hidden; } void NativeWindowMac::SetWindowButtonPosition( absl::optional<gfx::Point> position) { traffic_light_position_ = std::move(position); if (buttons_proxy_) { [buttons_proxy_ setMargin:traffic_light_position_]; NotifyLayoutWindowControlsOverlay(); } } absl::optional<gfx::Point> NativeWindowMac::GetWindowButtonPosition() const { return traffic_light_position_; } void NativeWindowMac::RedrawTrafficLights() { if (buttons_proxy_ && !IsFullscreen()) [buttons_proxy_ redraw]; } // In simpleFullScreen mode, update the frame for new bounds. void NativeWindowMac::UpdateFrame() { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); NSRect fullscreenFrame = [window.screen frame]; [window setFrame:fullscreenFrame display:YES animate:YES]; } void NativeWindowMac::SetTouchBar( std::vector<gin_helper::PersistentDictionary> items) { touch_bar_ = [[ElectronTouchBar alloc] initWithDelegate:window_delegate_ window:this settings:std::move(items)]; [window_ setTouchBar:nil]; } void NativeWindowMac::RefreshTouchBarItem(const std::string& item_id) { if (touch_bar_ && [window_ touchBar]) [touch_bar_ refreshTouchBarItem:[window_ touchBar] id:item_id]; } void NativeWindowMac::SetEscapeTouchBarItem( gin_helper::PersistentDictionary item) { if (touch_bar_ && [window_ touchBar]) [touch_bar_ setEscapeTouchBarItem:std::move(item) forTouchBar:[window_ touchBar]]; } void NativeWindowMac::SelectPreviousTab() { [window_ selectPreviousTab:nil]; } void NativeWindowMac::SelectNextTab() { [window_ selectNextTab:nil]; } void NativeWindowMac::ShowAllTabs() { [window_ toggleTabOverview:nil]; } void NativeWindowMac::MergeAllWindows() { [window_ mergeAllWindows:nil]; } void NativeWindowMac::MoveTabToNewWindow() { [window_ moveTabToNewWindow:nil]; } void NativeWindowMac::ToggleTabBar() { [window_ toggleTabBar:nil]; } bool NativeWindowMac::AddTabbedWindow(NativeWindow* window) { if (window_ == window->GetNativeWindow().GetNativeNSWindow()) { return false; } else { [window_ addTabbedWindow:window->GetNativeWindow().GetNativeNSWindow() ordered:NSWindowAbove]; } return true; } void NativeWindowMac::SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) { NativeWindow::SetAspectRatio(aspect_ratio, extra_size); // Reset the behaviour to default if aspect_ratio is set to 0 or less. if (aspect_ratio > 0.0) { NSSize aspect_ratio_size = NSMakeSize(aspect_ratio, 1.0); if (has_frame()) [window_ setContentAspectRatio:aspect_ratio_size]; else [window_ setAspectRatio:aspect_ratio_size]; } else { [window_ setResizeIncrements:NSMakeSize(1.0, 1.0)]; } } void NativeWindowMac::PreviewFile(const std::string& path, const std::string& display_name) { preview_item_ = [[ElectronPreviewItem alloc] initWithURL:[NSURL fileURLWithPath:base::SysUTF8ToNSString(path)] title:base::SysUTF8ToNSString(display_name)]; [[QLPreviewPanel sharedPreviewPanel] makeKeyAndOrderFront:nil]; } void NativeWindowMac::CloseFilePreview() { if ([QLPreviewPanel sharedPreviewPanelExists]) { [[QLPreviewPanel sharedPreviewPanel] close]; } } gfx::Rect NativeWindowMac::ContentBoundsToWindowBounds( const gfx::Rect& bounds) const { if (has_frame()) { gfx::Rect window_bounds( [window_ frameRectForContentRect:bounds.ToCGRect()]); int frame_height = window_bounds.height() - bounds.height(); window_bounds.set_y(window_bounds.y() - frame_height); return window_bounds; } else { return bounds; } } gfx::Rect NativeWindowMac::WindowBoundsToContentBounds( const gfx::Rect& bounds) const { if (has_frame()) { gfx::Rect content_bounds( [window_ contentRectForFrameRect:bounds.ToCGRect()]); int frame_height = bounds.height() - content_bounds.height(); content_bounds.set_y(content_bounds.y() + frame_height); return content_bounds; } else { return bounds; } } void NativeWindowMac::NotifyWindowEnterFullScreen() { NativeWindow::NotifyWindowEnterFullScreen(); // Restore the window title under fullscreen mode. if (buttons_proxy_) [window_ setTitleVisibility:NSWindowTitleVisible]; } void NativeWindowMac::NotifyWindowLeaveFullScreen() { NativeWindow::NotifyWindowLeaveFullScreen(); // Restore window buttons. if (buttons_proxy_ && window_button_visibility_.value_or(true)) { [buttons_proxy_ redraw]; [buttons_proxy_ setVisible:YES]; } } void NativeWindowMac::NotifyWindowWillEnterFullScreen() { UpdateVibrancyRadii(true); } void NativeWindowMac::NotifyWindowWillLeaveFullScreen() { if (buttons_proxy_) { // Hide window title when leaving fullscreen. [window_ setTitleVisibility:NSWindowTitleHidden]; // Hide the container otherwise traffic light buttons jump. [buttons_proxy_ setVisible:NO]; } UpdateVibrancyRadii(false); } void NativeWindowMac::SetActive(bool is_key) { is_active_ = is_key; } bool NativeWindowMac::IsActive() const { return is_active_; } void NativeWindowMac::Cleanup() { DCHECK(!IsClosed()); ui::NativeTheme::GetInstanceForNativeUi()->RemoveObserver(this); display::Screen::GetScreen()->RemoveObserver(this); } class NativeAppWindowFrameViewMac : public views::NativeFrameViewMac { public: NativeAppWindowFrameViewMac(views::Widget* frame, NativeWindowMac* window) : views::NativeFrameViewMac(frame), native_window_(window) {} NativeAppWindowFrameViewMac(const NativeAppWindowFrameViewMac&) = delete; NativeAppWindowFrameViewMac& operator=(const NativeAppWindowFrameViewMac&) = delete; ~NativeAppWindowFrameViewMac() override = default; // NonClientFrameView: int NonClientHitTest(const gfx::Point& point) override { if (!bounds().Contains(point)) return HTNOWHERE; if (GetWidget()->IsFullscreen()) return HTCLIENT; // Check for possible draggable region in the client area for the frameless // window. int contents_hit_test = native_window_->NonClientHitTest(point); if (contents_hit_test != HTNOWHERE) return contents_hit_test; return HTCLIENT; } private: // Weak. raw_ptr<NativeWindowMac> const native_window_; }; std::unique_ptr<views::NonClientFrameView> NativeWindowMac::CreateNonClientFrameView(views::Widget* widget) { return std::make_unique<NativeAppWindowFrameViewMac>(widget, this); } bool NativeWindowMac::HasStyleMask(NSUInteger flag) const { return [window_ styleMask] & flag; } void NativeWindowMac::SetStyleMask(bool on, NSUInteger flag) { // Changing the styleMask of a frameless windows causes it to change size so // we explicitly disable resizing while setting it. ScopedDisableResize disable_resize; if (on) [window_ setStyleMask:[window_ styleMask] | flag]; else [window_ setStyleMask:[window_ styleMask] & (~flag)]; // Change style mask will make the zoom button revert to default, probably // a bug of Cocoa or macOS. SetMaximizable(maximizable_); } void NativeWindowMac::SetCollectionBehavior(bool on, NSUInteger flag) { if (on) [window_ setCollectionBehavior:[window_ collectionBehavior] | flag]; else [window_ setCollectionBehavior:[window_ collectionBehavior] & (~flag)]; // Change collectionBehavior will make the zoom button revert to default, // probably a bug of Cocoa or macOS. SetMaximizable(maximizable_); } views::View* NativeWindowMac::GetContentsView() { return root_view_.get(); } bool NativeWindowMac::CanMaximize() const { return maximizable_; } void NativeWindowMac::OnNativeThemeUpdated(ui::NativeTheme* observed_theme) { content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&NativeWindow::RedrawTrafficLights, GetWeakPtr())); } void NativeWindowMac::AddContentViewLayers() { // Make sure the bottom corner is rounded for non-modal windows: // http://crbug.com/396264. if (!is_modal()) { // For normal window, we need to explicitly set layer for contentView to // make setBackgroundColor work correctly. // There is no need to do so for frameless window, and doing so would make // titleBarStyle stop working. if (has_frame()) { CALayer* background_layer = [[CALayer alloc] init]; [background_layer setAutoresizingMask:kCALayerWidthSizable | kCALayerHeightSizable]; [[window_ contentView] setLayer:background_layer]; } [[window_ contentView] setWantsLayer:YES]; } } void NativeWindowMac::InternalSetWindowButtonVisibility(bool visible) { [[window_ standardWindowButton:NSWindowCloseButton] setHidden:!visible]; [[window_ standardWindowButton:NSWindowMiniaturizeButton] setHidden:!visible]; [[window_ standardWindowButton:NSWindowZoomButton] setHidden:!visible]; } void NativeWindowMac::InternalSetParentWindow(NativeWindow* new_parent, bool attach) { if (is_modal()) return; // Do not remove/add if we are already properly attached. if (attach && new_parent && [window_ parentWindow] == new_parent->GetNativeWindow().GetNativeNSWindow()) return; // Remove current parent window. RemoveChildFromParentWindow(); // Set new parent window. if (new_parent) { new_parent->add_child_window(this); if (attach) new_parent->AttachChildren(); } NativeWindow::SetParentWindow(new_parent); } void NativeWindowMac::SetForwardMouseMessages(bool forward) { [window_ setAcceptsMouseMovedEvents:forward]; } gfx::Rect NativeWindowMac::GetWindowControlsOverlayRect() { if (titlebar_overlay_ && buttons_proxy_ && window_button_visibility_.value_or(true)) { NSRect buttons = [buttons_proxy_ getButtonsContainerBounds]; gfx::Rect overlay; overlay.set_width(GetContentSize().width() - NSWidth(buttons)); if ([buttons_proxy_ useCustomHeight]) { overlay.set_height(titlebar_overlay_height()); } else { overlay.set_height(NSHeight(buttons)); } if (!base::i18n::IsRTL()) overlay.set_x(NSMaxX(buttons)); return overlay; } return gfx::Rect(); } // static NativeWindow* NativeWindow::Create(const gin_helper::Dictionary& options, NativeWindow* parent) { return new NativeWindowMac(options, parent); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
39,614
[Bug]: non-fullscreenable, non-resizable child windows get fullscreened when being shown if the parent window is fullscreened
### 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 26.0.0 ### What operating system are you using? macOS ### Operating System Version macOS Ventura 13.2.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior I expect that if a child window that's configured to be non-fullscreenable is shown while the parent window is fullscreened, the child window won't get fullscreened. ### Actual Behavior Child window opens fullscreened for some reason and the main window crashes when the child is closed. ### Testcase Gist URL https://gist.github.com/pushkin-/3b4bcdb219eee85789e95f6d94ec8a92 ### Additional Information 1. full screen main window 2. click open window 3. notice that child window is fullscreened even though it shouldn't be able to get fullscreen 4. closing the window makes the parent window go black seems like the invocation of `BrowserWindow::show()` causes the `enter-full-screen` event to get emitted for some reason. https://github.com/electron/electron/assets/6374473/f96e2680-4938-4de6-b562-94f80c46ecfb
https://github.com/electron/electron/issues/39614
https://github.com/electron/electron/pull/39620
2affecd4dd26b9f0cf2644ec115635559f920480
33e66b5cd02d2b258b956022c482024c74c13b4b
2023-08-22T22:41:12Z
c++
2023-08-24T20:54:08Z
spec/api-browser-window-spec.ts
import { expect } from 'chai'; import * as childProcess from 'node:child_process'; import * as path from 'node:path'; import * as fs from 'node:fs'; import * as qs from 'node:querystring'; import * as http from 'node:http'; import * as os from 'node:os'; import { AddressInfo } from 'node:net'; import { app, BrowserWindow, BrowserView, dialog, ipcMain, OnBeforeSendHeadersListenerDetails, protocol, screen, webContents, webFrameMain, session, WebContents, WebFrameMain } from 'electron/main'; import { emittedUntil, emittedNTimes } from './lib/events-helpers'; import { ifit, ifdescribe, defer, listen } from './lib/spec-helpers'; import { closeWindow, closeAllWindows } from './lib/window-helpers'; import { areColorsSimilar, captureScreen, HexColors, getPixelColor } from './lib/screen-helpers'; import { once } from 'node:events'; import { setTimeout } from 'node:timers/promises'; const fixtures = path.resolve(__dirname, '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', () => { it('sets the correct class name on the prototype', () => { expect(BrowserWindow.prototype.constructor.name).to.equal('BrowserWindow'); }); 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(fixtures, 'apps', 'xwindow-icon'); const appProcess = childProcess.spawn(process.execPath, [appPath]); await once(appProcess, 'exit'); }); 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. const wr = new WeakRef(w); await setTimeout(); // 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 setTimeout(); expect(wr.deref()).to.not.be.undefined(); }); }); describe('BrowserWindow.close()', () => { let w: 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 = once(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 = once(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 allow access to id after destruction', async () => { const closed = once(w, 'closed'); w.destroy(); await closed; expect(w.id).to.be.a('number'); }); it('should emit unload handler', async () => { await w.loadFile(path.join(fixtures, 'api', 'unload.html')); const closed = once(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 once(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 = once(w, 'closed'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' }); w.close(); await closed; }); describe('when invoked synchronously inside navigation observer', () => { let server: http.Server; let url: string; before(async () => { 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}`); } }); url = (await listen(server)).url; }); 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 = once(w.webContents, 'destroyed'); w.webContents.loadURL(url + path); await destroyed; }); } }); }); describe('window.close()', () => { let w: 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 once(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 once(w.webContents, 'before-unload-fired'); }); }); describe('BrowserWindow.destroy()', () => { let w: 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: 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: http.Server; let url: string; let postData = null as any; before(async () => { 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(req.url && req.url.includes('slow') ? 200 : 0).then(respond); }); url = (await listen(server)).url; }); after(() => { server.close(); }); it('should emit did-start-loading event', async () => { const didStartLoading = once(w.webContents, 'did-start-loading'); w.loadURL('about:blank'); await didStartLoading; }); it('should emit ready-to-show event', async () => { const readyToShow = once(w, 'ready-to-show'); w.loadURL('about:blank'); await readyToShow; }); // DISABLED-FIXME(deepak1556): The error code now seems to be `ERR_FAILED`, verify what // changed and adjust the test. it('should emit did-fail-load event for files that do not exist', async () => { const didFailLoad = once(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 = once(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 not emit did-fail-load for a successfully loaded media file', async () => { w.webContents.on('did-fail-load', () => { expect.fail('did-fail-load should not emit on media file loads'); }); const mediaStarted = once(w.webContents, 'media-started-playing'); w.loadFile(path.join(fixtures, 'cat-spin.mp4')); await mediaStarted; }); it('should set `mainFrame = false` on did-fail-load events in iframes', async () => { const didFailLoad = once(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 = once(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: 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: http.Server; let url: string; before(async () => { server = http.createServer((req, res) => { if (req.url === '/navigate-top') { res.end('<a target=_top href="/">navigate _top</a>'); } else { res.end(''); } }); url = (await listen(server)).url; }); after(() => { server.close(); }); it('allows the window to be closed from the event listener', async () => { const event = once(w.webContents, 'will-navigate'); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); await event; w.close(); }); 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 () => { w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-top"></iframe>`); await emittedUntil(w.webContents, 'did-frame-finish-load', (e: any, isMainFrame: boolean) => !isMainFrame); let initiator: WebFrameMain | undefined; w.webContents.on('will-navigate', (e) => { initiator = e.initiator; }); const subframe = w.webContents.mainFrame.frames[0]; subframe.executeJavaScript('document.getElementsByTagName("a")[0].click()', true); await once(w.webContents, 'did-navigate'); expect(initiator).not.to.be.undefined(); expect(initiator).to.equal(subframe); }); }); describe('will-frame-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 if (req.url === '/navigate-iframe') { res.end('<a href="/test">navigate iframe</a>'); } else if (req.url === '/navigate-iframe?navigated') { res.end('Successfully navigated'); } else if (req.url === '/navigate-iframe-immediately') { res.end(` <script type="text/javascript" charset="utf-8"> location.href += '?navigated' </script> `); } else if (req.url === '/navigate-iframe-immediately?navigated') { res.end('Successfully navigated'); } 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-frame-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-frame-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('can be prevented when navigating subframe', (done) => { let willNavigate = false; w.webContents.on('did-frame-navigate', (_event, _url, _httpResponseCode, _httpStatusText, isMainFrame, frameProcessId, frameRoutingId) => { if (isMainFrame) return; w.webContents.once('will-frame-navigate', (e) => { willNavigate = true; e.preventDefault(); }); w.webContents.on('did-stop-loading', () => { const frame = webFrameMain.fromId(frameProcessId, frameRoutingId); expect(frame).to.not.be.undefined(); if (willNavigate) { // i.e. it shouldn't have had '?navigated' appended to it. try { expect(frame!.url.endsWith('/navigate-iframe-immediately')).to.be.true(); done(); } catch (e) { done(e); } } }); }); w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-iframe-immediately"></iframe>`); }); 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-frame-navigate', (e) => { e.preventDefault(); resolve(e.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-frame-navigate', (e) => { e.preventDefault(); resolve(e.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 setTimeout(1000); let willFrameNavigateEmitted = false; let isMainFrameValue; w.webContents.on('will-frame-navigate', (event) => { willFrameNavigateEmitted = true; isMainFrameValue = event.isMainFrame; }); const didNavigatePromise = once(w.webContents, 'did-navigate'); 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); await didNavigatePromise; expect(willFrameNavigateEmitted).to.be.true(); expect(isMainFrameValue).to.be.true(); }); it('is triggered when a cross-origin iframe navigates itself', async () => { await w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-iframe"></iframe>`); await setTimeout(1000); let willNavigateEmitted = false; let isMainFrameValue; w.webContents.on('will-frame-navigate', (event) => { willNavigateEmitted = true; isMainFrameValue = event.isMainFrame; }); const didNavigatePromise = once(w.webContents, 'did-frame-navigate'); 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); await didNavigatePromise; expect(willNavigateEmitted).to.be.true(); expect(isMainFrameValue).to.be.false(); }); it('can cancel when a cross-origin iframe navigates itself', async () => { }); }); describe('will-redirect event', () => { let server: http.Server; let url: string; before(async () => { 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(); } }); url = (await listen(server)).url; }); after(() => { server.close(); }); it('is emitted on redirects', async () => { const willRedirect = once(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 = once(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 = once(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', async () => { const event = once(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await event; w.close(); }); 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('ordering', () => { let server = null as unknown as http.Server; let url = null as unknown as string; const navigationEvents = [ 'did-start-navigation', 'did-navigate-in-page', 'will-frame-navigate', 'will-navigate', 'will-redirect', 'did-redirect-navigation', 'did-frame-navigate', 'did-navigate' ]; before((done) => { server = http.createServer((req, res) => { if (req.url === '/navigate') { res.end('<a href="/">navigate</a>'); } else if (req.url === '/redirect') { res.end('<a href="/redirect2">redirect</a>'); } else if (req.url === '/redirect2') { res.statusCode = 302; res.setHeader('location', url); res.end(); } else if (req.url === '/in-page') { res.end('<a href="#in-page">redirect</a><div id="in-page"></div>'); } else { res.end(''); } }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/`; done(); }); }); it('for initial navigation, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'did-frame-navigate', 'did-navigate' ]; const allEvents = Promise.all(navigationEvents.map(event => once(w.webContents, event).then(() => firedEvents.push(event)) )); const timeout = setTimeout(1000); w.loadURL(url); await Promise.race([allEvents, timeout]); expect(firedEvents).to.deep.equal(expectedEventOrder); }); it('for second navigation, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'will-frame-navigate', 'will-navigate', 'did-frame-navigate', 'did-navigate' ]; w.loadURL(`${url}navigate`); await once(w.webContents, 'did-navigate'); await setTimeout(2000); Promise.all(navigationEvents.map(event => once(w.webContents, event).then(() => firedEvents.push(event)) )); const navigationFinished = once(w.webContents, 'did-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: pageTarget.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); await navigationFinished; expect(firedEvents).to.deep.equal(expectedEventOrder); }); it('when navigating with redirection, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'will-frame-navigate', 'will-navigate', 'will-redirect', 'did-redirect-navigation', 'did-frame-navigate', 'did-navigate' ]; w.loadURL(`${url}redirect`); await once(w.webContents, 'did-navigate'); await setTimeout(2000); Promise.all(navigationEvents.map(event => once(w.webContents, event).then(() => firedEvents.push(event)) )); const navigationFinished = once(w.webContents, 'did-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: pageTarget.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); await navigationFinished; expect(firedEvents).to.deep.equal(expectedEventOrder); }); it('when navigating in-page, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'did-navigate-in-page' ]; w.loadURL(`${url}in-page`); await once(w.webContents, 'did-navigate'); await setTimeout(2000); Promise.all(navigationEvents.map(event => once(w.webContents, event).then(() => firedEvents.push(event)) )); const navigationFinished = once(w.webContents, 'did-navigate-in-page'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: pageTarget.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); await navigationFinished; expect(firedEvents).to.deep.equal(expectedEventOrder); }); }); }); } describe('focus and visibility', () => { let w: 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', async () => { const p = once(w, 'focus'); w.show(); await p; expect(w.isFocused()).to.equal(true); }); it('should make the window visible', async () => { const p = once(w, 'focus'); w.show(); await p; expect(w.isVisible()).to.equal(true); }); it('emits when window is shown', async () => { const show = once(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 = once(w, 'show'); w.show(); await shown; const hidden = once(w, 'hide'); w.hide(); await hidden; expect(w.isVisible()).to.equal(false); }); }); describe('BrowserWindow.minimize()', () => { // TODO(codebytere): Enable for Linux once maximize/minimize events work in CI. ifit(process.platform !== 'linux')('should not be visible when the window is minimized', async () => { const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMinimized()).to.equal(true); 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 = once(w, 'maximize'); const shown = once(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 setTimeout(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); }); ifit(process.platform !== 'win32')('focuses a blurred window', async () => { { const isBlurred = once(w, 'blur'); const isShown = once(w, 'show'); w.show(); w.blur(); await isShown; await isBlurred; } expect(w.isFocused()).to.equal(false); w.focus(); expect(w.isFocused()).to.equal(true); }); ifit(process.platform !== 'linux')('acquires focus status from the other windows', async () => { const w1 = new BrowserWindow({ show: false }); const w2 = new BrowserWindow({ show: false }); const w3 = new BrowserWindow({ show: false }); { const isFocused3 = once(w3, 'focus'); const isShown1 = once(w1, 'show'); const isShown2 = once(w2, 'show'); const isShown3 = once(w3, 'show'); w1.show(); w2.show(); w3.show(); await isShown1; await isShown2; await isShown3; await isFocused3; } // TODO(RaisinTen): Investigate why this assertion fails only on Linux. expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); w1.focus(); expect(w1.isFocused()).to.equal(true); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(false); w2.focus(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(true); expect(w3.isFocused()).to.equal(false); w3.focus(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); { const isClosed1 = once(w1, 'closed'); const isClosed2 = once(w2, 'closed'); const isClosed3 = once(w3, 'closed'); w1.destroy(); w2.destroy(); w3.destroy(); await isClosed1; await isClosed2; await isClosed3; } }); }); // TODO(RaisinTen): Make this work on Windows too. // Refs: https://github.com/electron/electron/issues/20464. ifdescribe(process.platform !== 'win32')('BrowserWindow.blur()', () => { it('removes focus from window', async () => { { const isFocused = once(w, 'focus'); const isShown = once(w, 'show'); w.show(); await isShown; await isFocused; } expect(w.isFocused()).to.equal(true); w.blur(); expect(w.isFocused()).to.equal(false); }); ifit(process.platform !== 'linux')('transfers focus status to the next window', async () => { const w1 = new BrowserWindow({ show: false }); const w2 = new BrowserWindow({ show: false }); const w3 = new BrowserWindow({ show: false }); { const isFocused3 = once(w3, 'focus'); const isShown1 = once(w1, 'show'); const isShown2 = once(w2, 'show'); const isShown3 = once(w3, 'show'); w1.show(); w2.show(); w3.show(); await isShown1; await isShown2; await isShown3; await isFocused3; } // TODO(RaisinTen): Investigate why this assertion fails only on Linux. expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); w3.blur(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(true); expect(w3.isFocused()).to.equal(false); w2.blur(); expect(w1.isFocused()).to.equal(true); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(false); w1.blur(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); { const isClosed1 = once(w1, 'closed'); const isClosed2 = once(w2, 'closed'); const isClosed3 = once(w3, 'closed'); w1.destroy(); w2.destroy(); w3.destroy(); await isClosed1; await isClosed2; await isClosed3; } }); }); describe('BrowserWindow.getFocusedWindow()', () => { it('returns the opener window when dev tools window is focused', async () => { const p = once(w, 'focus'); w.show(); await p; w.webContents.openDevTools({ mode: 'undocked' }); await once(w.webContents, 'devtools-focused'); expect(BrowserWindow.getFocusedWindow()).to.equal(w); }); }); describe('BrowserWindow.moveTop()', () => { afterEach(closeAllWindows); it('should not steal focus', async () => { const posDelta = 50; const wShownInactive = once(w, 'show'); w.showInactive(); await wShownInactive; expect(w.isFocused()).to.equal(false); const otherWindow = new BrowserWindow({ show: false, title: 'otherWindow' }); const otherWindowShown = once(otherWindow, 'show'); const otherWindowFocused = once(otherWindow, 'focus'); otherWindow.show(); await otherWindowShown; await otherWindowFocused; expect(otherWindow.isFocused()).to.equal(true); w.moveTop(); const wPos = w.getPosition(); const wMoving = once(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 = once(w, 'focus'); const otherWindowBlurred = once(otherWindow, 'blur'); w.focus(); await wFocused; await otherWindowBlurred; expect(w.isFocused()).to.equal(true); otherWindow.moveTop(); const otherWindowPos = otherWindow.getPosition(); const otherWindowMoving = once(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); }); it('should not crash when called on a modal child window', async () => { const shown = once(w, 'show'); w.show(); await shown; const child = new BrowserWindow({ modal: true, parent: w }); expect(() => { child.moveTop(); }).to.not.throw(); }); }); describe('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 = once(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 = once(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: 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 = { ...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(once(w, 'resized')).to.eventually.be.fulfilled(); }); }); }); describe('BrowserWindow.setSize(width, height)', () => { it('sets the window size', async () => { const size = [300, 400]; const resized = once(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(once(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 = once(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 = once(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 = once(w, 'resize'); w.setContentBounds(bounds); await resize; await setTimeout(); 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 = once(w, 'resize'); w.setContentBounds(bounds); await resize; await setTimeout(); 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); }); it('returns correct color with multiple passed formats', () => { w.destroy(); w = new BrowserWindow({}); w.setBackgroundColor('#AABBFF'); expect(w.getBackgroundColor()).to.equal('#AABBFF'); w.setBackgroundColor('blueviolet'); expect(w.getBackgroundColor()).to.equal('#8A2BE2'); w.setBackgroundColor('rgb(255, 0, 185)'); expect(w.getBackgroundColor()).to.equal('#FF00B9'); w.setBackgroundColor('rgba(245, 40, 145, 0.8)'); expect(w.getBackgroundColor()).to.equal('#F52891'); w.setBackgroundColor('hsl(155, 100%, 50%)'); expect(w.getBackgroundColor()).to.equal('#00FF95'); }); }); describe('BrowserWindow.getNormalBounds()', () => { describe('Normal state', () => { it('checks normal bounds after resize', async () => { const size = [300, 400]; const resize = once(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 = once(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 = once(w, 'maximize'); w.show(); w.maximize(); await maximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after resize and maximize', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('updates normal bounds after move and maximize', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('checks normal bounds when unmaximized', async () => { const bounds = w.getBounds(); w.once('maximize', () => { w.unmaximize(); }); const unmaximize = once(w, 'unmaximize'); w.show(); w.maximize(); await unmaximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('correctly reports maximized state after maximizing then minimizing', async () => { w.destroy(); w = new BrowserWindow({ show: false }); w.show(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMaximized()).to.equal(false); expect(w.isMinimized()).to.equal(true); }); it('correctly reports maximized state after maximizing then fullscreening', async () => { w.destroy(); w = new BrowserWindow({ show: false }); w.show(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; expect(w.isMaximized()).to.equal(false); expect(w.isFullScreen()).to.equal(true); }); it('checks normal bounds for maximized transparent window', async () => { w.destroy(); w = new BrowserWindow({ transparent: true, show: false }); w.show(); const bounds = w.getNormalBounds(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; 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 = once(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 = once(w, 'maximize'); w.show(); w.maximize(); await maximize; expect(w.isMaximized()).to.equal(true); const unmaximize = once(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 = once(w, 'maximize'); 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 = once(w, 'minimize'); w.show(); w.minimize(); await minimize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after move and minimize', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const minimize = once(w, 'minimize'); w.minimize(); await minimize; const normal = w.getNormalBounds(); expect(original).to.deep.equal(normal); expectBoundsEqual(normal, w.getBounds()); }); it('updates normal bounds after resize and minimize', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const minimize = once(w, 'minimize'); w.minimize(); await minimize; const normal = w.getNormalBounds(); expect(original).to.deep.equal(normal); expectBoundsEqual(normal, w.getBounds()); }); it('checks normal bounds when restored', async () => { const bounds = w.getBounds(); w.once('minimize', () => { w.restore(); }); const restore = once(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 = once(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('does not go fullscreen if roundedCorners are enabled', async () => { w = new BrowserWindow({ frame: false, roundedCorners: false, fullscreen: true }); expect(w.fullScreen).to.be.false(); }); 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 = once(w, 'enter-full-screen'); w.show(); w.fullScreen = true; await enterFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after resize and fullscreen', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.fullScreen = true; await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('updates normal bounds after move and fullscreen', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.fullScreen = true; await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('checks normal bounds when unfullscreen\'ed', async () => { const bounds = w.getBounds(); w.once('enter-full-screen', () => { w.fullScreen = false; }); const leaveFullScreen = once(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 = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after resize and fullscreen', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.setFullScreen(true); await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('updates normal bounds after move and fullscreen', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.setFullScreen(true); await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('checks normal bounds when unfullscreen\'ed', async () => { const bounds = w.getBounds(); w.show(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); }); }); }); ifdescribe(process.platform === 'darwin')('tabbed windows', () => { let w: 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.showAllTabs()', () => { it('does not throw', () => { expect(() => { w.showAllTabs(); }).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); }); ifit(process.platform === 'darwin')('honors the stayHidden argument', async () => { const w = new BrowserWindow({ webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.hide(); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } await w.capturePage({ x: 0, y: 0, width: 0, height: 0 }, { stayHidden: true }); const visible = await w.webContents.executeJavaScript('document.visibilityState'); expect(visible).to.equal('hidden'); }); it('resolves after the window is hidden', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixtures, 'pages', 'a.html')); await once(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('resolves after the window is hidden and capturer count is non-zero', async () => { const w = new BrowserWindow({ show: false }); w.webContents.setBackgroundThrottling(false); w.loadFile(path.join(fixtures, 'pages', 'a.html')); await once(w, 'ready-to-show'); const image = await w.capturePage(); expect(image.isEmpty()).to.equal(false); }); it('preserves transparency', async () => { const w = new BrowserWindow({ show: false, transparent: true }); w.loadFile(path.join(fixtures, 'pages', 'theme-color.html')); await once(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: 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: 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', async () => { expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); const minimized = once(w, 'minimize'); w.minimize(); await minimized; expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); const restored = once(w, 'restore'); w.restore(); await restored; 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 = once(w, 'always-on-top-changed') as Promise<[any, boolean]>; 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: BrowserWindow; let server: http.Server; let url: 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++; }); url = (await listen(server)).url; }); 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 = once(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: 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); }); it('correctly updates when entering/exiting fullscreen for hidden style', async () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hidden' }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; const leaveFS = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFS; w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); it('correctly updates when entering/exiting fullscreen for hiddenInset style', async () => { 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); const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; const leaveFS = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFS; w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setVibrancy(type)', () => { afterEach(closeAllWindows); it('allows setting, changing, and removing the vibrancy', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setVibrancy('titlebar'); w.setVibrancy('selection'); w.setVibrancy(null); w.setVibrancy('menu'); 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(); }); }); ifdescribe(process.platform === 'darwin')('trafficLightPosition', () => { const pos = { x: 10, y: 10 }; afterEach(closeAllWindows); describe('BrowserWindow.getWindowButtonPosition(pos)', () => { it('returns null when there is no custom position', () => { const w = new BrowserWindow({ show: false }); expect(w.getWindowButtonPosition()).to.be.null('getWindowButtonPosition'); }); it('gets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); expect(w.getWindowButtonPosition()).to.deep.equal(pos); }); it('gets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); expect(w.getWindowButtonPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setWindowButtonPosition(pos)', () => { it('resets the position when null is passed', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); w.setWindowButtonPosition(null); expect(w.getWindowButtonPosition()).to.be.null('setWindowButtonPosition'); }); it('sets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setWindowButtonPosition(newPos); expect(w.getWindowButtonPosition()).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.setWindowButtonPosition(newPos); expect(w.getWindowButtonPosition()).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('Opening a BrowserWindow from a link', () => { let appProcess: childProcess.ChildProcessWithoutNullStreams | undefined; afterEach(() => { if (appProcess && !appProcess.killed) { appProcess.kill(); appProcess = undefined; } }); it('can properly open and load a new window from a link', async () => { const appPath = path.join(__dirname, 'fixtures', 'apps', 'open-new-window-from-link'); appProcess = childProcess.spawn(process.execPath, [appPath]); const [code] = await once(appProcess, 'exit'); expect(code).to.equal(0); }); }); 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 typeof ElectronInternal.WebContents).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.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 = once(w.webContents, 'did-attach-webview'); const [, webviewContents] = await once(app, 'web-contents-created') as [any, WebContents]; expect(BrowserWindow.fromWebContents(webviewContents)!.id).to.equal(w.id); await p; }); it('is usable immediately on browser-window-created', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.executeJavaScript('window.open(""); null'); const [win, winFromWebContents] = await new Promise<any>((resolve) => { app.once('browser-window-created', (e, win) => { resolve([win, BrowserWindow.fromWebContents(win.webContents)]); }); }); expect(winFromWebContents).to.equal(win); }); }); 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.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.destroy(); bv2.webContents.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.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(['win32', 'darwin'].includes(process.platform))('"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 = once(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 = once(ipcMain, 'geometrychange'); w.setBounds({ width: 800 }); const [, newOverlayRect] = await geometryChange; expect(newOverlayRect.width).to.equal(overlayRect.width + 400); }; afterEach(async () => { await closeAllWindows(); 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')('when an invalid titleBarStyle is initially set', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { color: '#0000f0', symbolColor: '#ffffff' }, titleBarStyle: 'hiddenInset' }); }); afterEach(async () => { await closeAllWindows(); }); it('does not crash changing minimizability ', () => { expect(() => { w.setMinimizable(false); }).to.not.throw(); }); it('does not crash changing maximizability', () => { expect(() => { w.setMaximizable(false); }).to.not.throw(); }); }); }); ifdescribe(['win32', 'darwin'].includes(process.platform))('"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 = once(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()'); if (!w.isMaximized()) { const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; } expect(w.isMaximized()).to.be.true('not maximized'); 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(async () => { await closeAllWindows(); ipcMain.removeAllListeners('geometrychange'); }); it('sets Window Control Overlay with title bar height of 40', async () => { await testWindowsOverlayHeight(40); }); }); ifdescribe(process.platform === 'win32')('BrowserWindow.setTitlebarOverlay', () => { afterEach(async () => { await closeAllWindows(); ipcMain.removeAllListeners('geometrychange'); }); it('does not crash when an invalid titleBarStyle was initially set', () => { const win = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { color: '#0000f0', symbolColor: '#ffffff' }, titleBarStyle: 'hiddenInset' }); expect(() => { win.setTitleBarOverlay({ color: '#000000' }); }).to.not.throw(); }); it('correctly updates the height of the overlay', async () => { const testOverlay = async (w: BrowserWindow, size: Number, firstRun: boolean) => { const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); const overlayReady = once(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); if (firstRun) { await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const { height: preMaxHeight } = await w.webContents.executeJavaScript('getJSOverlayProperties()'); if (!w.isMaximized()) { const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; } expect(w.isMaximized()).to.be.true('not maximized'); const { x, y, width, height } = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(x).to.equal(0); expect(y).to.equal(0); expect(width).to.be.greaterThan(0); expect(height).to.equal(size); expect(preMaxHeight).to.equal(size); }; const INITIAL_SIZE = 40; const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden', webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { height: INITIAL_SIZE } }); await testOverlay(w, INITIAL_SIZE, true); w.setTitleBarOverlay({ height: INITIAL_SIZE + 10 }); await testOverlay(w, INITIAL_SIZE + 10, false); }); }); 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-next-line no-new */ new BrowserWindow({ tabbingIdentifier: 'group1' }); /* eslint-disable-next-line no-new */ new BrowserWindow({ tabbingIdentifier: 'group2', frame: false }); }).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 once(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 once(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 once(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-isolated 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 once(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 once(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 once(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 once(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 once(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 once(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; let serverUrl: string; before(async () => { 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}`); } }); serverUrl = (await listen(server)).url; }); 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 once(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 once(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 once(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 once(ipcMain, 'answer'); const expectedUrl = process.platform === 'win32' ? 'file:///' + htmlPath.replace(/\\/g, '/') : pageUrl; expect(url).to.equal(expectedUrl); }); it('exposes full EventEmitter object to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload: path.join(fixtures, 'module', 'preload-eventemitter.js') } }); w.loadURL('about:blank'); const [, rendererEventEmitterProperties] = await once(ipcMain, 'answer'); const { EventEmitter } = require('node:events'); const emitter = new EventEmitter(); const browserEventEmitterProperties = []; let currentObj = emitter; do { browserEventEmitterProperties.push(...Object.getOwnPropertyNames(currentObj)); } while ((currentObj = Object.getPrototypeOf(currentObj))); expect(rendererEventEmitterProperties).to.deep.equal(browserEventEmitterProperties); }); 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 = once(ipcMain, 'answer'); w.loadURL(pageUrl); const [, { url, frameName, options }] = await once(w.webContents, 'did-create-window') as [BrowserWindow, Electron.DidCreateWindowDetails]; 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 once(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 once(app, 'browser-window-created') as [any, BrowserWindow]; // Ask the popup window for details. const detailsAnswer = once(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 = once(ipcMain, 'answer'); w.webContents.send('touch-the-popup'); const [, popupAccessMessage] = await touchPopupResult; // Ask the popup to access the opener. const touchOpenerResult = once(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 once(ipcMain, 'answer'); expect(argv).to.include('--enable-sandbox'); }); it('should open windows with the options configured via setWindowOpenHandler handlers', 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([ once(app, 'web-contents-created') as Promise<[any, WebContents]>, once(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 => once(ipcMain, name))); w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'verify-ipc-sender' }); await done; }); describe('event handling', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); }); it('works for window events', async () => { const pageTitleUpdated = once(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 => once(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 => once(w.webContents, name))); w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'webcontents-events' }); await done; }); }); 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 once(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'); expect(test.nodeEvents).to.equal(true); expect(test.nodeTimers).to.equal(true); expect(test.nodeUrl).to.equal(true); 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 = once(w.webContents, 'did-attach-webview') as Promise<[any, WebContents]>; const webviewDomReady = once(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; 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 = once(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 = once(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 = once(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 = once(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 once(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 once(ipcMain, 'answer'); expect(content).to.equal('function'); } w.reload(); { const [, content] = await once(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, preload } } })); const webviewLoaded = once(ipcMain, 'webview-loaded'); w.loadFile(path.join(fixtures, 'api', 'new-window-webview.html')); await webviewLoaded; }); it('should open windows with the options configured via setWindowOpenHandler handlers', 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([ once(app, 'web-contents-created') as Promise<[any, WebContents]>, once(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 once(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 once(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 = once(w.webContents, 'enter-html-full-screen'); w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true); await enterHtmlFullScreen; expect(w.getSize()).to.deep.equal(size); }); }); describe('"defaultFontFamily" option', () => { it('can change the standard font family', async () => { const w = new BrowserWindow({ show: false, webPreferences: { defaultFontFamily: { standard: 'Impact' } } }); await w.loadFile(path.join(fixtures, 'pages', 'content.html')); const fontFamily = await w.webContents.executeJavaScript("window.getComputedStyle(document.getElementsByTagName('p')[0])['font-family']", true); expect(fontFamily).to.equal('Impact'); }); }); }); describe('beforeunload handler', function () { let w: 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 = once(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 once(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 once(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 once(w.webContents, 'console-message'); w.close(); await once(w.webContents, 'before-unload-fired'); w.close(); await once(w.webContents, 'before-unload-fired'); w.webContents.removeListener('destroyed', destroyListener); const wait = once(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 once(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 once(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 once(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'); }); }); // TODO(codebytere): figure out how to make these pass in CI on Windows. ifdescribe(process.platform !== 'win32')('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 once(ipcMain, 'pong'); expect(readyToShow).to.be.false('ready to show'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); }); it('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 once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.hide(); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } }); it('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 once(w, 'show'); } w.hide(); w.show(); const [, visibilityState] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); }); it('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 once(w, 'show'); } w.hide(); w.showInactive(); const [, visibilityState] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); }); 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 once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.minimize(); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } }); it('visibilityState remains visible if backgroundThrottling is disabled', async () => { const w = new BrowserWindow({ show: false, width: 100, height: 100, webPreferences: { backgroundThrottling: false, nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await once(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 = once(w, 'show'); w.show(); await shown1; const hidden = once(w, 'hide'); w.hide(); await hidden; const shown2 = once(w, 'show'); w.show(); await shown2; } finally { ipcMain.removeAllListeners('pong'); } }); }); 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 = once(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 = once(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 = once(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 = once(w, 'maximize'); const unmaximize = once(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 = once(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 }); let called = false; w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); w.webContents.on('dom-ready', () => { w.webContents.beginFrameSubscription(function () { // This callback might be called twice. if (called) return; called = true; // Pending endFrameSubscription to next tick can reliably reproduce // a crash which happens when nothing is returned in the callback. setTimeout().then(() => { 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 () => { /* Use temp directory for saving MHTML file since the write handle * gets passed to untrusted process and chromium will deny exec access to * the path. To perform this task, chromium requires that the path is one * of the browser controlled paths, refs https://chromium-review.googlesource.com/c/chromium/src/+/3774416 */ const tmpDir = await fs.promises.mkdtemp(path.resolve(os.tmpdir(), 'electron-mhtml-save-')); const savePageMHTMLPath = path.join(tmpDir, 'save_page.html'); const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageMHTMLPath, 'MHTML'); expect(fs.existsSync(savePageMHTMLPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.false('js path'); expect(fs.existsSync(savePageCssPath)).to.be.false('css path'); try { await fs.promises.unlink(savePageMHTMLPath); await fs.promises.rmdir(tmpDir); } catch {} }); 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(); }); // TODO(zcbenz): // This test does not run on Linux CI. See: // https://github.com/electron/electron/issues/28699 ifit(process.platform === 'linux' && !process.env.CI)('should bring a minimized maximized window back to maximized state', async () => { const w = new BrowserWindow({}); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMaximized()).to.equal(false); const restore = once(w, 'restore'); w.restore(); await restore; expect(w.isMaximized()).to.equal(true); }); }); // TODO(dsanders11): Enable once maximize event works on Linux again on CI ifdescribe(process.platform !== 'linux')('BrowserWindow.maximize()', () => { afterEach(closeAllWindows); it('should show the window if it is not currently shown', async () => { const w = new BrowserWindow({ show: false }); const hidden = once(w, 'hide'); let shown = once(w, 'show'); const maximize = once(w, 'maximize'); expect(w.isVisible()).to.be.false('visible'); w.maximize(); await maximize; await shown; expect(w.isMaximized()).to.be.true('maximized'); expect(w.isVisible()).to.be.true('visible'); // Even if the window is already maximized w.hide(); await hidden; expect(w.isVisible()).to.be.false('visible'); shown = once(w, 'show'); w.maximize(); await shown; expect(w.isVisible()).to.be.true('visible'); }); }); 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 = once(w, 'minimize'); w.minimize(); await minimize; w.unmaximize(); await setTimeout(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 setTimeout(1000); expectBoundsEqual(w.getSize(), initialSize); expectBoundsEqual(w.getPosition(), initialPosition); }); ifit(process.platform === 'darwin')('should not change size or position of a window which is functionally maximized', async () => { const { workArea } = screen.getPrimaryDisplay(); const bounds = { x: workArea.x, y: workArea.y, width: workArea.width, height: workArea.height }; const w = new BrowserWindow(bounds); w.unmaximize(); await setTimeout(1000); expectBoundsEqual(w.getBounds(), bounds); }); }); 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 = once(w, 'show'); // start fullscreen and hidden w.setFullScreen(true); w.show(); await shown; const leftFullScreen = once(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 = once(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 once(w, 'enter-full-screen'); // Wait a tick for the full-screen state to 'stick' await setTimeout(); w.setFullScreen(false); await once(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 = once(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 = once(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 = once(c, 'closed'); c.close(); await closed; // The child window list is not immediately cleared, so wait a tick until it's ready. await setTimeout(); expect(w.getChildWindows().length).to.equal(0); }); it('can handle child window close and reparent multiple times', async () => { const w = new BrowserWindow({ show: false }); let c: BrowserWindow | null; for (let i = 0; i < 5; i++) { c = new BrowserWindow({ show: false, parent: w }); const closed = once(c, 'closed'); c.close(); await closed; } await setTimeout(); expect(w.getChildWindows().length).to.equal(0); }); ifit(process.platform === 'darwin')('child window matches visibility when visibility changes', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); const wShow = once(w, 'show'); const cShow = once(c, 'show'); w.show(); c.show(); await Promise.all([wShow, cShow]); const minimized = once(w, 'minimize'); w.minimize(); await minimized; expect(w.isVisible()).to.be.false('parent is visible'); expect(c.isVisible()).to.be.false('child is visible'); const restored = once(w, 'restore'); w.restore(); await restored; expect(w.isVisible()).to.be.true('parent is visible'); expect(c.isVisible()).to.be.true('child is visible'); }); ifit(process.platform === 'darwin')('matches child window visibility when visibility changes', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); const wShow = once(w, 'show'); const cShow = once(c, 'show'); w.show(); c.show(); await Promise.all([wShow, cShow]); const minimized = once(c, 'minimize'); c.minimize(); await minimized; expect(c.isVisible()).to.be.false('child is visible'); const restored = once(c, 'restore'); c.restore(); await restored; expect(w.isVisible()).to.be.true('parent is visible'); expect(c.isVisible()).to.be.true('child is visible'); }); it('closes a grandchild window when a middle child window is destroyed', (done) => { const w = new BrowserWindow(); w.loadFile(path.join(fixtures, 'pages', 'base-page.html')); w.webContents.executeJavaScript('window.open("")'); w.webContents.on('did-create-window', async (window) => { const childWindow = new BrowserWindow({ parent: window }); await setTimeout(); window.close(); childWindow.on('closed', () => { expect(() => { BrowserWindow.getFocusedWindow(); }).to.not.throw(); done(); }); }); }); 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 = once(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 setTimeout(); expect(w.getChildWindows().length).to.equal(0); }); ifit(process.platform === 'darwin')('can reparent when the first parent is destroyed', async () => { const w1 = new BrowserWindow({ show: false }); const w2 = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); c.setParentWindow(w1); expect(w1.getChildWindows().length).to.equal(1); const closed = once(w1, 'closed'); w1.destroy(); await closed; c.setParentWindow(w2); await setTimeout(); const children = w2.getChildWindows(); expect(children[0]).to.equal(c); }); }); 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 = once(two, 'show'); two.show(); await twoShown; setTimeout(500).then(() => two.close()); await once(two, 'closed'); }; const one = new BrowserWindow({ width: 600, height: 400, parent: parentWindow, modal: true, show: false }); const oneShown = once(one, 'show'); one.show(); await oneShown; setTimeout(500).then(() => one.destroy()); await once(one, 'closed'); await createTwo(); }); ifit(process.platform !== 'darwin')('can disable and enable a window', () => { const w = new BrowserWindow({ show: false }); w.setEnabled(false); expect(w.isEnabled()).to.be.false('w.isEnabled()'); w.setEnabled(true); expect(w.isEnabled()).to.be.true('!w.isEnabled()'); }); 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 = once(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 = once(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; let serverUrl: string; before(async () => { server = http.createServer((request, response) => { response.end(); }); serverUrl = (await listen(server)).url; }); after(() => { server.close(); }); it('is true when the main frame is loading', async () => { const w = new BrowserWindow({ show: false }); const didStartLoading = once(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 = once(w.webContents, 'did-stop-loading'); w.webContents.loadURL(serverUrl); await didStopLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); const didStartLoading = once(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 = once(w.webContents, 'did-stop-loading'); w.webContents.loadURL(serverUrl); await didStopLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); const didStartLoading = once(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')('when fullscreen state is changed', () => { it('correctly remembers state prior to fullscreen change', async () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); w.setMenuBarVisibility(false); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; expect(w.fullScreen).to.be.true('not fullscreen'); const exitFS = once(w, 'leave-full-screen'); w.setFullScreen(false); await exitFS; expect(w.fullScreen).to.be.false('not fullscreen'); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); }); it('correctly remembers state prior to fullscreen change with autoHide', async () => { const w = new BrowserWindow({ show: false }); expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); w.autoHideMenuBar = true; expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); w.setMenuBarVisibility(false); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; expect(w.fullScreen).to.be.true('not fullscreen'); const exitFS = once(w, 'leave-full-screen'); w.setFullScreen(false); await exitFS; expect(w.fullScreen).to.be.false('not fullscreen'); expect(w.isMenuBarVisible()).to.be.false('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'); }); }); }); ifdescribe(process.platform === 'darwin')('isHiddenInMissionControl state', () => { it('with functions', () => { it('can be set with ignoreMissionControl constructor option', () => { const w = new BrowserWindow({ show: false, hiddenInMissionControl: true }); expect(w.isHiddenInMissionControl()).to.be.true('isHiddenInMissionControl'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isHiddenInMissionControl()).to.be.false('isHiddenInMissionControl'); w.setHiddenInMissionControl(true); expect(w.isHiddenInMissionControl()).to.be.true('isHiddenInMissionControl'); w.setHiddenInMissionControl(false); expect(w.isHiddenInMissionControl()).to.be.false('isHiddenInMissionControl'); }); }); }); // 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 = once(w, 'enter-full-screen'); w.kiosk = true; expect(w.isKiosk()).to.be.true('isKiosk'); await enterFullScreen; await setTimeout(); const leaveFullScreen = once(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 = once(w, 'enter-full-screen'); w.setKiosk(true); expect(w.isKiosk()).to.be.true('isKiosk'); await enterFullScreen; await setTimeout(); const leaveFullScreen = once(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 false and restored', async () => { const w = new BrowserWindow({ resizable: false }); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.resizable).to.be.false('resizable'); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.resizable).to.be.false('resizable'); }); it('default resizable flag should be restored after entering/exiting fullscreen', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.resizable).to.be.false('resizable'); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.resizable).to.be.true('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 = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; }); it('should be able to load a URL while transitioning to fullscreen', async () => { const w = new BrowserWindow({ fullscreen: true }); w.loadFile(path.join(fixtures, 'pages', 'c.html')); const load = once(w.webContents, 'did-finish-load'); const enterFS = once(w, 'enter-full-screen'); await Promise.all([enterFS, load]); expect(w.fullScreen).to.be.true(); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; }); it('can be changed with setFullScreen method', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await setTimeout(); const leaveFullScreen = once(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 setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); }); it('handles several HTML fullscreen transitions', async () => { const w = new BrowserWindow(); await w.loadFile(path.join(fixtures, 'pages', 'a.html')); expect(w.isFullScreen()).to.be.false('is fullscreen'); const enterFullScreen = once(w, 'enter-full-screen'); const leaveFullScreen = once(w, 'leave-full-screen'); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await enterFullScreen; await w.webContents.executeJavaScript('document.exitFullscreen()', true); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); await setTimeout(); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await enterFullScreen; await w.webContents.executeJavaScript('document.exitFullscreen()', true); 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'); const enterFS = emittedNTimes(w, 'enter-full-screen', 2); const leaveFS = emittedNTimes(w, 'leave-full-screen', 2); w.setFullScreen(true); w.setFullScreen(false); w.setFullScreen(true); w.setFullScreen(false); await Promise.all([enterFS, leaveFS]); expect(w.isFullScreen()).to.be.false('not fullscreen'); }); it('handles several chromium-initiated transitions in close proximity', async () => { const w = new BrowserWindow(); await w.loadFile(path.join(fixtures, 'pages', 'a.html')); expect(w.isFullScreen()).to.be.false('is fullscreen'); let enterCount = 0; let exitCount = 0; const done = new Promise<void>(resolve => { const checkDone = () => { if (enterCount === 2 && exitCount === 2) resolve(); }; w.webContents.on('enter-html-full-screen', () => { enterCount++; checkDone(); }); w.webContents.on('leave-html-full-screen', () => { exitCount++; checkDone(); }); }); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await done; }); it('handles HTML fullscreen transitions when fullscreenable is false', async () => { const w = new BrowserWindow({ fullscreenable: false }); await w.loadFile(path.join(fixtures, 'pages', 'a.html')); expect(w.isFullScreen()).to.be.false('is fullscreen'); let enterCount = 0; let exitCount = 0; const done = new Promise<void>((resolve, reject) => { const checkDone = () => { if (enterCount === 2 && exitCount === 2) resolve(); }; w.webContents.on('enter-html-full-screen', async () => { enterCount++; if (w.isFullScreen()) reject(new Error('w.isFullScreen should be false')); const isFS = await w.webContents.executeJavaScript('!!document.fullscreenElement'); if (!isFS) reject(new Error('Document should have fullscreen element')); checkDone(); }); w.webContents.on('leave-html-full-screen', () => { exitCount++; if (w.isFullScreen()) reject(new Error('w.isFullScreen should be false')); checkDone(); }); }); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await expect(done).to.eventually.be.fulfilled(); }); it('does not crash when exiting simpleFullScreen (properties)', async () => { const w = new BrowserWindow(); w.setSimpleFullScreen(true); await setTimeout(1000); w.setFullScreen(!w.isFullScreen()); }); it('does not crash when exiting simpleFullScreen (functions)', async () => { const w = new BrowserWindow(); w.simpleFullScreen = true; await setTimeout(1000); w.setFullScreen(!w.isFullScreen()); }); it('should not be changed by setKiosk method', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setKiosk(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); const leaveFullScreen = once(w, 'leave-full-screen'); w.setKiosk(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('isFullScreen'); }); it('should stay fullscreen if fullscreen before kiosk', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); w.setKiosk(true); w.setKiosk(false); // Wait enough time for a fullscreen change to take effect. await setTimeout(2000); expect(w.isFullScreen()).to.be.true('isFullScreen'); }); it('multiple windows inherit correct fullscreen state', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await setTimeout(1000); const w2 = new BrowserWindow({ show: false }); const enterFullScreen2 = once(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 = once(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(); }); it('should not call BrowserWindow show event', async () => { const w = new BrowserWindow({ show: false }); const shown = once(w, 'show'); w.show(); await shown; let showCalled = false; w.on('show', () => { showCalled = true; }); w.previewFile(__filename); await setTimeout(500); expect(showCalled).to.equal(false, 'should not have called show twice'); }); }); // TODO (jkleinsc) renable these tests on mas arm64 ifdescribe(!process.mas || process.arch !== 'arm64')('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 = once(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 = once(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 = once(app, 'browser-window-created') as Promise<[any, BrowserWindow]>; 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 = once(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 = once(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 = once(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 = once(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 = once(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 = once(w1, 'focus'); w1.webContents.focus(); await w1Focused; expect(w1.webContents.isFocused()).to.be.true('focuses window'); }); }); describe('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 = once(w.webContents, 'paint') as Promise<[any, Electron.Rectangle, Electron.NativeImage]>; 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 = once(w.webContents, 'paint') as Promise<[any, Electron.Rectangle, Electron.NativeImage]>; 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 = once(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 = once(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.stopPainting(); w.webContents.startPainting(); await once(w.webContents, 'paint') as [any, Electron.Rectangle, Electron.NativeImage]; 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 once(w.webContents, 'paint') as [any, Electron.Rectangle, Electron.NativeImage]; expect(w.webContents.getFrameRate()).to.equal(60); }); it('has default frame rate (property)', async () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await once(w.webContents, 'paint') as [any, Electron.Rectangle, Electron.NativeImage]; expect(w.webContents.frameRate).to.equal(60); }); it('sets custom frame rate (function)', async () => { const domReady = once(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.setFrameRate(30); await once(w.webContents, 'paint') as [any, Electron.Rectangle, Electron.NativeImage]; expect(w.webContents.getFrameRate()).to.equal(30); }); it('sets custom frame rate (property)', async () => { const domReady = once(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.frameRate = 30; await once(w.webContents, 'paint') as [any, Electron.Rectangle, Electron.NativeImage]; expect(w.webContents.frameRate).to.equal(30); }); }); }); describe('"transparent" option', () => { afterEach(closeAllWindows); ifit(process.platform !== 'linux')('correctly returns isMaximized() when the window is maximized then minimized', async () => { const w = new BrowserWindow({ frame: false, transparent: true }); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMaximized()).to.be.false(); expect(w.isMinimized()).to.be.true(); }); // 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 once(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 === 'darwin' && process.arch === 'x64')('should not display a visible background', async () => { const display = screen.getPrimaryDisplay(); const backgroundWindow = new BrowserWindow({ ...display.bounds, frame: false, backgroundColor: HexColors.GREEN, hasShadow: false }); await backgroundWindow.loadURL('about:blank'); const foregroundWindow = new BrowserWindow({ ...display.bounds, show: true, transparent: true, frame: false, hasShadow: false }); const colorFile = path.join(__dirname, 'fixtures', 'pages', 'half-background-color.html'); await foregroundWindow.loadFile(colorFile); await setTimeout(1000); 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, HexColors.GREEN)).to.be.true(); expect(areColorsSimilar(rightHalfColor, HexColors.RED)).to.be.true(); }); ifit(process.platform === 'darwin')('Allows setting a transparent window via CSS', async () => { const display = screen.getPrimaryDisplay(); const backgroundWindow = new BrowserWindow({ ...display.bounds, frame: false, backgroundColor: HexColors.PURPLE, hasShadow: false }); await backgroundWindow.loadURL('about:blank'); const foregroundWindow = new BrowserWindow({ ...display.bounds, frame: false, transparent: true, hasShadow: false, webPreferences: { contextIsolation: false, nodeIntegration: true } }); foregroundWindow.loadFile(path.join(__dirname, 'fixtures', 'pages', 'css-transparent.html')); await once(ipcMain, 'set-transparent'); await setTimeout(); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); expect(areColorsSimilar(centerColor, HexColors.PURPLE)).to.be.true(); }); // Linux and arm64 platforms (WOA and macOS) do not return any capture sources ifit(process.platform === 'darwin' && process.arch === 'x64')('should not make background transparent if falsy', async () => { const display = screen.getPrimaryDisplay(); for (const transparent of [false, undefined]) { const window = new BrowserWindow({ ...display.bounds, transparent }); await once(window, 'show'); await window.webContents.loadURL('data:text/html,<head><meta name="color-scheme" content="dark"></head>'); await setTimeout(500); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); window.close(); // color-scheme is set to dark so background should not be white expect(areColorsSimilar(centerColor, HexColors.WHITE)).to.be.false(); } }); }); describe('"backgroundColor" option', () => { afterEach(closeAllWindows); // Linux/WOA doesn't return any capture sources. ifit(process.platform === 'darwin')('should display the set color', async () => { const display = screen.getPrimaryDisplay(); const w = new BrowserWindow({ ...display.bounds, show: true, backgroundColor: HexColors.BLUE }); w.loadURL('about:blank'); await once(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, HexColors.BLUE)).to.be.true(); }); }); });
closed
electron/electron
https://github.com/electron/electron
39,630
[Bug]: fullscreenable in BrowserWindowConstructorOptions is ignored if resizable flag presents
### 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 25.6.0 ### What operating system are you using? macOS ### Operating System Version 12.3 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior Windows parameters corresponds to constructor options ### Actual Behavior It doesn't ### Testcase Gist URL https://gist.github.com/origin-yaropolk/8770735fda705a6bbc7d2132a30314dc ### Additional Information _No response_
https://github.com/electron/electron/issues/39630
https://github.com/electron/electron/pull/39620
2affecd4dd26b9f0cf2644ec115635559f920480
33e66b5cd02d2b258b956022c482024c74c13b4b
2023-08-23T17:00:10Z
c++
2023-08-24T20:54:08Z
shell/browser/native_window_mac.mm
// 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_mac.h" #include <AvailabilityMacros.h> #include <objc/objc-runtime.h> #include <algorithm> #include <memory> #include <string> #include <utility> #include <vector> #include "base/mac/mac_util.h" #include "base/mac/scoped_cftyperef.h" #include "base/strings/sys_string_conversions.h" #include "components/remote_cocoa/app_shim/native_widget_ns_window_bridge.h" #include "components/remote_cocoa/browser/scoped_cg_window_id.h" #include "content/public/browser/browser_accessibility_state.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/desktop_media_id.h" #include "shell/browser/browser.h" #include "shell/browser/javascript_environment.h" #include "shell/browser/native_browser_view_mac.h" #include "shell/browser/ui/cocoa/electron_native_widget_mac.h" #include "shell/browser/ui/cocoa/electron_ns_window.h" #include "shell/browser/ui/cocoa/electron_ns_window_delegate.h" #include "shell/browser/ui/cocoa/electron_preview_item.h" #include "shell/browser/ui/cocoa/electron_touch_bar.h" #include "shell/browser/ui/cocoa/root_view_mac.h" #include "shell/browser/ui/cocoa/window_buttons_proxy.h" #include "shell/browser/ui/drag_util.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/window_list.h" #include "shell/common/gin_converters/gfx_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/node_includes.h" #include "shell/common/options_switches.h" #include "shell/common/process_util.h" #include "skia/ext/skia_utils_mac.h" #include "third_party/skia/include/core/SkRegion.h" #include "third_party/webrtc/modules/desktop_capture/mac/window_list_utils.h" #include "ui/base/hit_test.h" #include "ui/display/screen.h" #include "ui/gfx/skia_util.h" #include "ui/gl/gpu_switching_manager.h" #include "ui/views/background.h" #include "ui/views/cocoa/native_widget_mac_ns_window_host.h" #include "ui/views/widget/widget.h" #include "ui/views/window/native_frame_view_mac.h" @interface ElectronProgressBar : NSProgressIndicator @end @implementation ElectronProgressBar - (void)drawRect:(NSRect)dirtyRect { if (self.style != NSProgressIndicatorStyleBar) return; // Draw edges of rounded rect. NSRect rect = NSInsetRect([self bounds], 1.0, 1.0); CGFloat radius = rect.size.height / 2; NSBezierPath* bezier_path = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [bezier_path setLineWidth:2.0]; [[NSColor grayColor] set]; [bezier_path stroke]; // Fill the rounded rect. rect = NSInsetRect(rect, 2.0, 2.0); radius = rect.size.height / 2; bezier_path = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [bezier_path setLineWidth:1.0]; [bezier_path addClip]; // Calculate the progress width. rect.size.width = floor(rect.size.width * ([self doubleValue] / [self maxValue])); // Fill the progress bar with color blue. [[NSColor colorWithSRGBRed:0.2 green:0.6 blue:1 alpha:1] set]; NSRectFill(rect); } @end namespace gin { template <> struct Converter<electron::NativeWindowMac::VisualEffectState> { static bool FromV8(v8::Isolate* isolate, v8::Handle<v8::Value> val, electron::NativeWindowMac::VisualEffectState* out) { using VisualEffectState = electron::NativeWindowMac::VisualEffectState; std::string visual_effect_state; if (!ConvertFromV8(isolate, val, &visual_effect_state)) return false; if (visual_effect_state == "followWindow") { *out = VisualEffectState::kFollowWindow; } else if (visual_effect_state == "active") { *out = VisualEffectState::kActive; } else if (visual_effect_state == "inactive") { *out = VisualEffectState::kInactive; } else { return false; } return true; } }; } // namespace gin namespace electron { namespace { bool IsFramelessWindow(NSView* view) { NSWindow* nswindow = [view window]; if (![nswindow respondsToSelector:@selector(shell)]) return false; NativeWindow* window = [static_cast<ElectronNSWindow*>(nswindow) shell]; return window && !window->has_frame(); } IMP original_set_frame_size = nullptr; IMP original_view_did_move_to_superview = nullptr; // This method is directly called by NSWindow during a window resize on OSX // 10.10.0, beta 2. We must override it to prevent the content view from // shrinking. void SetFrameSize(NSView* self, SEL _cmd, NSSize size) { if (!IsFramelessWindow(self)) { auto original = reinterpret_cast<decltype(&SetFrameSize)>(original_set_frame_size); return original(self, _cmd, size); } // For frameless window, resize the view to cover full window. if ([self superview]) size = [[self superview] bounds].size; auto super_impl = reinterpret_cast<decltype(&SetFrameSize)>( [[self superclass] instanceMethodForSelector:_cmd]); super_impl(self, _cmd, size); } // The contentView gets moved around during certain full-screen operations. // This is less than ideal, and should eventually be removed. void ViewDidMoveToSuperview(NSView* self, SEL _cmd) { if (!IsFramelessWindow(self)) { // [BridgedContentView viewDidMoveToSuperview]; auto original = reinterpret_cast<decltype(&ViewDidMoveToSuperview)>( original_view_did_move_to_superview); if (original) original(self, _cmd); return; } [self setFrame:[[self superview] bounds]]; } // -[NSWindow orderWindow] does not handle reordering for children // windows. Their order is fixed to the attachment order (the last attached // window is on the top). Therefore, work around it by re-parenting in our // desired order. void ReorderChildWindowAbove(NSWindow* child_window, NSWindow* other_window) { NSWindow* parent = [child_window parentWindow]; DCHECK(parent); // `ordered_children` sorts children windows back to front. NSArray<NSWindow*>* children = [[child_window parentWindow] childWindows]; std::vector<std::pair<NSInteger, NSWindow*>> ordered_children; for (NSWindow* child in children) ordered_children.push_back({[child orderedIndex], child}); std::sort(ordered_children.begin(), ordered_children.end(), std::greater<>()); // If `other_window` is nullptr, place `child_window` in front of // all other children windows. if (other_window == nullptr) other_window = ordered_children.back().second; if (child_window == other_window) return; for (NSWindow* child in children) [parent removeChildWindow:child]; const bool relative_to_parent = parent == other_window; if (relative_to_parent) [parent addChildWindow:child_window ordered:NSWindowAbove]; // Re-parent children windows in the desired order. for (auto [ordered_index, child] : ordered_children) { if (child != child_window && child != other_window) { [parent addChildWindow:child ordered:NSWindowAbove]; } else if (child == other_window && !relative_to_parent) { [parent addChildWindow:other_window ordered:NSWindowAbove]; [parent addChildWindow:child_window ordered:NSWindowAbove]; } } } } // namespace NativeWindowMac::NativeWindowMac(const gin_helper::Dictionary& options, NativeWindow* parent) : NativeWindow(options, parent), root_view_(new RootViewMac(this)) { ui::NativeTheme::GetInstanceForNativeUi()->AddObserver(this); display::Screen::GetScreen()->AddObserver(this); int width = 800, height = 600; options.Get(options::kWidth, &width); options.Get(options::kHeight, &height); NSRect main_screen_rect = [[[NSScreen screens] firstObject] frame]; gfx::Rect bounds(round((NSWidth(main_screen_rect) - width) / 2), round((NSHeight(main_screen_rect) - height) / 2), width, height); bool resizable = true; options.Get(options::kResizable, &resizable); options.Get(options::kZoomToPageWidth, &zoom_to_page_width_); options.Get(options::kSimpleFullScreen, &always_simple_fullscreen_); options.GetOptional(options::kTrafficLightPosition, &traffic_light_position_); options.Get(options::kVisualEffectState, &visual_effect_state_); if (options.Has(options::kFullscreenWindowTitle)) { EmitWarning( node::Environment::GetCurrent(JavascriptEnvironment::GetIsolate()), "\"fullscreenWindowTitle\" option has been deprecated and is " "no-op now.", "electron"); } bool minimizable = true; options.Get(options::kMinimizable, &minimizable); bool maximizable = true; options.Get(options::kMaximizable, &maximizable); bool closable = true; options.Get(options::kClosable, &closable); std::string tabbingIdentifier; options.Get(options::kTabbingIdentifier, &tabbingIdentifier); std::string windowType; options.Get(options::kType, &windowType); bool hiddenInMissionControl = false; options.Get(options::kHiddenInMissionControl, &hiddenInMissionControl); bool useStandardWindow = true; // eventually deprecate separate "standardWindow" option in favor of // standard / textured window types options.Get(options::kStandardWindow, &useStandardWindow); if (windowType == "textured") { useStandardWindow = false; } // The window without titlebar is treated the same with frameless window. if (title_bar_style_ != TitleBarStyle::kNormal) set_has_frame(false); NSUInteger styleMask = NSWindowStyleMaskTitled; // The NSWindowStyleMaskFullSizeContentView style removes rounded corners // for frameless window. bool rounded_corner = true; options.Get(options::kRoundedCorners, &rounded_corner); if (!rounded_corner && !has_frame()) styleMask = NSWindowStyleMaskBorderless; if (minimizable) styleMask |= NSWindowStyleMaskMiniaturizable; if (closable) styleMask |= NSWindowStyleMaskClosable; if (resizable) styleMask |= NSWindowStyleMaskResizable; if (!useStandardWindow || transparent() || !has_frame()) styleMask |= NSWindowStyleMaskTexturedBackground; // Create views::Widget and assign window_ with it. // TODO(zcbenz): Get rid of the window_ in future. 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.native_widget = new ElectronNativeWidgetMac(this, windowType, styleMask, widget()); widget()->Init(std::move(params)); SetCanResize(resizable); window_ = static_cast<ElectronNSWindow*>( widget()->GetNativeWindow().GetNativeNSWindow()); RegisterDeleteDelegateCallback(base::BindOnce( [](NativeWindowMac* window) { if (window->window_) window->window_ = nil; if (window->buttons_proxy_) window->buttons_proxy_ = nil; }, this)); [window_ setEnableLargerThanScreen:enable_larger_than_screen()]; window_delegate_ = [[ElectronNSWindowDelegate alloc] initWithShell:this]; [window_ setDelegate:window_delegate_]; // Only use native parent window for non-modal windows. if (parent && !is_modal()) { SetParentWindow(parent); } if (transparent()) { // Setting the background color to clear will also hide the shadow. [window_ setBackgroundColor:[NSColor clearColor]]; } if (windowType == "desktop") { [window_ setLevel:kCGDesktopWindowLevel - 1]; [window_ setDisableKeyOrMainWindow:YES]; [window_ setCollectionBehavior:(NSWindowCollectionBehaviorCanJoinAllSpaces | NSWindowCollectionBehaviorStationary | NSWindowCollectionBehaviorIgnoresCycle)]; } if (windowType == "panel") { [window_ setLevel:NSFloatingWindowLevel]; } bool focusable; if (options.Get(options::kFocusable, &focusable) && !focusable) [window_ setDisableKeyOrMainWindow:YES]; if (transparent() || !has_frame()) { // Don't show title bar. [window_ setTitlebarAppearsTransparent:YES]; [window_ setTitleVisibility:NSWindowTitleHidden]; // Remove non-transparent corners, see // https://github.com/electron/electron/issues/517. [window_ setOpaque:NO]; // Show window buttons if titleBarStyle is not "normal". if (title_bar_style_ == TitleBarStyle::kNormal) { InternalSetWindowButtonVisibility(false); } else { buttons_proxy_ = [[WindowButtonsProxy alloc] initWithWindow:window_]; [buttons_proxy_ setHeight:titlebar_overlay_height()]; if (traffic_light_position_) { [buttons_proxy_ setMargin:*traffic_light_position_]; } else if (title_bar_style_ == TitleBarStyle::kHiddenInset) { // For macOS >= 11, while this value does not match official macOS apps // like Safari or Notes, it matches titleBarStyle's old implementation // before Electron <= 12. [buttons_proxy_ setMargin:gfx::Point(12, 11)]; } if (title_bar_style_ == TitleBarStyle::kCustomButtonsOnHover) { [buttons_proxy_ setShowOnHover:YES]; } else { // customButtonsOnHover does not show buttons initially. InternalSetWindowButtonVisibility(true); } } } // Create a tab only if tabbing identifier is specified and window has // a native title bar. if (tabbingIdentifier.empty() || transparent() || !has_frame()) { [window_ setTabbingMode:NSWindowTabbingModeDisallowed]; } else { [window_ setTabbingIdentifier:base::SysUTF8ToNSString(tabbingIdentifier)]; } // Resize to content bounds. bool use_content_size = false; options.Get(options::kUseContentSize, &use_content_size); if (!has_frame() || use_content_size) SetContentSize(gfx::Size(width, height)); // Enable the NSView to accept first mouse event. bool acceptsFirstMouse = false; options.Get(options::kAcceptFirstMouse, &acceptsFirstMouse); [window_ setAcceptsFirstMouse:acceptsFirstMouse]; // Disable auto-hiding cursor. bool disableAutoHideCursor = false; options.Get(options::kDisableAutoHideCursor, &disableAutoHideCursor); [window_ setDisableAutoHideCursor:disableAutoHideCursor]; SetHiddenInMissionControl(hiddenInMissionControl); // Set maximizable state last to ensure zoom button does not get reset // by calls to other APIs. SetMaximizable(maximizable); // Default content view. SetContentView(new views::View()); AddContentViewLayers(); UpdateWindowOriginalFrame(); original_level_ = [window_ level]; } NativeWindowMac::~NativeWindowMac() = default; void NativeWindowMac::SetContentView(views::View* view) { views::View* root_view = GetContentsView(); if (content_view()) root_view->RemoveChildView(content_view()); set_content_view(view); root_view->AddChildView(content_view()); root_view->Layout(); } void NativeWindowMac::Close() { if (!IsClosable()) { WindowList::WindowCloseCancelled(this); return; } if (fullscreen_transition_state() != FullScreenTransitionState::kNone) { SetHasDeferredWindowClose(true); return; } // Ensure we're detached from the parent window before closing. RemoveChildFromParentWindow(); while (!child_windows_.empty()) { auto* child = child_windows_.back(); child->RemoveChildFromParentWindow(); } // If a sheet is attached to the window when we call // [window_ performClose:nil], the window won't close properly // even after the user has ended the sheet. // Ensure it's closed before calling [window_ performClose:nil]. if ([window_ attachedSheet]) [window_ endSheet:[window_ attachedSheet]]; [window_ performClose:nil]; // Closing a sheet doesn't trigger windowShouldClose, // so we need to manually call it ourselves here. if (is_modal() && parent() && IsVisible()) { NotifyWindowCloseButtonClicked(); } } void NativeWindowMac::CloseImmediately() { // Ensure we're detached from the parent window before closing. RemoveChildFromParentWindow(); while (!child_windows_.empty()) { auto* child = child_windows_.back(); child->RemoveChildFromParentWindow(); } [window_ close]; } void NativeWindowMac::Focus(bool focus) { if (!IsVisible()) return; if (focus) { [[NSApplication sharedApplication] activateIgnoringOtherApps:NO]; [window_ makeKeyAndOrderFront:nil]; } else { [window_ orderOut:nil]; [window_ orderBack:nil]; } } bool NativeWindowMac::IsFocused() { return [window_ isKeyWindow]; } void NativeWindowMac::Show() { if (is_modal() && parent()) { NSWindow* window = parent()->GetNativeWindow().GetNativeNSWindow(); if ([window_ sheetParent] == nil) [window beginSheet:window_ completionHandler:^(NSModalResponse){ }]; return; } // Reattach the window to the parent to actually show it. if (parent()) InternalSetParentWindow(parent(), true); // This method is supposed to put focus on window, however if the app does not // have focus then "makeKeyAndOrderFront" will only show the window. [NSApp activateIgnoringOtherApps:YES]; [window_ makeKeyAndOrderFront:nil]; } void NativeWindowMac::ShowInactive() { // Reattach the window to the parent to actually show it. if (parent()) InternalSetParentWindow(parent(), true); [window_ orderFrontRegardless]; } void NativeWindowMac::Hide() { // If a sheet is attached to the window when we call [window_ orderOut:nil], // the sheet won't be able to show again on the same window. // Ensure it's closed before calling [window_ orderOut:nil]. if ([window_ attachedSheet]) [window_ endSheet:[window_ attachedSheet]]; if (is_modal() && parent()) { [window_ orderOut:nil]; [parent()->GetNativeWindow().GetNativeNSWindow() endSheet:window_]; return; } DetachChildren(); // Detach the window from the parent before. if (parent()) InternalSetParentWindow(parent(), false); [window_ orderOut:nil]; } bool NativeWindowMac::IsVisible() { bool occluded = [window_ occlusionState] == NSWindowOcclusionStateVisible; return [window_ isVisible] && !occluded && !IsMinimized(); } bool NativeWindowMac::IsEnabled() { return [window_ attachedSheet] == nil; } void NativeWindowMac::SetEnabled(bool enable) { if (!enable) { NSRect frame = [window_ frame]; NSWindow* window = [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, frame.size.width, frame.size.height) styleMask:NSWindowStyleMaskTitled backing:NSBackingStoreBuffered defer:NO]; [window setAlphaValue:0.5]; [window_ beginSheet:window completionHandler:^(NSModalResponse returnCode) { NSLog(@"main window disabled"); return; }]; } else if ([window_ attachedSheet]) { [window_ endSheet:[window_ attachedSheet]]; } } void NativeWindowMac::Maximize() { const bool is_visible = [window_ isVisible]; if (IsMaximized()) { if (!is_visible) ShowInactive(); return; } // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); [window_ zoom:nil]; if (!is_visible) { ShowInactive(); NotifyWindowMaximize(); } } void NativeWindowMac::Unmaximize() { // Bail if the last user set bounds were the same size as the window // screen (e.g. the user set the window to maximized via setBounds) // // Per docs during zoom: // > If there’s no saved user state because there has been no previous // > zoom,the size and location of the window don’t change. // // However, in classic Apple fashion, this is not the case in practice, // and the frame inexplicably becomes very tiny. We should prevent // zoom from being called if the window is being unmaximized and its // unmaximized window bounds are themselves functionally maximized. if (!IsMaximized() || user_set_bounds_maximized_) return; [window_ zoom:nil]; } bool NativeWindowMac::IsMaximized() { // It's possible for [window_ isZoomed] to be true // when the window is minimized or fullscreened. if (IsMinimized() || IsFullscreen()) return false; if (HasStyleMask(NSWindowStyleMaskResizable) != 0) return [window_ isZoomed]; NSRect rectScreen = GetAspectRatio() > 0.0 ? default_frame_for_zoom() : [[NSScreen mainScreen] visibleFrame]; return NSEqualRects([window_ frame], rectScreen); } void NativeWindowMac::Minimize() { if (IsMinimized()) return; // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); [window_ miniaturize:nil]; } void NativeWindowMac::Restore() { [window_ deminiaturize:nil]; } bool NativeWindowMac::IsMinimized() { return [window_ isMiniaturized]; } bool NativeWindowMac::HandleDeferredClose() { if (has_deferred_window_close_) { SetHasDeferredWindowClose(false); Close(); return true; } return false; } void NativeWindowMac::RemoveChildWindow(NativeWindow* child) { child_windows_.remove_if([&child](NativeWindow* w) { return (w == child); }); [window_ removeChildWindow:child->GetNativeWindow().GetNativeNSWindow()]; } void NativeWindowMac::RemoveChildFromParentWindow() { if (parent() && !is_modal()) { parent()->RemoveChildWindow(this); NativeWindow::SetParentWindow(nullptr); } } void NativeWindowMac::AttachChildren() { for (auto* child : child_windows_) { auto* child_nswindow = child->GetNativeWindow().GetNativeNSWindow(); if ([child_nswindow parentWindow] == window_) continue; // Attaching a window as a child window resets its window level, so // save and restore it afterwards. NSInteger level = window_.level; [window_ addChildWindow:child_nswindow ordered:NSWindowAbove]; [window_ setLevel:level]; } } void NativeWindowMac::DetachChildren() { DCHECK(child_windows_.size() == [[window_ childWindows] count]); // Hide all children before hiding/minimizing the window. // NativeWidgetNSWindowBridge::NotifyVisibilityChangeDown() // will DCHECK otherwise. for (auto* child : child_windows_) { [child->GetNativeWindow().GetNativeNSWindow() orderOut:nil]; } } void NativeWindowMac::SetFullScreen(bool fullscreen) { if (!has_frame() && !HasStyleMask(NSWindowStyleMaskTitled)) return; // [NSWindow -toggleFullScreen] is an asynchronous operation, which means // that it's possible to call it while a fullscreen transition is currently // in process. This can create weird behavior (incl. phantom windows), // so we want to schedule a transition for when the current one has completed. if (fullscreen_transition_state() != FullScreenTransitionState::kNone) { if (!pending_transitions_.empty()) { bool last_pending = pending_transitions_.back(); // Only push new transitions if they're different than the last transition // in the queue. if (last_pending != fullscreen) pending_transitions_.push(fullscreen); } else { pending_transitions_.push(fullscreen); } return; } if (fullscreen == IsFullscreen() || !IsFullScreenable()) return; // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); // This needs to be set here because it can be the case that // SetFullScreen is called by a user before windowWillEnterFullScreen // or windowWillExitFullScreen are invoked, and so a potential transition // could be dropped. fullscreen_transition_state_ = fullscreen ? FullScreenTransitionState::kEntering : FullScreenTransitionState::kExiting; [window_ toggleFullScreenMode:nil]; } bool NativeWindowMac::IsFullscreen() const { return HasStyleMask(NSWindowStyleMaskFullScreen); } void NativeWindowMac::SetBounds(const gfx::Rect& bounds, bool animate) { // Do nothing if in fullscreen mode. if (IsFullscreen()) return; // Check size constraints since setFrame does not check it. gfx::Size size = bounds.size(); size.SetToMax(GetMinimumSize()); gfx::Size max_size = GetMaximumSize(); if (!max_size.IsEmpty()) size.SetToMin(max_size); NSRect cocoa_bounds = NSMakeRect(bounds.x(), 0, size.width(), size.height()); // Flip coordinates based on the primary screen. NSScreen* screen = [[NSScreen screens] firstObject]; cocoa_bounds.origin.y = NSHeight([screen frame]) - size.height() - bounds.y(); [window_ setFrame:cocoa_bounds display:YES animate:animate]; user_set_bounds_maximized_ = IsMaximized() ? true : false; UpdateWindowOriginalFrame(); } gfx::Rect NativeWindowMac::GetBounds() { NSRect frame = [window_ frame]; gfx::Rect bounds(frame.origin.x, 0, NSWidth(frame), NSHeight(frame)); NSScreen* screen = [[NSScreen screens] firstObject]; bounds.set_y(NSHeight([screen frame]) - NSMaxY(frame)); return bounds; } bool NativeWindowMac::IsNormal() { return NativeWindow::IsNormal() && !IsSimpleFullScreen(); } gfx::Rect NativeWindowMac::GetNormalBounds() { if (IsNormal()) { return GetBounds(); } NSRect frame = original_frame_; gfx::Rect bounds(frame.origin.x, 0, NSWidth(frame), NSHeight(frame)); NSScreen* screen = [[NSScreen screens] firstObject]; bounds.set_y(NSHeight([screen frame]) - NSMaxY(frame)); return bounds; // Works on OS_WIN ! // return widget()->GetRestoredBounds(); } void NativeWindowMac::SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints) { auto convertSize = [this](const gfx::Size& size) { // Our frameless window still has titlebar attached, so setting contentSize // will result in actual content size being larger. if (!has_frame()) { NSRect frame = NSMakeRect(0, 0, size.width(), size.height()); NSRect content = [window_ originalContentRectForFrameRect:frame]; return content.size; } else { return NSMakeSize(size.width(), size.height()); } }; NSView* content = [window_ contentView]; if (size_constraints.HasMinimumSize()) { NSSize min_size = convertSize(size_constraints.GetMinimumSize()); [window_ setContentMinSize:[content convertSize:min_size toView:nil]]; } if (size_constraints.HasMaximumSize()) { NSSize max_size = convertSize(size_constraints.GetMaximumSize()); [window_ setContentMaxSize:[content convertSize:max_size toView:nil]]; } NativeWindow::SetContentSizeConstraints(size_constraints); } bool NativeWindowMac::MoveAbove(const std::string& sourceId) { const content::DesktopMediaID id = content::DesktopMediaID::Parse(sourceId); if (id.type != content::DesktopMediaID::TYPE_WINDOW) return false; // Check if the window source is valid. const CGWindowID window_id = id.id; if (!webrtc::GetWindowOwnerPid(window_id)) return false; if (!parent() || is_modal()) { [window_ orderWindow:NSWindowAbove relativeTo:window_id]; } else { NSWindow* other_window = [NSApp windowWithWindowNumber:window_id]; ReorderChildWindowAbove(window_, other_window); } return true; } void NativeWindowMac::MoveTop() { if (!parent() || is_modal()) { [window_ orderWindow:NSWindowAbove relativeTo:0]; } else { ReorderChildWindowAbove(window_, nullptr); } } void NativeWindowMac::SetResizable(bool resizable) { ScopedDisableResize disable_resize; SetStyleMask(resizable, NSWindowStyleMaskResizable); // Right now, resizable and fullscreenable are decoupled in // documentation and on Windows/Linux. Chromium disables // fullscreenability if resizability is false on macOS as well // as disabling the maximize traffic light unless the window // is both resizable and maximizable. To work around this, we want // to match behavior on other platforms by disabiliting the maximize // button but keeping fullscreenability enabled. // TODO(codebytere): refactor this once we have a better solution. SetCanResize(resizable); if (!resizable) { SetFullScreenable(true); [[window_ standardWindowButton:NSWindowZoomButton] setEnabled:false]; } else { SetFullScreenable(true); [[window_ standardWindowButton:NSWindowZoomButton] setEnabled:IsFullScreenable()]; } } bool NativeWindowMac::IsResizable() { bool in_fs_transition = fullscreen_transition_state() != FullScreenTransitionState::kNone; bool has_rs_mask = HasStyleMask(NSWindowStyleMaskResizable); return has_rs_mask && !IsFullscreen() && !in_fs_transition; } void NativeWindowMac::SetMovable(bool movable) { [window_ setMovable:movable]; } bool NativeWindowMac::IsMovable() { return [window_ isMovable]; } void NativeWindowMac::SetMinimizable(bool minimizable) { SetStyleMask(minimizable, NSWindowStyleMaskMiniaturizable); } bool NativeWindowMac::IsMinimizable() { return HasStyleMask(NSWindowStyleMaskMiniaturizable); } void NativeWindowMac::SetMaximizable(bool maximizable) { maximizable_ = maximizable; [[window_ standardWindowButton:NSWindowZoomButton] setEnabled:maximizable]; } bool NativeWindowMac::IsMaximizable() { return [[window_ standardWindowButton:NSWindowZoomButton] isEnabled]; } void NativeWindowMac::SetFullScreenable(bool fullscreenable) { SetCollectionBehavior(fullscreenable, NSWindowCollectionBehaviorFullScreenPrimary); // On EL Capitan this flag is required to hide fullscreen button. SetCollectionBehavior(!fullscreenable, NSWindowCollectionBehaviorFullScreenAuxiliary); } bool NativeWindowMac::IsFullScreenable() { NSUInteger collectionBehavior = [window_ collectionBehavior]; return collectionBehavior & NSWindowCollectionBehaviorFullScreenPrimary; } void NativeWindowMac::SetClosable(bool closable) { SetStyleMask(closable, NSWindowStyleMaskClosable); } bool NativeWindowMac::IsClosable() { return HasStyleMask(NSWindowStyleMaskClosable); } void NativeWindowMac::SetAlwaysOnTop(ui::ZOrderLevel z_order, const std::string& level_name, int relative_level) { if (z_order == ui::ZOrderLevel::kNormal) { SetWindowLevel(NSNormalWindowLevel); return; } int level = NSNormalWindowLevel; if (level_name == "floating") { level = NSFloatingWindowLevel; } else if (level_name == "torn-off-menu") { level = NSTornOffMenuWindowLevel; } else if (level_name == "modal-panel") { level = NSModalPanelWindowLevel; } else if (level_name == "main-menu") { level = NSMainMenuWindowLevel; } else if (level_name == "status") { level = NSStatusWindowLevel; } else if (level_name == "pop-up-menu") { level = NSPopUpMenuWindowLevel; } else if (level_name == "screen-saver") { level = NSScreenSaverWindowLevel; } SetWindowLevel(level + relative_level); } std::string NativeWindowMac::GetAlwaysOnTopLevel() { std::string level_name = "normal"; int level = [window_ level]; if (level == NSFloatingWindowLevel) { level_name = "floating"; } else if (level == NSTornOffMenuWindowLevel) { level_name = "torn-off-menu"; } else if (level == NSModalPanelWindowLevel) { level_name = "modal-panel"; } else if (level == NSMainMenuWindowLevel) { level_name = "main-menu"; } else if (level == NSStatusWindowLevel) { level_name = "status"; } else if (level == NSPopUpMenuWindowLevel) { level_name = "pop-up-menu"; } else if (level == NSScreenSaverWindowLevel) { level_name = "screen-saver"; } return level_name; } void NativeWindowMac::SetWindowLevel(int unbounded_level) { int level = std::min( std::max(unbounded_level, CGWindowLevelForKey(kCGMinimumWindowLevelKey)), CGWindowLevelForKey(kCGMaximumWindowLevelKey)); ui::ZOrderLevel z_order_level = level == NSNormalWindowLevel ? ui::ZOrderLevel::kNormal : ui::ZOrderLevel::kFloatingWindow; bool did_z_order_level_change = z_order_level != GetZOrderLevel(); was_maximizable_ = IsMaximizable(); // We need to explicitly keep the NativeWidget up to date, since it stores the // window level in a local variable, rather than reading it from the NSWindow. // Unfortunately, it results in a second setLevel call. It's not ideal, but we // don't expect this to cause any user-visible jank. widget()->SetZOrderLevel(z_order_level); [window_ setLevel:level]; // Set level will make the zoom button revert to default, probably // a bug of Cocoa or macOS. SetMaximizable(was_maximizable_); // This must be notified at the very end or IsAlwaysOnTop // will not yet have been updated to reflect the new status if (did_z_order_level_change) NativeWindow::NotifyWindowAlwaysOnTopChanged(); } ui::ZOrderLevel NativeWindowMac::GetZOrderLevel() { return widget()->GetZOrderLevel(); } void NativeWindowMac::Center() { [window_ center]; } void NativeWindowMac::Invalidate() { [[window_ contentView] setNeedsDisplay:YES]; } void NativeWindowMac::SetTitle(const std::string& title) { [window_ setTitle:base::SysUTF8ToNSString(title)]; if (buttons_proxy_) [buttons_proxy_ redraw]; } std::string NativeWindowMac::GetTitle() { return base::SysNSStringToUTF8([window_ title]); } void NativeWindowMac::FlashFrame(bool flash) { if (flash) { attention_request_id_ = [NSApp requestUserAttention:NSInformationalRequest]; } else { [NSApp cancelUserAttentionRequest:attention_request_id_]; attention_request_id_ = 0; } } void NativeWindowMac::SetSkipTaskbar(bool skip) {} bool NativeWindowMac::IsExcludedFromShownWindowsMenu() { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); return [window isExcludedFromWindowsMenu]; } void NativeWindowMac::SetExcludedFromShownWindowsMenu(bool excluded) { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); [window setExcludedFromWindowsMenu:excluded]; } void NativeWindowMac::OnDisplayMetricsChanged(const display::Display& display, uint32_t changed_metrics) { // We only want to force screen recalibration if we're in simpleFullscreen // mode. if (!is_simple_fullscreen_) return; content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&NativeWindow::UpdateFrame, GetWeakPtr())); } void NativeWindowMac::SetSimpleFullScreen(bool simple_fullscreen) { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); if (simple_fullscreen && !is_simple_fullscreen_) { is_simple_fullscreen_ = true; // Take note of the current window size and level if (IsNormal()) { UpdateWindowOriginalFrame(); original_level_ = [window_ level]; } simple_fullscreen_options_ = [NSApp currentSystemPresentationOptions]; simple_fullscreen_mask_ = [window styleMask]; // We can simulate the pre-Lion fullscreen by auto-hiding the dock and menu // bar NSApplicationPresentationOptions options = NSApplicationPresentationAutoHideDock | NSApplicationPresentationAutoHideMenuBar; [NSApp setPresentationOptions:options]; was_maximizable_ = IsMaximizable(); was_movable_ = IsMovable(); NSRect fullscreenFrame = [window.screen frame]; // If our app has dock hidden, set the window level higher so another app's // menu bar doesn't appear on top of our fullscreen app. if ([[NSRunningApplication currentApplication] activationPolicy] != NSApplicationActivationPolicyRegular) { window.level = NSPopUpMenuWindowLevel; } // Always hide the titlebar in simple fullscreen mode. // // Note that we must remove the NSWindowStyleMaskTitled style instead of // using the [window_ setTitleVisibility:], as the latter would leave the // window with rounded corners. SetStyleMask(false, NSWindowStyleMaskTitled); if (!window_button_visibility_.has_value()) { // Lets keep previous behaviour - hide window controls in titled // fullscreen mode when not specified otherwise. InternalSetWindowButtonVisibility(false); } [window setFrame:fullscreenFrame display:YES animate:YES]; // Fullscreen windows can't be resized, minimized, maximized, or moved SetMinimizable(false); SetResizable(false); SetMaximizable(false); SetMovable(false); } else if (!simple_fullscreen && is_simple_fullscreen_) { is_simple_fullscreen_ = false; [window setFrame:original_frame_ display:YES animate:YES]; window.level = original_level_; [NSApp setPresentationOptions:simple_fullscreen_options_]; // Restore original style mask ScopedDisableResize disable_resize; [window_ setStyleMask:simple_fullscreen_mask_]; // Restore window manipulation abilities SetMaximizable(was_maximizable_); SetMovable(was_movable_); // Restore default window controls visibility state. if (!window_button_visibility_.has_value()) { bool visibility; if (has_frame()) visibility = true; else visibility = title_bar_style_ != TitleBarStyle::kNormal; InternalSetWindowButtonVisibility(visibility); } if (buttons_proxy_) [buttons_proxy_ redraw]; } } bool NativeWindowMac::IsSimpleFullScreen() { return is_simple_fullscreen_; } void NativeWindowMac::SetKiosk(bool kiosk) { if (kiosk && !is_kiosk_) { kiosk_options_ = [NSApp currentSystemPresentationOptions]; NSApplicationPresentationOptions options = NSApplicationPresentationHideDock | NSApplicationPresentationHideMenuBar | NSApplicationPresentationDisableAppleMenu | NSApplicationPresentationDisableProcessSwitching | NSApplicationPresentationDisableForceQuit | NSApplicationPresentationDisableSessionTermination | NSApplicationPresentationDisableHideApplication; [NSApp setPresentationOptions:options]; is_kiosk_ = true; fullscreen_before_kiosk_ = IsFullscreen(); if (!fullscreen_before_kiosk_) SetFullScreen(true); } else if (!kiosk && is_kiosk_) { is_kiosk_ = false; if (!fullscreen_before_kiosk_) SetFullScreen(false); // Set presentation options *after* asynchronously exiting // fullscreen to ensure they take effect. [NSApp setPresentationOptions:kiosk_options_]; } } bool NativeWindowMac::IsKiosk() { return is_kiosk_; } void NativeWindowMac::SetBackgroundColor(SkColor color) { base::ScopedCFTypeRef<CGColorRef> cgcolor( skia::CGColorCreateFromSkColor(color)); [[[window_ contentView] layer] setBackgroundColor:cgcolor]; } SkColor NativeWindowMac::GetBackgroundColor() { CGColorRef color = [[[window_ contentView] layer] backgroundColor]; if (!color) return SK_ColorTRANSPARENT; return skia::CGColorRefToSkColor(color); } void NativeWindowMac::SetHasShadow(bool has_shadow) { [window_ setHasShadow:has_shadow]; } bool NativeWindowMac::HasShadow() { return [window_ hasShadow]; } void NativeWindowMac::InvalidateShadow() { [window_ invalidateShadow]; } void NativeWindowMac::SetOpacity(const double opacity) { const double boundedOpacity = std::clamp(opacity, 0.0, 1.0); [window_ setAlphaValue:boundedOpacity]; } double NativeWindowMac::GetOpacity() { return [window_ alphaValue]; } void NativeWindowMac::SetRepresentedFilename(const std::string& filename) { [window_ setRepresentedFilename:base::SysUTF8ToNSString(filename)]; if (buttons_proxy_) [buttons_proxy_ redraw]; } std::string NativeWindowMac::GetRepresentedFilename() { return base::SysNSStringToUTF8([window_ representedFilename]); } void NativeWindowMac::SetDocumentEdited(bool edited) { [window_ setDocumentEdited:edited]; if (buttons_proxy_) [buttons_proxy_ redraw]; } bool NativeWindowMac::IsDocumentEdited() { return [window_ isDocumentEdited]; } bool NativeWindowMac::IsHiddenInMissionControl() { NSUInteger collectionBehavior = [window_ collectionBehavior]; return collectionBehavior & NSWindowCollectionBehaviorTransient; } void NativeWindowMac::SetHiddenInMissionControl(bool hidden) { SetCollectionBehavior(hidden, NSWindowCollectionBehaviorTransient); } void NativeWindowMac::SetIgnoreMouseEvents(bool ignore, bool forward) { [window_ setIgnoresMouseEvents:ignore]; if (!ignore) { SetForwardMouseMessages(NO); } else { SetForwardMouseMessages(forward); } } void NativeWindowMac::SetContentProtection(bool enable) { [window_ setSharingType:enable ? NSWindowSharingNone : NSWindowSharingReadOnly]; } void NativeWindowMac::SetFocusable(bool focusable) { // No known way to unfocus the window if it had the focus. Here we do not // want to call Focus(false) because it moves the window to the back, i.e. // at the bottom in term of z-order. [window_ setDisableKeyOrMainWindow:!focusable]; } bool NativeWindowMac::IsFocusable() { return ![window_ disableKeyOrMainWindow]; } void NativeWindowMac::AddBrowserView(NativeBrowserView* view) { [CATransaction begin]; [CATransaction setDisableActions:YES]; if (!view) { [CATransaction commit]; return; } add_browser_view(view); if (view->GetInspectableWebContentsView()) { auto* native_view = view->GetInspectableWebContentsView() ->GetNativeView() .GetNativeNSView(); [[window_ contentView] addSubview:native_view positioned:NSWindowAbove relativeTo:nil]; native_view.hidden = NO; } [CATransaction commit]; } void NativeWindowMac::RemoveBrowserView(NativeBrowserView* view) { [CATransaction begin]; [CATransaction setDisableActions:YES]; if (!view) { [CATransaction commit]; return; } if (view->GetInspectableWebContentsView()) [view->GetInspectableWebContentsView()->GetNativeView().GetNativeNSView() removeFromSuperview]; remove_browser_view(view); [CATransaction commit]; } void NativeWindowMac::SetTopBrowserView(NativeBrowserView* view) { [CATransaction begin]; [CATransaction setDisableActions:YES]; if (!view) { [CATransaction commit]; return; } remove_browser_view(view); add_browser_view(view); if (view->GetInspectableWebContentsView()) { auto* native_view = view->GetInspectableWebContentsView() ->GetNativeView() .GetNativeNSView(); [[window_ contentView] addSubview:native_view positioned:NSWindowAbove relativeTo:nil]; native_view.hidden = NO; } [CATransaction commit]; } void NativeWindowMac::SetParentWindow(NativeWindow* parent) { InternalSetParentWindow(parent, IsVisible()); } gfx::NativeView NativeWindowMac::GetNativeView() const { return [window_ contentView]; } gfx::NativeWindow NativeWindowMac::GetNativeWindow() const { return window_; } gfx::AcceleratedWidget NativeWindowMac::GetAcceleratedWidget() const { return [window_ windowNumber]; } content::DesktopMediaID NativeWindowMac::GetDesktopMediaID() const { auto desktop_media_id = content::DesktopMediaID( content::DesktopMediaID::TYPE_WINDOW, GetAcceleratedWidget()); // c.f. // https://source.chromium.org/chromium/chromium/src/+/main:chrome/browser/media/webrtc/native_desktop_media_list.cc;l=775-780;drc=79502ab47f61bff351426f57f576daef02b1a8dc // Refs https://github.com/electron/electron/pull/30507 // TODO(deepak1556): Match upstream for `kWindowCaptureMacV2` #if 0 if (remote_cocoa::ScopedCGWindowID::Get(desktop_media_id.id)) { desktop_media_id.window_id = desktop_media_id.id; } #endif return desktop_media_id; } NativeWindowHandle NativeWindowMac::GetNativeWindowHandle() const { return [window_ contentView]; } void NativeWindowMac::SetProgressBar(double progress, const NativeWindow::ProgressState state) { NSDockTile* dock_tile = [NSApp dockTile]; // Sometimes macOS would install a default contentView for dock, we must // verify whether NSProgressIndicator has been installed. bool first_time = !dock_tile.contentView || [[dock_tile.contentView subviews] count] == 0 || ![[[dock_tile.contentView subviews] lastObject] isKindOfClass:[NSProgressIndicator class]]; // For the first time API invoked, we need to create a ContentView in // DockTile. if (first_time) { NSImageView* image_view = [[NSImageView alloc] init]; [image_view setImage:[NSApp applicationIconImage]]; [dock_tile setContentView:image_view]; NSRect frame = NSMakeRect(0.0f, 0.0f, dock_tile.size.width, 15.0); NSProgressIndicator* progress_indicator = [[ElectronProgressBar alloc] initWithFrame:frame]; [progress_indicator setStyle:NSProgressIndicatorStyleBar]; [progress_indicator setIndeterminate:NO]; [progress_indicator setBezeled:YES]; [progress_indicator setMinValue:0]; [progress_indicator setMaxValue:1]; [progress_indicator setHidden:NO]; [dock_tile.contentView addSubview:progress_indicator]; } NSProgressIndicator* progress_indicator = static_cast<NSProgressIndicator*>( [[[dock_tile contentView] subviews] lastObject]); if (progress < 0) { [progress_indicator setHidden:YES]; } else if (progress > 1) { [progress_indicator setHidden:NO]; [progress_indicator setIndeterminate:YES]; [progress_indicator setDoubleValue:1]; } else { [progress_indicator setHidden:NO]; [progress_indicator setDoubleValue:progress]; } [dock_tile display]; } void NativeWindowMac::SetOverlayIcon(const gfx::Image& overlay, const std::string& description) {} void NativeWindowMac::SetVisibleOnAllWorkspaces(bool visible, bool visibleOnFullScreen, bool skipTransformProcessType) { // In order for NSWindows to be visible on fullscreen we need to invoke // app.dock.hide() since Apple changed the underlying functionality of // NSWindows starting with 10.14 to disallow NSWindows from floating on top of // fullscreen apps. if (!skipTransformProcessType) { if (visibleOnFullScreen) { Browser::Get()->DockHide(); } else { Browser::Get()->DockShow(JavascriptEnvironment::GetIsolate()); } } SetCollectionBehavior(visible, NSWindowCollectionBehaviorCanJoinAllSpaces); SetCollectionBehavior(visibleOnFullScreen, NSWindowCollectionBehaviorFullScreenAuxiliary); } bool NativeWindowMac::IsVisibleOnAllWorkspaces() { NSUInteger collectionBehavior = [window_ collectionBehavior]; return collectionBehavior & NSWindowCollectionBehaviorCanJoinAllSpaces; } void NativeWindowMac::SetAutoHideCursor(bool auto_hide) { [window_ setDisableAutoHideCursor:!auto_hide]; } void NativeWindowMac::UpdateVibrancyRadii(bool fullscreen) { NSVisualEffectView* vibrantView = [window_ vibrantView]; if (vibrantView != nil && !vibrancy_type_.empty()) { const bool no_rounded_corner = !HasStyleMask(NSWindowStyleMaskTitled); if (!has_frame() && !is_modal() && !no_rounded_corner) { CGFloat radius; if (fullscreen) { radius = 0.0f; } else if (@available(macOS 11.0, *)) { radius = 9.0f; } else { // Smaller corner radius on versions prior to Big Sur. radius = 5.0f; } CGFloat dimension = 2 * radius + 1; NSSize size = NSMakeSize(dimension, dimension); NSImage* maskImage = [NSImage imageWithSize:size flipped:NO drawingHandler:^BOOL(NSRect rect) { NSBezierPath* bezierPath = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [[NSColor blackColor] set]; [bezierPath fill]; return YES; }]; [maskImage setCapInsets:NSEdgeInsetsMake(radius, radius, radius, radius)]; [maskImage setResizingMode:NSImageResizingModeStretch]; [vibrantView setMaskImage:maskImage]; [window_ setCornerMask:maskImage]; } } } void NativeWindowMac::UpdateWindowOriginalFrame() { original_frame_ = [window_ frame]; } void NativeWindowMac::SetVibrancy(const std::string& type) { NSVisualEffectView* vibrantView = [window_ vibrantView]; if (type.empty()) { if (vibrantView == nil) return; [vibrantView removeFromSuperview]; [window_ setVibrantView:nil]; return; } NSVisualEffectMaterial vibrancyType{}; if (type == "titlebar") { vibrancyType = NSVisualEffectMaterialTitlebar; } else if (type == "selection") { vibrancyType = NSVisualEffectMaterialSelection; } else if (type == "menu") { vibrancyType = NSVisualEffectMaterialMenu; } else if (type == "popover") { vibrancyType = NSVisualEffectMaterialPopover; } else if (type == "sidebar") { vibrancyType = NSVisualEffectMaterialSidebar; } else if (type == "header") { vibrancyType = NSVisualEffectMaterialHeaderView; } else if (type == "sheet") { vibrancyType = NSVisualEffectMaterialSheet; } else if (type == "window") { vibrancyType = NSVisualEffectMaterialWindowBackground; } else if (type == "hud") { vibrancyType = NSVisualEffectMaterialHUDWindow; } else if (type == "fullscreen-ui") { vibrancyType = NSVisualEffectMaterialFullScreenUI; } else if (type == "tooltip") { vibrancyType = NSVisualEffectMaterialToolTip; } else if (type == "content") { vibrancyType = NSVisualEffectMaterialContentBackground; } else if (type == "under-window") { vibrancyType = NSVisualEffectMaterialUnderWindowBackground; } else if (type == "under-page") { vibrancyType = NSVisualEffectMaterialUnderPageBackground; } if (vibrancyType) { vibrancy_type_ = type; if (vibrantView == nil) { vibrantView = [[NSVisualEffectView alloc] initWithFrame:[[window_ contentView] bounds]]; [window_ setVibrantView:vibrantView]; [vibrantView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable]; [vibrantView setBlendingMode:NSVisualEffectBlendingModeBehindWindow]; if (visual_effect_state_ == VisualEffectState::kActive) { [vibrantView setState:NSVisualEffectStateActive]; } else if (visual_effect_state_ == VisualEffectState::kInactive) { [vibrantView setState:NSVisualEffectStateInactive]; } else { [vibrantView setState:NSVisualEffectStateFollowsWindowActiveState]; } [[window_ contentView] addSubview:vibrantView positioned:NSWindowBelow relativeTo:nil]; UpdateVibrancyRadii(IsFullscreen()); } [vibrantView setMaterial:vibrancyType]; } } void NativeWindowMac::SetWindowButtonVisibility(bool visible) { window_button_visibility_ = visible; if (buttons_proxy_) { if (visible) [buttons_proxy_ redraw]; [buttons_proxy_ setVisible:visible]; } if (title_bar_style_ != TitleBarStyle::kCustomButtonsOnHover) InternalSetWindowButtonVisibility(visible); NotifyLayoutWindowControlsOverlay(); } bool NativeWindowMac::GetWindowButtonVisibility() const { return ![window_ standardWindowButton:NSWindowZoomButton].hidden || ![window_ standardWindowButton:NSWindowMiniaturizeButton].hidden || ![window_ standardWindowButton:NSWindowCloseButton].hidden; } void NativeWindowMac::SetWindowButtonPosition( absl::optional<gfx::Point> position) { traffic_light_position_ = std::move(position); if (buttons_proxy_) { [buttons_proxy_ setMargin:traffic_light_position_]; NotifyLayoutWindowControlsOverlay(); } } absl::optional<gfx::Point> NativeWindowMac::GetWindowButtonPosition() const { return traffic_light_position_; } void NativeWindowMac::RedrawTrafficLights() { if (buttons_proxy_ && !IsFullscreen()) [buttons_proxy_ redraw]; } // In simpleFullScreen mode, update the frame for new bounds. void NativeWindowMac::UpdateFrame() { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); NSRect fullscreenFrame = [window.screen frame]; [window setFrame:fullscreenFrame display:YES animate:YES]; } void NativeWindowMac::SetTouchBar( std::vector<gin_helper::PersistentDictionary> items) { touch_bar_ = [[ElectronTouchBar alloc] initWithDelegate:window_delegate_ window:this settings:std::move(items)]; [window_ setTouchBar:nil]; } void NativeWindowMac::RefreshTouchBarItem(const std::string& item_id) { if (touch_bar_ && [window_ touchBar]) [touch_bar_ refreshTouchBarItem:[window_ touchBar] id:item_id]; } void NativeWindowMac::SetEscapeTouchBarItem( gin_helper::PersistentDictionary item) { if (touch_bar_ && [window_ touchBar]) [touch_bar_ setEscapeTouchBarItem:std::move(item) forTouchBar:[window_ touchBar]]; } void NativeWindowMac::SelectPreviousTab() { [window_ selectPreviousTab:nil]; } void NativeWindowMac::SelectNextTab() { [window_ selectNextTab:nil]; } void NativeWindowMac::ShowAllTabs() { [window_ toggleTabOverview:nil]; } void NativeWindowMac::MergeAllWindows() { [window_ mergeAllWindows:nil]; } void NativeWindowMac::MoveTabToNewWindow() { [window_ moveTabToNewWindow:nil]; } void NativeWindowMac::ToggleTabBar() { [window_ toggleTabBar:nil]; } bool NativeWindowMac::AddTabbedWindow(NativeWindow* window) { if (window_ == window->GetNativeWindow().GetNativeNSWindow()) { return false; } else { [window_ addTabbedWindow:window->GetNativeWindow().GetNativeNSWindow() ordered:NSWindowAbove]; } return true; } void NativeWindowMac::SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) { NativeWindow::SetAspectRatio(aspect_ratio, extra_size); // Reset the behaviour to default if aspect_ratio is set to 0 or less. if (aspect_ratio > 0.0) { NSSize aspect_ratio_size = NSMakeSize(aspect_ratio, 1.0); if (has_frame()) [window_ setContentAspectRatio:aspect_ratio_size]; else [window_ setAspectRatio:aspect_ratio_size]; } else { [window_ setResizeIncrements:NSMakeSize(1.0, 1.0)]; } } void NativeWindowMac::PreviewFile(const std::string& path, const std::string& display_name) { preview_item_ = [[ElectronPreviewItem alloc] initWithURL:[NSURL fileURLWithPath:base::SysUTF8ToNSString(path)] title:base::SysUTF8ToNSString(display_name)]; [[QLPreviewPanel sharedPreviewPanel] makeKeyAndOrderFront:nil]; } void NativeWindowMac::CloseFilePreview() { if ([QLPreviewPanel sharedPreviewPanelExists]) { [[QLPreviewPanel sharedPreviewPanel] close]; } } gfx::Rect NativeWindowMac::ContentBoundsToWindowBounds( const gfx::Rect& bounds) const { if (has_frame()) { gfx::Rect window_bounds( [window_ frameRectForContentRect:bounds.ToCGRect()]); int frame_height = window_bounds.height() - bounds.height(); window_bounds.set_y(window_bounds.y() - frame_height); return window_bounds; } else { return bounds; } } gfx::Rect NativeWindowMac::WindowBoundsToContentBounds( const gfx::Rect& bounds) const { if (has_frame()) { gfx::Rect content_bounds( [window_ contentRectForFrameRect:bounds.ToCGRect()]); int frame_height = bounds.height() - content_bounds.height(); content_bounds.set_y(content_bounds.y() + frame_height); return content_bounds; } else { return bounds; } } void NativeWindowMac::NotifyWindowEnterFullScreen() { NativeWindow::NotifyWindowEnterFullScreen(); // Restore the window title under fullscreen mode. if (buttons_proxy_) [window_ setTitleVisibility:NSWindowTitleVisible]; } void NativeWindowMac::NotifyWindowLeaveFullScreen() { NativeWindow::NotifyWindowLeaveFullScreen(); // Restore window buttons. if (buttons_proxy_ && window_button_visibility_.value_or(true)) { [buttons_proxy_ redraw]; [buttons_proxy_ setVisible:YES]; } } void NativeWindowMac::NotifyWindowWillEnterFullScreen() { UpdateVibrancyRadii(true); } void NativeWindowMac::NotifyWindowWillLeaveFullScreen() { if (buttons_proxy_) { // Hide window title when leaving fullscreen. [window_ setTitleVisibility:NSWindowTitleHidden]; // Hide the container otherwise traffic light buttons jump. [buttons_proxy_ setVisible:NO]; } UpdateVibrancyRadii(false); } void NativeWindowMac::SetActive(bool is_key) { is_active_ = is_key; } bool NativeWindowMac::IsActive() const { return is_active_; } void NativeWindowMac::Cleanup() { DCHECK(!IsClosed()); ui::NativeTheme::GetInstanceForNativeUi()->RemoveObserver(this); display::Screen::GetScreen()->RemoveObserver(this); } class NativeAppWindowFrameViewMac : public views::NativeFrameViewMac { public: NativeAppWindowFrameViewMac(views::Widget* frame, NativeWindowMac* window) : views::NativeFrameViewMac(frame), native_window_(window) {} NativeAppWindowFrameViewMac(const NativeAppWindowFrameViewMac&) = delete; NativeAppWindowFrameViewMac& operator=(const NativeAppWindowFrameViewMac&) = delete; ~NativeAppWindowFrameViewMac() override = default; // NonClientFrameView: int NonClientHitTest(const gfx::Point& point) override { if (!bounds().Contains(point)) return HTNOWHERE; if (GetWidget()->IsFullscreen()) return HTCLIENT; // Check for possible draggable region in the client area for the frameless // window. int contents_hit_test = native_window_->NonClientHitTest(point); if (contents_hit_test != HTNOWHERE) return contents_hit_test; return HTCLIENT; } private: // Weak. raw_ptr<NativeWindowMac> const native_window_; }; std::unique_ptr<views::NonClientFrameView> NativeWindowMac::CreateNonClientFrameView(views::Widget* widget) { return std::make_unique<NativeAppWindowFrameViewMac>(widget, this); } bool NativeWindowMac::HasStyleMask(NSUInteger flag) const { return [window_ styleMask] & flag; } void NativeWindowMac::SetStyleMask(bool on, NSUInteger flag) { // Changing the styleMask of a frameless windows causes it to change size so // we explicitly disable resizing while setting it. ScopedDisableResize disable_resize; if (on) [window_ setStyleMask:[window_ styleMask] | flag]; else [window_ setStyleMask:[window_ styleMask] & (~flag)]; // Change style mask will make the zoom button revert to default, probably // a bug of Cocoa or macOS. SetMaximizable(maximizable_); } void NativeWindowMac::SetCollectionBehavior(bool on, NSUInteger flag) { if (on) [window_ setCollectionBehavior:[window_ collectionBehavior] | flag]; else [window_ setCollectionBehavior:[window_ collectionBehavior] & (~flag)]; // Change collectionBehavior will make the zoom button revert to default, // probably a bug of Cocoa or macOS. SetMaximizable(maximizable_); } views::View* NativeWindowMac::GetContentsView() { return root_view_.get(); } bool NativeWindowMac::CanMaximize() const { return maximizable_; } void NativeWindowMac::OnNativeThemeUpdated(ui::NativeTheme* observed_theme) { content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&NativeWindow::RedrawTrafficLights, GetWeakPtr())); } void NativeWindowMac::AddContentViewLayers() { // Make sure the bottom corner is rounded for non-modal windows: // http://crbug.com/396264. if (!is_modal()) { // For normal window, we need to explicitly set layer for contentView to // make setBackgroundColor work correctly. // There is no need to do so for frameless window, and doing so would make // titleBarStyle stop working. if (has_frame()) { CALayer* background_layer = [[CALayer alloc] init]; [background_layer setAutoresizingMask:kCALayerWidthSizable | kCALayerHeightSizable]; [[window_ contentView] setLayer:background_layer]; } [[window_ contentView] setWantsLayer:YES]; } } void NativeWindowMac::InternalSetWindowButtonVisibility(bool visible) { [[window_ standardWindowButton:NSWindowCloseButton] setHidden:!visible]; [[window_ standardWindowButton:NSWindowMiniaturizeButton] setHidden:!visible]; [[window_ standardWindowButton:NSWindowZoomButton] setHidden:!visible]; } void NativeWindowMac::InternalSetParentWindow(NativeWindow* new_parent, bool attach) { if (is_modal()) return; // Do not remove/add if we are already properly attached. if (attach && new_parent && [window_ parentWindow] == new_parent->GetNativeWindow().GetNativeNSWindow()) return; // Remove current parent window. RemoveChildFromParentWindow(); // Set new parent window. if (new_parent) { new_parent->add_child_window(this); if (attach) new_parent->AttachChildren(); } NativeWindow::SetParentWindow(new_parent); } void NativeWindowMac::SetForwardMouseMessages(bool forward) { [window_ setAcceptsMouseMovedEvents:forward]; } gfx::Rect NativeWindowMac::GetWindowControlsOverlayRect() { if (titlebar_overlay_ && buttons_proxy_ && window_button_visibility_.value_or(true)) { NSRect buttons = [buttons_proxy_ getButtonsContainerBounds]; gfx::Rect overlay; overlay.set_width(GetContentSize().width() - NSWidth(buttons)); if ([buttons_proxy_ useCustomHeight]) { overlay.set_height(titlebar_overlay_height()); } else { overlay.set_height(NSHeight(buttons)); } if (!base::i18n::IsRTL()) overlay.set_x(NSMaxX(buttons)); return overlay; } return gfx::Rect(); } // static NativeWindow* NativeWindow::Create(const gin_helper::Dictionary& options, NativeWindow* parent) { return new NativeWindowMac(options, parent); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
39,630
[Bug]: fullscreenable in BrowserWindowConstructorOptions is ignored if resizable flag presents
### 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 25.6.0 ### What operating system are you using? macOS ### Operating System Version 12.3 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior Windows parameters corresponds to constructor options ### Actual Behavior It doesn't ### Testcase Gist URL https://gist.github.com/origin-yaropolk/8770735fda705a6bbc7d2132a30314dc ### Additional Information _No response_
https://github.com/electron/electron/issues/39630
https://github.com/electron/electron/pull/39620
2affecd4dd26b9f0cf2644ec115635559f920480
33e66b5cd02d2b258b956022c482024c74c13b4b
2023-08-23T17:00:10Z
c++
2023-08-24T20:54:08Z
spec/api-browser-window-spec.ts
import { expect } from 'chai'; import * as childProcess from 'node:child_process'; import * as path from 'node:path'; import * as fs from 'node:fs'; import * as qs from 'node:querystring'; import * as http from 'node:http'; import * as os from 'node:os'; import { AddressInfo } from 'node:net'; import { app, BrowserWindow, BrowserView, dialog, ipcMain, OnBeforeSendHeadersListenerDetails, protocol, screen, webContents, webFrameMain, session, WebContents, WebFrameMain } from 'electron/main'; import { emittedUntil, emittedNTimes } from './lib/events-helpers'; import { ifit, ifdescribe, defer, listen } from './lib/spec-helpers'; import { closeWindow, closeAllWindows } from './lib/window-helpers'; import { areColorsSimilar, captureScreen, HexColors, getPixelColor } from './lib/screen-helpers'; import { once } from 'node:events'; import { setTimeout } from 'node:timers/promises'; const fixtures = path.resolve(__dirname, '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', () => { it('sets the correct class name on the prototype', () => { expect(BrowserWindow.prototype.constructor.name).to.equal('BrowserWindow'); }); 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(fixtures, 'apps', 'xwindow-icon'); const appProcess = childProcess.spawn(process.execPath, [appPath]); await once(appProcess, 'exit'); }); 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. const wr = new WeakRef(w); await setTimeout(); // 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 setTimeout(); expect(wr.deref()).to.not.be.undefined(); }); }); describe('BrowserWindow.close()', () => { let w: 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 = once(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 = once(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 allow access to id after destruction', async () => { const closed = once(w, 'closed'); w.destroy(); await closed; expect(w.id).to.be.a('number'); }); it('should emit unload handler', async () => { await w.loadFile(path.join(fixtures, 'api', 'unload.html')); const closed = once(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 once(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 = once(w, 'closed'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' }); w.close(); await closed; }); describe('when invoked synchronously inside navigation observer', () => { let server: http.Server; let url: string; before(async () => { 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}`); } }); url = (await listen(server)).url; }); 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 = once(w.webContents, 'destroyed'); w.webContents.loadURL(url + path); await destroyed; }); } }); }); describe('window.close()', () => { let w: 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 once(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 once(w.webContents, 'before-unload-fired'); }); }); describe('BrowserWindow.destroy()', () => { let w: 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: 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: http.Server; let url: string; let postData = null as any; before(async () => { 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(req.url && req.url.includes('slow') ? 200 : 0).then(respond); }); url = (await listen(server)).url; }); after(() => { server.close(); }); it('should emit did-start-loading event', async () => { const didStartLoading = once(w.webContents, 'did-start-loading'); w.loadURL('about:blank'); await didStartLoading; }); it('should emit ready-to-show event', async () => { const readyToShow = once(w, 'ready-to-show'); w.loadURL('about:blank'); await readyToShow; }); // DISABLED-FIXME(deepak1556): The error code now seems to be `ERR_FAILED`, verify what // changed and adjust the test. it('should emit did-fail-load event for files that do not exist', async () => { const didFailLoad = once(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 = once(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 not emit did-fail-load for a successfully loaded media file', async () => { w.webContents.on('did-fail-load', () => { expect.fail('did-fail-load should not emit on media file loads'); }); const mediaStarted = once(w.webContents, 'media-started-playing'); w.loadFile(path.join(fixtures, 'cat-spin.mp4')); await mediaStarted; }); it('should set `mainFrame = false` on did-fail-load events in iframes', async () => { const didFailLoad = once(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 = once(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: 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: http.Server; let url: string; before(async () => { server = http.createServer((req, res) => { if (req.url === '/navigate-top') { res.end('<a target=_top href="/">navigate _top</a>'); } else { res.end(''); } }); url = (await listen(server)).url; }); after(() => { server.close(); }); it('allows the window to be closed from the event listener', async () => { const event = once(w.webContents, 'will-navigate'); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); await event; w.close(); }); 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 () => { w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-top"></iframe>`); await emittedUntil(w.webContents, 'did-frame-finish-load', (e: any, isMainFrame: boolean) => !isMainFrame); let initiator: WebFrameMain | undefined; w.webContents.on('will-navigate', (e) => { initiator = e.initiator; }); const subframe = w.webContents.mainFrame.frames[0]; subframe.executeJavaScript('document.getElementsByTagName("a")[0].click()', true); await once(w.webContents, 'did-navigate'); expect(initiator).not.to.be.undefined(); expect(initiator).to.equal(subframe); }); }); describe('will-frame-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 if (req.url === '/navigate-iframe') { res.end('<a href="/test">navigate iframe</a>'); } else if (req.url === '/navigate-iframe?navigated') { res.end('Successfully navigated'); } else if (req.url === '/navigate-iframe-immediately') { res.end(` <script type="text/javascript" charset="utf-8"> location.href += '?navigated' </script> `); } else if (req.url === '/navigate-iframe-immediately?navigated') { res.end('Successfully navigated'); } 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-frame-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-frame-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('can be prevented when navigating subframe', (done) => { let willNavigate = false; w.webContents.on('did-frame-navigate', (_event, _url, _httpResponseCode, _httpStatusText, isMainFrame, frameProcessId, frameRoutingId) => { if (isMainFrame) return; w.webContents.once('will-frame-navigate', (e) => { willNavigate = true; e.preventDefault(); }); w.webContents.on('did-stop-loading', () => { const frame = webFrameMain.fromId(frameProcessId, frameRoutingId); expect(frame).to.not.be.undefined(); if (willNavigate) { // i.e. it shouldn't have had '?navigated' appended to it. try { expect(frame!.url.endsWith('/navigate-iframe-immediately')).to.be.true(); done(); } catch (e) { done(e); } } }); }); w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-iframe-immediately"></iframe>`); }); 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-frame-navigate', (e) => { e.preventDefault(); resolve(e.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-frame-navigate', (e) => { e.preventDefault(); resolve(e.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 setTimeout(1000); let willFrameNavigateEmitted = false; let isMainFrameValue; w.webContents.on('will-frame-navigate', (event) => { willFrameNavigateEmitted = true; isMainFrameValue = event.isMainFrame; }); const didNavigatePromise = once(w.webContents, 'did-navigate'); 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); await didNavigatePromise; expect(willFrameNavigateEmitted).to.be.true(); expect(isMainFrameValue).to.be.true(); }); it('is triggered when a cross-origin iframe navigates itself', async () => { await w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-iframe"></iframe>`); await setTimeout(1000); let willNavigateEmitted = false; let isMainFrameValue; w.webContents.on('will-frame-navigate', (event) => { willNavigateEmitted = true; isMainFrameValue = event.isMainFrame; }); const didNavigatePromise = once(w.webContents, 'did-frame-navigate'); 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); await didNavigatePromise; expect(willNavigateEmitted).to.be.true(); expect(isMainFrameValue).to.be.false(); }); it('can cancel when a cross-origin iframe navigates itself', async () => { }); }); describe('will-redirect event', () => { let server: http.Server; let url: string; before(async () => { 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(); } }); url = (await listen(server)).url; }); after(() => { server.close(); }); it('is emitted on redirects', async () => { const willRedirect = once(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 = once(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 = once(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', async () => { const event = once(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await event; w.close(); }); 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('ordering', () => { let server = null as unknown as http.Server; let url = null as unknown as string; const navigationEvents = [ 'did-start-navigation', 'did-navigate-in-page', 'will-frame-navigate', 'will-navigate', 'will-redirect', 'did-redirect-navigation', 'did-frame-navigate', 'did-navigate' ]; before((done) => { server = http.createServer((req, res) => { if (req.url === '/navigate') { res.end('<a href="/">navigate</a>'); } else if (req.url === '/redirect') { res.end('<a href="/redirect2">redirect</a>'); } else if (req.url === '/redirect2') { res.statusCode = 302; res.setHeader('location', url); res.end(); } else if (req.url === '/in-page') { res.end('<a href="#in-page">redirect</a><div id="in-page"></div>'); } else { res.end(''); } }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/`; done(); }); }); it('for initial navigation, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'did-frame-navigate', 'did-navigate' ]; const allEvents = Promise.all(navigationEvents.map(event => once(w.webContents, event).then(() => firedEvents.push(event)) )); const timeout = setTimeout(1000); w.loadURL(url); await Promise.race([allEvents, timeout]); expect(firedEvents).to.deep.equal(expectedEventOrder); }); it('for second navigation, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'will-frame-navigate', 'will-navigate', 'did-frame-navigate', 'did-navigate' ]; w.loadURL(`${url}navigate`); await once(w.webContents, 'did-navigate'); await setTimeout(2000); Promise.all(navigationEvents.map(event => once(w.webContents, event).then(() => firedEvents.push(event)) )); const navigationFinished = once(w.webContents, 'did-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: pageTarget.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); await navigationFinished; expect(firedEvents).to.deep.equal(expectedEventOrder); }); it('when navigating with redirection, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'will-frame-navigate', 'will-navigate', 'will-redirect', 'did-redirect-navigation', 'did-frame-navigate', 'did-navigate' ]; w.loadURL(`${url}redirect`); await once(w.webContents, 'did-navigate'); await setTimeout(2000); Promise.all(navigationEvents.map(event => once(w.webContents, event).then(() => firedEvents.push(event)) )); const navigationFinished = once(w.webContents, 'did-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: pageTarget.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); await navigationFinished; expect(firedEvents).to.deep.equal(expectedEventOrder); }); it('when navigating in-page, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'did-navigate-in-page' ]; w.loadURL(`${url}in-page`); await once(w.webContents, 'did-navigate'); await setTimeout(2000); Promise.all(navigationEvents.map(event => once(w.webContents, event).then(() => firedEvents.push(event)) )); const navigationFinished = once(w.webContents, 'did-navigate-in-page'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: pageTarget.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); await navigationFinished; expect(firedEvents).to.deep.equal(expectedEventOrder); }); }); }); } describe('focus and visibility', () => { let w: 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', async () => { const p = once(w, 'focus'); w.show(); await p; expect(w.isFocused()).to.equal(true); }); it('should make the window visible', async () => { const p = once(w, 'focus'); w.show(); await p; expect(w.isVisible()).to.equal(true); }); it('emits when window is shown', async () => { const show = once(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 = once(w, 'show'); w.show(); await shown; const hidden = once(w, 'hide'); w.hide(); await hidden; expect(w.isVisible()).to.equal(false); }); }); describe('BrowserWindow.minimize()', () => { // TODO(codebytere): Enable for Linux once maximize/minimize events work in CI. ifit(process.platform !== 'linux')('should not be visible when the window is minimized', async () => { const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMinimized()).to.equal(true); 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 = once(w, 'maximize'); const shown = once(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 setTimeout(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); }); ifit(process.platform !== 'win32')('focuses a blurred window', async () => { { const isBlurred = once(w, 'blur'); const isShown = once(w, 'show'); w.show(); w.blur(); await isShown; await isBlurred; } expect(w.isFocused()).to.equal(false); w.focus(); expect(w.isFocused()).to.equal(true); }); ifit(process.platform !== 'linux')('acquires focus status from the other windows', async () => { const w1 = new BrowserWindow({ show: false }); const w2 = new BrowserWindow({ show: false }); const w3 = new BrowserWindow({ show: false }); { const isFocused3 = once(w3, 'focus'); const isShown1 = once(w1, 'show'); const isShown2 = once(w2, 'show'); const isShown3 = once(w3, 'show'); w1.show(); w2.show(); w3.show(); await isShown1; await isShown2; await isShown3; await isFocused3; } // TODO(RaisinTen): Investigate why this assertion fails only on Linux. expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); w1.focus(); expect(w1.isFocused()).to.equal(true); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(false); w2.focus(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(true); expect(w3.isFocused()).to.equal(false); w3.focus(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); { const isClosed1 = once(w1, 'closed'); const isClosed2 = once(w2, 'closed'); const isClosed3 = once(w3, 'closed'); w1.destroy(); w2.destroy(); w3.destroy(); await isClosed1; await isClosed2; await isClosed3; } }); }); // TODO(RaisinTen): Make this work on Windows too. // Refs: https://github.com/electron/electron/issues/20464. ifdescribe(process.platform !== 'win32')('BrowserWindow.blur()', () => { it('removes focus from window', async () => { { const isFocused = once(w, 'focus'); const isShown = once(w, 'show'); w.show(); await isShown; await isFocused; } expect(w.isFocused()).to.equal(true); w.blur(); expect(w.isFocused()).to.equal(false); }); ifit(process.platform !== 'linux')('transfers focus status to the next window', async () => { const w1 = new BrowserWindow({ show: false }); const w2 = new BrowserWindow({ show: false }); const w3 = new BrowserWindow({ show: false }); { const isFocused3 = once(w3, 'focus'); const isShown1 = once(w1, 'show'); const isShown2 = once(w2, 'show'); const isShown3 = once(w3, 'show'); w1.show(); w2.show(); w3.show(); await isShown1; await isShown2; await isShown3; await isFocused3; } // TODO(RaisinTen): Investigate why this assertion fails only on Linux. expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); w3.blur(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(true); expect(w3.isFocused()).to.equal(false); w2.blur(); expect(w1.isFocused()).to.equal(true); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(false); w1.blur(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); { const isClosed1 = once(w1, 'closed'); const isClosed2 = once(w2, 'closed'); const isClosed3 = once(w3, 'closed'); w1.destroy(); w2.destroy(); w3.destroy(); await isClosed1; await isClosed2; await isClosed3; } }); }); describe('BrowserWindow.getFocusedWindow()', () => { it('returns the opener window when dev tools window is focused', async () => { const p = once(w, 'focus'); w.show(); await p; w.webContents.openDevTools({ mode: 'undocked' }); await once(w.webContents, 'devtools-focused'); expect(BrowserWindow.getFocusedWindow()).to.equal(w); }); }); describe('BrowserWindow.moveTop()', () => { afterEach(closeAllWindows); it('should not steal focus', async () => { const posDelta = 50; const wShownInactive = once(w, 'show'); w.showInactive(); await wShownInactive; expect(w.isFocused()).to.equal(false); const otherWindow = new BrowserWindow({ show: false, title: 'otherWindow' }); const otherWindowShown = once(otherWindow, 'show'); const otherWindowFocused = once(otherWindow, 'focus'); otherWindow.show(); await otherWindowShown; await otherWindowFocused; expect(otherWindow.isFocused()).to.equal(true); w.moveTop(); const wPos = w.getPosition(); const wMoving = once(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 = once(w, 'focus'); const otherWindowBlurred = once(otherWindow, 'blur'); w.focus(); await wFocused; await otherWindowBlurred; expect(w.isFocused()).to.equal(true); otherWindow.moveTop(); const otherWindowPos = otherWindow.getPosition(); const otherWindowMoving = once(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); }); it('should not crash when called on a modal child window', async () => { const shown = once(w, 'show'); w.show(); await shown; const child = new BrowserWindow({ modal: true, parent: w }); expect(() => { child.moveTop(); }).to.not.throw(); }); }); describe('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 = once(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 = once(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: 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 = { ...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(once(w, 'resized')).to.eventually.be.fulfilled(); }); }); }); describe('BrowserWindow.setSize(width, height)', () => { it('sets the window size', async () => { const size = [300, 400]; const resized = once(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(once(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 = once(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 = once(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 = once(w, 'resize'); w.setContentBounds(bounds); await resize; await setTimeout(); 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 = once(w, 'resize'); w.setContentBounds(bounds); await resize; await setTimeout(); 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); }); it('returns correct color with multiple passed formats', () => { w.destroy(); w = new BrowserWindow({}); w.setBackgroundColor('#AABBFF'); expect(w.getBackgroundColor()).to.equal('#AABBFF'); w.setBackgroundColor('blueviolet'); expect(w.getBackgroundColor()).to.equal('#8A2BE2'); w.setBackgroundColor('rgb(255, 0, 185)'); expect(w.getBackgroundColor()).to.equal('#FF00B9'); w.setBackgroundColor('rgba(245, 40, 145, 0.8)'); expect(w.getBackgroundColor()).to.equal('#F52891'); w.setBackgroundColor('hsl(155, 100%, 50%)'); expect(w.getBackgroundColor()).to.equal('#00FF95'); }); }); describe('BrowserWindow.getNormalBounds()', () => { describe('Normal state', () => { it('checks normal bounds after resize', async () => { const size = [300, 400]; const resize = once(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 = once(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 = once(w, 'maximize'); w.show(); w.maximize(); await maximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after resize and maximize', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('updates normal bounds after move and maximize', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('checks normal bounds when unmaximized', async () => { const bounds = w.getBounds(); w.once('maximize', () => { w.unmaximize(); }); const unmaximize = once(w, 'unmaximize'); w.show(); w.maximize(); await unmaximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('correctly reports maximized state after maximizing then minimizing', async () => { w.destroy(); w = new BrowserWindow({ show: false }); w.show(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMaximized()).to.equal(false); expect(w.isMinimized()).to.equal(true); }); it('correctly reports maximized state after maximizing then fullscreening', async () => { w.destroy(); w = new BrowserWindow({ show: false }); w.show(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; expect(w.isMaximized()).to.equal(false); expect(w.isFullScreen()).to.equal(true); }); it('checks normal bounds for maximized transparent window', async () => { w.destroy(); w = new BrowserWindow({ transparent: true, show: false }); w.show(); const bounds = w.getNormalBounds(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; 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 = once(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 = once(w, 'maximize'); w.show(); w.maximize(); await maximize; expect(w.isMaximized()).to.equal(true); const unmaximize = once(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 = once(w, 'maximize'); 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 = once(w, 'minimize'); w.show(); w.minimize(); await minimize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after move and minimize', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const minimize = once(w, 'minimize'); w.minimize(); await minimize; const normal = w.getNormalBounds(); expect(original).to.deep.equal(normal); expectBoundsEqual(normal, w.getBounds()); }); it('updates normal bounds after resize and minimize', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const minimize = once(w, 'minimize'); w.minimize(); await minimize; const normal = w.getNormalBounds(); expect(original).to.deep.equal(normal); expectBoundsEqual(normal, w.getBounds()); }); it('checks normal bounds when restored', async () => { const bounds = w.getBounds(); w.once('minimize', () => { w.restore(); }); const restore = once(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 = once(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('does not go fullscreen if roundedCorners are enabled', async () => { w = new BrowserWindow({ frame: false, roundedCorners: false, fullscreen: true }); expect(w.fullScreen).to.be.false(); }); 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 = once(w, 'enter-full-screen'); w.show(); w.fullScreen = true; await enterFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after resize and fullscreen', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.fullScreen = true; await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('updates normal bounds after move and fullscreen', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.fullScreen = true; await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('checks normal bounds when unfullscreen\'ed', async () => { const bounds = w.getBounds(); w.once('enter-full-screen', () => { w.fullScreen = false; }); const leaveFullScreen = once(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 = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after resize and fullscreen', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.setFullScreen(true); await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('updates normal bounds after move and fullscreen', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.setFullScreen(true); await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('checks normal bounds when unfullscreen\'ed', async () => { const bounds = w.getBounds(); w.show(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); }); }); }); ifdescribe(process.platform === 'darwin')('tabbed windows', () => { let w: 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.showAllTabs()', () => { it('does not throw', () => { expect(() => { w.showAllTabs(); }).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); }); ifit(process.platform === 'darwin')('honors the stayHidden argument', async () => { const w = new BrowserWindow({ webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.hide(); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } await w.capturePage({ x: 0, y: 0, width: 0, height: 0 }, { stayHidden: true }); const visible = await w.webContents.executeJavaScript('document.visibilityState'); expect(visible).to.equal('hidden'); }); it('resolves after the window is hidden', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixtures, 'pages', 'a.html')); await once(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('resolves after the window is hidden and capturer count is non-zero', async () => { const w = new BrowserWindow({ show: false }); w.webContents.setBackgroundThrottling(false); w.loadFile(path.join(fixtures, 'pages', 'a.html')); await once(w, 'ready-to-show'); const image = await w.capturePage(); expect(image.isEmpty()).to.equal(false); }); it('preserves transparency', async () => { const w = new BrowserWindow({ show: false, transparent: true }); w.loadFile(path.join(fixtures, 'pages', 'theme-color.html')); await once(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: 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: 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', async () => { expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); const minimized = once(w, 'minimize'); w.minimize(); await minimized; expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); const restored = once(w, 'restore'); w.restore(); await restored; 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 = once(w, 'always-on-top-changed') as Promise<[any, boolean]>; 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: BrowserWindow; let server: http.Server; let url: 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++; }); url = (await listen(server)).url; }); 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 = once(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: 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); }); it('correctly updates when entering/exiting fullscreen for hidden style', async () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hidden' }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; const leaveFS = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFS; w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); it('correctly updates when entering/exiting fullscreen for hiddenInset style', async () => { 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); const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; const leaveFS = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFS; w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setVibrancy(type)', () => { afterEach(closeAllWindows); it('allows setting, changing, and removing the vibrancy', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setVibrancy('titlebar'); w.setVibrancy('selection'); w.setVibrancy(null); w.setVibrancy('menu'); 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(); }); }); ifdescribe(process.platform === 'darwin')('trafficLightPosition', () => { const pos = { x: 10, y: 10 }; afterEach(closeAllWindows); describe('BrowserWindow.getWindowButtonPosition(pos)', () => { it('returns null when there is no custom position', () => { const w = new BrowserWindow({ show: false }); expect(w.getWindowButtonPosition()).to.be.null('getWindowButtonPosition'); }); it('gets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); expect(w.getWindowButtonPosition()).to.deep.equal(pos); }); it('gets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); expect(w.getWindowButtonPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setWindowButtonPosition(pos)', () => { it('resets the position when null is passed', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); w.setWindowButtonPosition(null); expect(w.getWindowButtonPosition()).to.be.null('setWindowButtonPosition'); }); it('sets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setWindowButtonPosition(newPos); expect(w.getWindowButtonPosition()).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.setWindowButtonPosition(newPos); expect(w.getWindowButtonPosition()).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('Opening a BrowserWindow from a link', () => { let appProcess: childProcess.ChildProcessWithoutNullStreams | undefined; afterEach(() => { if (appProcess && !appProcess.killed) { appProcess.kill(); appProcess = undefined; } }); it('can properly open and load a new window from a link', async () => { const appPath = path.join(__dirname, 'fixtures', 'apps', 'open-new-window-from-link'); appProcess = childProcess.spawn(process.execPath, [appPath]); const [code] = await once(appProcess, 'exit'); expect(code).to.equal(0); }); }); 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 typeof ElectronInternal.WebContents).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.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 = once(w.webContents, 'did-attach-webview'); const [, webviewContents] = await once(app, 'web-contents-created') as [any, WebContents]; expect(BrowserWindow.fromWebContents(webviewContents)!.id).to.equal(w.id); await p; }); it('is usable immediately on browser-window-created', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.executeJavaScript('window.open(""); null'); const [win, winFromWebContents] = await new Promise<any>((resolve) => { app.once('browser-window-created', (e, win) => { resolve([win, BrowserWindow.fromWebContents(win.webContents)]); }); }); expect(winFromWebContents).to.equal(win); }); }); 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.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.destroy(); bv2.webContents.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.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(['win32', 'darwin'].includes(process.platform))('"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 = once(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 = once(ipcMain, 'geometrychange'); w.setBounds({ width: 800 }); const [, newOverlayRect] = await geometryChange; expect(newOverlayRect.width).to.equal(overlayRect.width + 400); }; afterEach(async () => { await closeAllWindows(); 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')('when an invalid titleBarStyle is initially set', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { color: '#0000f0', symbolColor: '#ffffff' }, titleBarStyle: 'hiddenInset' }); }); afterEach(async () => { await closeAllWindows(); }); it('does not crash changing minimizability ', () => { expect(() => { w.setMinimizable(false); }).to.not.throw(); }); it('does not crash changing maximizability', () => { expect(() => { w.setMaximizable(false); }).to.not.throw(); }); }); }); ifdescribe(['win32', 'darwin'].includes(process.platform))('"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 = once(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()'); if (!w.isMaximized()) { const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; } expect(w.isMaximized()).to.be.true('not maximized'); 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(async () => { await closeAllWindows(); ipcMain.removeAllListeners('geometrychange'); }); it('sets Window Control Overlay with title bar height of 40', async () => { await testWindowsOverlayHeight(40); }); }); ifdescribe(process.platform === 'win32')('BrowserWindow.setTitlebarOverlay', () => { afterEach(async () => { await closeAllWindows(); ipcMain.removeAllListeners('geometrychange'); }); it('does not crash when an invalid titleBarStyle was initially set', () => { const win = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { color: '#0000f0', symbolColor: '#ffffff' }, titleBarStyle: 'hiddenInset' }); expect(() => { win.setTitleBarOverlay({ color: '#000000' }); }).to.not.throw(); }); it('correctly updates the height of the overlay', async () => { const testOverlay = async (w: BrowserWindow, size: Number, firstRun: boolean) => { const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); const overlayReady = once(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); if (firstRun) { await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const { height: preMaxHeight } = await w.webContents.executeJavaScript('getJSOverlayProperties()'); if (!w.isMaximized()) { const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; } expect(w.isMaximized()).to.be.true('not maximized'); const { x, y, width, height } = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(x).to.equal(0); expect(y).to.equal(0); expect(width).to.be.greaterThan(0); expect(height).to.equal(size); expect(preMaxHeight).to.equal(size); }; const INITIAL_SIZE = 40; const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden', webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { height: INITIAL_SIZE } }); await testOverlay(w, INITIAL_SIZE, true); w.setTitleBarOverlay({ height: INITIAL_SIZE + 10 }); await testOverlay(w, INITIAL_SIZE + 10, false); }); }); 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-next-line no-new */ new BrowserWindow({ tabbingIdentifier: 'group1' }); /* eslint-disable-next-line no-new */ new BrowserWindow({ tabbingIdentifier: 'group2', frame: false }); }).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 once(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 once(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 once(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-isolated 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 once(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 once(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 once(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 once(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 once(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 once(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; let serverUrl: string; before(async () => { 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}`); } }); serverUrl = (await listen(server)).url; }); 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 once(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 once(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 once(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 once(ipcMain, 'answer'); const expectedUrl = process.platform === 'win32' ? 'file:///' + htmlPath.replace(/\\/g, '/') : pageUrl; expect(url).to.equal(expectedUrl); }); it('exposes full EventEmitter object to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload: path.join(fixtures, 'module', 'preload-eventemitter.js') } }); w.loadURL('about:blank'); const [, rendererEventEmitterProperties] = await once(ipcMain, 'answer'); const { EventEmitter } = require('node:events'); const emitter = new EventEmitter(); const browserEventEmitterProperties = []; let currentObj = emitter; do { browserEventEmitterProperties.push(...Object.getOwnPropertyNames(currentObj)); } while ((currentObj = Object.getPrototypeOf(currentObj))); expect(rendererEventEmitterProperties).to.deep.equal(browserEventEmitterProperties); }); 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 = once(ipcMain, 'answer'); w.loadURL(pageUrl); const [, { url, frameName, options }] = await once(w.webContents, 'did-create-window') as [BrowserWindow, Electron.DidCreateWindowDetails]; 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 once(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 once(app, 'browser-window-created') as [any, BrowserWindow]; // Ask the popup window for details. const detailsAnswer = once(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 = once(ipcMain, 'answer'); w.webContents.send('touch-the-popup'); const [, popupAccessMessage] = await touchPopupResult; // Ask the popup to access the opener. const touchOpenerResult = once(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 once(ipcMain, 'answer'); expect(argv).to.include('--enable-sandbox'); }); it('should open windows with the options configured via setWindowOpenHandler handlers', 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([ once(app, 'web-contents-created') as Promise<[any, WebContents]>, once(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 => once(ipcMain, name))); w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'verify-ipc-sender' }); await done; }); describe('event handling', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); }); it('works for window events', async () => { const pageTitleUpdated = once(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 => once(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 => once(w.webContents, name))); w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'webcontents-events' }); await done; }); }); 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 once(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'); expect(test.nodeEvents).to.equal(true); expect(test.nodeTimers).to.equal(true); expect(test.nodeUrl).to.equal(true); 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 = once(w.webContents, 'did-attach-webview') as Promise<[any, WebContents]>; const webviewDomReady = once(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; 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 = once(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 = once(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 = once(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 = once(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 once(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 once(ipcMain, 'answer'); expect(content).to.equal('function'); } w.reload(); { const [, content] = await once(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, preload } } })); const webviewLoaded = once(ipcMain, 'webview-loaded'); w.loadFile(path.join(fixtures, 'api', 'new-window-webview.html')); await webviewLoaded; }); it('should open windows with the options configured via setWindowOpenHandler handlers', 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([ once(app, 'web-contents-created') as Promise<[any, WebContents]>, once(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 once(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 once(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 = once(w.webContents, 'enter-html-full-screen'); w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true); await enterHtmlFullScreen; expect(w.getSize()).to.deep.equal(size); }); }); describe('"defaultFontFamily" option', () => { it('can change the standard font family', async () => { const w = new BrowserWindow({ show: false, webPreferences: { defaultFontFamily: { standard: 'Impact' } } }); await w.loadFile(path.join(fixtures, 'pages', 'content.html')); const fontFamily = await w.webContents.executeJavaScript("window.getComputedStyle(document.getElementsByTagName('p')[0])['font-family']", true); expect(fontFamily).to.equal('Impact'); }); }); }); describe('beforeunload handler', function () { let w: 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 = once(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 once(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 once(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 once(w.webContents, 'console-message'); w.close(); await once(w.webContents, 'before-unload-fired'); w.close(); await once(w.webContents, 'before-unload-fired'); w.webContents.removeListener('destroyed', destroyListener); const wait = once(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 once(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 once(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 once(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'); }); }); // TODO(codebytere): figure out how to make these pass in CI on Windows. ifdescribe(process.platform !== 'win32')('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 once(ipcMain, 'pong'); expect(readyToShow).to.be.false('ready to show'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); }); it('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 once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.hide(); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } }); it('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 once(w, 'show'); } w.hide(); w.show(); const [, visibilityState] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); }); it('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 once(w, 'show'); } w.hide(); w.showInactive(); const [, visibilityState] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); }); 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 once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.minimize(); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } }); it('visibilityState remains visible if backgroundThrottling is disabled', async () => { const w = new BrowserWindow({ show: false, width: 100, height: 100, webPreferences: { backgroundThrottling: false, nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await once(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 = once(w, 'show'); w.show(); await shown1; const hidden = once(w, 'hide'); w.hide(); await hidden; const shown2 = once(w, 'show'); w.show(); await shown2; } finally { ipcMain.removeAllListeners('pong'); } }); }); 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 = once(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 = once(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 = once(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 = once(w, 'maximize'); const unmaximize = once(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 = once(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 }); let called = false; w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); w.webContents.on('dom-ready', () => { w.webContents.beginFrameSubscription(function () { // This callback might be called twice. if (called) return; called = true; // Pending endFrameSubscription to next tick can reliably reproduce // a crash which happens when nothing is returned in the callback. setTimeout().then(() => { 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 () => { /* Use temp directory for saving MHTML file since the write handle * gets passed to untrusted process and chromium will deny exec access to * the path. To perform this task, chromium requires that the path is one * of the browser controlled paths, refs https://chromium-review.googlesource.com/c/chromium/src/+/3774416 */ const tmpDir = await fs.promises.mkdtemp(path.resolve(os.tmpdir(), 'electron-mhtml-save-')); const savePageMHTMLPath = path.join(tmpDir, 'save_page.html'); const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageMHTMLPath, 'MHTML'); expect(fs.existsSync(savePageMHTMLPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.false('js path'); expect(fs.existsSync(savePageCssPath)).to.be.false('css path'); try { await fs.promises.unlink(savePageMHTMLPath); await fs.promises.rmdir(tmpDir); } catch {} }); 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(); }); // TODO(zcbenz): // This test does not run on Linux CI. See: // https://github.com/electron/electron/issues/28699 ifit(process.platform === 'linux' && !process.env.CI)('should bring a minimized maximized window back to maximized state', async () => { const w = new BrowserWindow({}); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMaximized()).to.equal(false); const restore = once(w, 'restore'); w.restore(); await restore; expect(w.isMaximized()).to.equal(true); }); }); // TODO(dsanders11): Enable once maximize event works on Linux again on CI ifdescribe(process.platform !== 'linux')('BrowserWindow.maximize()', () => { afterEach(closeAllWindows); it('should show the window if it is not currently shown', async () => { const w = new BrowserWindow({ show: false }); const hidden = once(w, 'hide'); let shown = once(w, 'show'); const maximize = once(w, 'maximize'); expect(w.isVisible()).to.be.false('visible'); w.maximize(); await maximize; await shown; expect(w.isMaximized()).to.be.true('maximized'); expect(w.isVisible()).to.be.true('visible'); // Even if the window is already maximized w.hide(); await hidden; expect(w.isVisible()).to.be.false('visible'); shown = once(w, 'show'); w.maximize(); await shown; expect(w.isVisible()).to.be.true('visible'); }); }); 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 = once(w, 'minimize'); w.minimize(); await minimize; w.unmaximize(); await setTimeout(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 setTimeout(1000); expectBoundsEqual(w.getSize(), initialSize); expectBoundsEqual(w.getPosition(), initialPosition); }); ifit(process.platform === 'darwin')('should not change size or position of a window which is functionally maximized', async () => { const { workArea } = screen.getPrimaryDisplay(); const bounds = { x: workArea.x, y: workArea.y, width: workArea.width, height: workArea.height }; const w = new BrowserWindow(bounds); w.unmaximize(); await setTimeout(1000); expectBoundsEqual(w.getBounds(), bounds); }); }); 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 = once(w, 'show'); // start fullscreen and hidden w.setFullScreen(true); w.show(); await shown; const leftFullScreen = once(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 = once(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 once(w, 'enter-full-screen'); // Wait a tick for the full-screen state to 'stick' await setTimeout(); w.setFullScreen(false); await once(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 = once(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 = once(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 = once(c, 'closed'); c.close(); await closed; // The child window list is not immediately cleared, so wait a tick until it's ready. await setTimeout(); expect(w.getChildWindows().length).to.equal(0); }); it('can handle child window close and reparent multiple times', async () => { const w = new BrowserWindow({ show: false }); let c: BrowserWindow | null; for (let i = 0; i < 5; i++) { c = new BrowserWindow({ show: false, parent: w }); const closed = once(c, 'closed'); c.close(); await closed; } await setTimeout(); expect(w.getChildWindows().length).to.equal(0); }); ifit(process.platform === 'darwin')('child window matches visibility when visibility changes', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); const wShow = once(w, 'show'); const cShow = once(c, 'show'); w.show(); c.show(); await Promise.all([wShow, cShow]); const minimized = once(w, 'minimize'); w.minimize(); await minimized; expect(w.isVisible()).to.be.false('parent is visible'); expect(c.isVisible()).to.be.false('child is visible'); const restored = once(w, 'restore'); w.restore(); await restored; expect(w.isVisible()).to.be.true('parent is visible'); expect(c.isVisible()).to.be.true('child is visible'); }); ifit(process.platform === 'darwin')('matches child window visibility when visibility changes', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); const wShow = once(w, 'show'); const cShow = once(c, 'show'); w.show(); c.show(); await Promise.all([wShow, cShow]); const minimized = once(c, 'minimize'); c.minimize(); await minimized; expect(c.isVisible()).to.be.false('child is visible'); const restored = once(c, 'restore'); c.restore(); await restored; expect(w.isVisible()).to.be.true('parent is visible'); expect(c.isVisible()).to.be.true('child is visible'); }); it('closes a grandchild window when a middle child window is destroyed', (done) => { const w = new BrowserWindow(); w.loadFile(path.join(fixtures, 'pages', 'base-page.html')); w.webContents.executeJavaScript('window.open("")'); w.webContents.on('did-create-window', async (window) => { const childWindow = new BrowserWindow({ parent: window }); await setTimeout(); window.close(); childWindow.on('closed', () => { expect(() => { BrowserWindow.getFocusedWindow(); }).to.not.throw(); done(); }); }); }); 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 = once(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 setTimeout(); expect(w.getChildWindows().length).to.equal(0); }); ifit(process.platform === 'darwin')('can reparent when the first parent is destroyed', async () => { const w1 = new BrowserWindow({ show: false }); const w2 = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); c.setParentWindow(w1); expect(w1.getChildWindows().length).to.equal(1); const closed = once(w1, 'closed'); w1.destroy(); await closed; c.setParentWindow(w2); await setTimeout(); const children = w2.getChildWindows(); expect(children[0]).to.equal(c); }); }); 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 = once(two, 'show'); two.show(); await twoShown; setTimeout(500).then(() => two.close()); await once(two, 'closed'); }; const one = new BrowserWindow({ width: 600, height: 400, parent: parentWindow, modal: true, show: false }); const oneShown = once(one, 'show'); one.show(); await oneShown; setTimeout(500).then(() => one.destroy()); await once(one, 'closed'); await createTwo(); }); ifit(process.platform !== 'darwin')('can disable and enable a window', () => { const w = new BrowserWindow({ show: false }); w.setEnabled(false); expect(w.isEnabled()).to.be.false('w.isEnabled()'); w.setEnabled(true); expect(w.isEnabled()).to.be.true('!w.isEnabled()'); }); 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 = once(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 = once(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; let serverUrl: string; before(async () => { server = http.createServer((request, response) => { response.end(); }); serverUrl = (await listen(server)).url; }); after(() => { server.close(); }); it('is true when the main frame is loading', async () => { const w = new BrowserWindow({ show: false }); const didStartLoading = once(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 = once(w.webContents, 'did-stop-loading'); w.webContents.loadURL(serverUrl); await didStopLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); const didStartLoading = once(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 = once(w.webContents, 'did-stop-loading'); w.webContents.loadURL(serverUrl); await didStopLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); const didStartLoading = once(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')('when fullscreen state is changed', () => { it('correctly remembers state prior to fullscreen change', async () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); w.setMenuBarVisibility(false); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; expect(w.fullScreen).to.be.true('not fullscreen'); const exitFS = once(w, 'leave-full-screen'); w.setFullScreen(false); await exitFS; expect(w.fullScreen).to.be.false('not fullscreen'); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); }); it('correctly remembers state prior to fullscreen change with autoHide', async () => { const w = new BrowserWindow({ show: false }); expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); w.autoHideMenuBar = true; expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); w.setMenuBarVisibility(false); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; expect(w.fullScreen).to.be.true('not fullscreen'); const exitFS = once(w, 'leave-full-screen'); w.setFullScreen(false); await exitFS; expect(w.fullScreen).to.be.false('not fullscreen'); expect(w.isMenuBarVisible()).to.be.false('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'); }); }); }); ifdescribe(process.platform === 'darwin')('isHiddenInMissionControl state', () => { it('with functions', () => { it('can be set with ignoreMissionControl constructor option', () => { const w = new BrowserWindow({ show: false, hiddenInMissionControl: true }); expect(w.isHiddenInMissionControl()).to.be.true('isHiddenInMissionControl'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isHiddenInMissionControl()).to.be.false('isHiddenInMissionControl'); w.setHiddenInMissionControl(true); expect(w.isHiddenInMissionControl()).to.be.true('isHiddenInMissionControl'); w.setHiddenInMissionControl(false); expect(w.isHiddenInMissionControl()).to.be.false('isHiddenInMissionControl'); }); }); }); // 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 = once(w, 'enter-full-screen'); w.kiosk = true; expect(w.isKiosk()).to.be.true('isKiosk'); await enterFullScreen; await setTimeout(); const leaveFullScreen = once(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 = once(w, 'enter-full-screen'); w.setKiosk(true); expect(w.isKiosk()).to.be.true('isKiosk'); await enterFullScreen; await setTimeout(); const leaveFullScreen = once(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 false and restored', async () => { const w = new BrowserWindow({ resizable: false }); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.resizable).to.be.false('resizable'); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.resizable).to.be.false('resizable'); }); it('default resizable flag should be restored after entering/exiting fullscreen', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.resizable).to.be.false('resizable'); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.resizable).to.be.true('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 = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; }); it('should be able to load a URL while transitioning to fullscreen', async () => { const w = new BrowserWindow({ fullscreen: true }); w.loadFile(path.join(fixtures, 'pages', 'c.html')); const load = once(w.webContents, 'did-finish-load'); const enterFS = once(w, 'enter-full-screen'); await Promise.all([enterFS, load]); expect(w.fullScreen).to.be.true(); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; }); it('can be changed with setFullScreen method', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await setTimeout(); const leaveFullScreen = once(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 setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); }); it('handles several HTML fullscreen transitions', async () => { const w = new BrowserWindow(); await w.loadFile(path.join(fixtures, 'pages', 'a.html')); expect(w.isFullScreen()).to.be.false('is fullscreen'); const enterFullScreen = once(w, 'enter-full-screen'); const leaveFullScreen = once(w, 'leave-full-screen'); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await enterFullScreen; await w.webContents.executeJavaScript('document.exitFullscreen()', true); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); await setTimeout(); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await enterFullScreen; await w.webContents.executeJavaScript('document.exitFullscreen()', true); 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'); const enterFS = emittedNTimes(w, 'enter-full-screen', 2); const leaveFS = emittedNTimes(w, 'leave-full-screen', 2); w.setFullScreen(true); w.setFullScreen(false); w.setFullScreen(true); w.setFullScreen(false); await Promise.all([enterFS, leaveFS]); expect(w.isFullScreen()).to.be.false('not fullscreen'); }); it('handles several chromium-initiated transitions in close proximity', async () => { const w = new BrowserWindow(); await w.loadFile(path.join(fixtures, 'pages', 'a.html')); expect(w.isFullScreen()).to.be.false('is fullscreen'); let enterCount = 0; let exitCount = 0; const done = new Promise<void>(resolve => { const checkDone = () => { if (enterCount === 2 && exitCount === 2) resolve(); }; w.webContents.on('enter-html-full-screen', () => { enterCount++; checkDone(); }); w.webContents.on('leave-html-full-screen', () => { exitCount++; checkDone(); }); }); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await done; }); it('handles HTML fullscreen transitions when fullscreenable is false', async () => { const w = new BrowserWindow({ fullscreenable: false }); await w.loadFile(path.join(fixtures, 'pages', 'a.html')); expect(w.isFullScreen()).to.be.false('is fullscreen'); let enterCount = 0; let exitCount = 0; const done = new Promise<void>((resolve, reject) => { const checkDone = () => { if (enterCount === 2 && exitCount === 2) resolve(); }; w.webContents.on('enter-html-full-screen', async () => { enterCount++; if (w.isFullScreen()) reject(new Error('w.isFullScreen should be false')); const isFS = await w.webContents.executeJavaScript('!!document.fullscreenElement'); if (!isFS) reject(new Error('Document should have fullscreen element')); checkDone(); }); w.webContents.on('leave-html-full-screen', () => { exitCount++; if (w.isFullScreen()) reject(new Error('w.isFullScreen should be false')); checkDone(); }); }); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await expect(done).to.eventually.be.fulfilled(); }); it('does not crash when exiting simpleFullScreen (properties)', async () => { const w = new BrowserWindow(); w.setSimpleFullScreen(true); await setTimeout(1000); w.setFullScreen(!w.isFullScreen()); }); it('does not crash when exiting simpleFullScreen (functions)', async () => { const w = new BrowserWindow(); w.simpleFullScreen = true; await setTimeout(1000); w.setFullScreen(!w.isFullScreen()); }); it('should not be changed by setKiosk method', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setKiosk(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); const leaveFullScreen = once(w, 'leave-full-screen'); w.setKiosk(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('isFullScreen'); }); it('should stay fullscreen if fullscreen before kiosk', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); w.setKiosk(true); w.setKiosk(false); // Wait enough time for a fullscreen change to take effect. await setTimeout(2000); expect(w.isFullScreen()).to.be.true('isFullScreen'); }); it('multiple windows inherit correct fullscreen state', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await setTimeout(1000); const w2 = new BrowserWindow({ show: false }); const enterFullScreen2 = once(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 = once(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(); }); it('should not call BrowserWindow show event', async () => { const w = new BrowserWindow({ show: false }); const shown = once(w, 'show'); w.show(); await shown; let showCalled = false; w.on('show', () => { showCalled = true; }); w.previewFile(__filename); await setTimeout(500); expect(showCalled).to.equal(false, 'should not have called show twice'); }); }); // TODO (jkleinsc) renable these tests on mas arm64 ifdescribe(!process.mas || process.arch !== 'arm64')('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 = once(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 = once(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 = once(app, 'browser-window-created') as Promise<[any, BrowserWindow]>; 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 = once(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 = once(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 = once(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 = once(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 = once(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 = once(w1, 'focus'); w1.webContents.focus(); await w1Focused; expect(w1.webContents.isFocused()).to.be.true('focuses window'); }); }); describe('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 = once(w.webContents, 'paint') as Promise<[any, Electron.Rectangle, Electron.NativeImage]>; 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 = once(w.webContents, 'paint') as Promise<[any, Electron.Rectangle, Electron.NativeImage]>; 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 = once(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 = once(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.stopPainting(); w.webContents.startPainting(); await once(w.webContents, 'paint') as [any, Electron.Rectangle, Electron.NativeImage]; 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 once(w.webContents, 'paint') as [any, Electron.Rectangle, Electron.NativeImage]; expect(w.webContents.getFrameRate()).to.equal(60); }); it('has default frame rate (property)', async () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await once(w.webContents, 'paint') as [any, Electron.Rectangle, Electron.NativeImage]; expect(w.webContents.frameRate).to.equal(60); }); it('sets custom frame rate (function)', async () => { const domReady = once(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.setFrameRate(30); await once(w.webContents, 'paint') as [any, Electron.Rectangle, Electron.NativeImage]; expect(w.webContents.getFrameRate()).to.equal(30); }); it('sets custom frame rate (property)', async () => { const domReady = once(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.frameRate = 30; await once(w.webContents, 'paint') as [any, Electron.Rectangle, Electron.NativeImage]; expect(w.webContents.frameRate).to.equal(30); }); }); }); describe('"transparent" option', () => { afterEach(closeAllWindows); ifit(process.platform !== 'linux')('correctly returns isMaximized() when the window is maximized then minimized', async () => { const w = new BrowserWindow({ frame: false, transparent: true }); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMaximized()).to.be.false(); expect(w.isMinimized()).to.be.true(); }); // 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 once(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 === 'darwin' && process.arch === 'x64')('should not display a visible background', async () => { const display = screen.getPrimaryDisplay(); const backgroundWindow = new BrowserWindow({ ...display.bounds, frame: false, backgroundColor: HexColors.GREEN, hasShadow: false }); await backgroundWindow.loadURL('about:blank'); const foregroundWindow = new BrowserWindow({ ...display.bounds, show: true, transparent: true, frame: false, hasShadow: false }); const colorFile = path.join(__dirname, 'fixtures', 'pages', 'half-background-color.html'); await foregroundWindow.loadFile(colorFile); await setTimeout(1000); 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, HexColors.GREEN)).to.be.true(); expect(areColorsSimilar(rightHalfColor, HexColors.RED)).to.be.true(); }); ifit(process.platform === 'darwin')('Allows setting a transparent window via CSS', async () => { const display = screen.getPrimaryDisplay(); const backgroundWindow = new BrowserWindow({ ...display.bounds, frame: false, backgroundColor: HexColors.PURPLE, hasShadow: false }); await backgroundWindow.loadURL('about:blank'); const foregroundWindow = new BrowserWindow({ ...display.bounds, frame: false, transparent: true, hasShadow: false, webPreferences: { contextIsolation: false, nodeIntegration: true } }); foregroundWindow.loadFile(path.join(__dirname, 'fixtures', 'pages', 'css-transparent.html')); await once(ipcMain, 'set-transparent'); await setTimeout(); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); expect(areColorsSimilar(centerColor, HexColors.PURPLE)).to.be.true(); }); // Linux and arm64 platforms (WOA and macOS) do not return any capture sources ifit(process.platform === 'darwin' && process.arch === 'x64')('should not make background transparent if falsy', async () => { const display = screen.getPrimaryDisplay(); for (const transparent of [false, undefined]) { const window = new BrowserWindow({ ...display.bounds, transparent }); await once(window, 'show'); await window.webContents.loadURL('data:text/html,<head><meta name="color-scheme" content="dark"></head>'); await setTimeout(500); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); window.close(); // color-scheme is set to dark so background should not be white expect(areColorsSimilar(centerColor, HexColors.WHITE)).to.be.false(); } }); }); describe('"backgroundColor" option', () => { afterEach(closeAllWindows); // Linux/WOA doesn't return any capture sources. ifit(process.platform === 'darwin')('should display the set color', async () => { const display = screen.getPrimaryDisplay(); const w = new BrowserWindow({ ...display.bounds, show: true, backgroundColor: HexColors.BLUE }); w.loadURL('about:blank'); await once(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, HexColors.BLUE)).to.be.true(); }); }); });
closed
electron/electron
https://github.com/electron/electron
39,614
[Bug]: non-fullscreenable, non-resizable child windows get fullscreened when being shown if the parent window is fullscreened
### 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 26.0.0 ### What operating system are you using? macOS ### Operating System Version macOS Ventura 13.2.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior I expect that if a child window that's configured to be non-fullscreenable is shown while the parent window is fullscreened, the child window won't get fullscreened. ### Actual Behavior Child window opens fullscreened for some reason and the main window crashes when the child is closed. ### Testcase Gist URL https://gist.github.com/pushkin-/3b4bcdb219eee85789e95f6d94ec8a92 ### Additional Information 1. full screen main window 2. click open window 3. notice that child window is fullscreened even though it shouldn't be able to get fullscreen 4. closing the window makes the parent window go black seems like the invocation of `BrowserWindow::show()` causes the `enter-full-screen` event to get emitted for some reason. https://github.com/electron/electron/assets/6374473/f96e2680-4938-4de6-b562-94f80c46ecfb
https://github.com/electron/electron/issues/39614
https://github.com/electron/electron/pull/39620
2affecd4dd26b9f0cf2644ec115635559f920480
33e66b5cd02d2b258b956022c482024c74c13b4b
2023-08-22T22:41:12Z
c++
2023-08-24T20:54:08Z
shell/browser/native_window_mac.mm
// 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_mac.h" #include <AvailabilityMacros.h> #include <objc/objc-runtime.h> #include <algorithm> #include <memory> #include <string> #include <utility> #include <vector> #include "base/mac/mac_util.h" #include "base/mac/scoped_cftyperef.h" #include "base/strings/sys_string_conversions.h" #include "components/remote_cocoa/app_shim/native_widget_ns_window_bridge.h" #include "components/remote_cocoa/browser/scoped_cg_window_id.h" #include "content/public/browser/browser_accessibility_state.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/desktop_media_id.h" #include "shell/browser/browser.h" #include "shell/browser/javascript_environment.h" #include "shell/browser/native_browser_view_mac.h" #include "shell/browser/ui/cocoa/electron_native_widget_mac.h" #include "shell/browser/ui/cocoa/electron_ns_window.h" #include "shell/browser/ui/cocoa/electron_ns_window_delegate.h" #include "shell/browser/ui/cocoa/electron_preview_item.h" #include "shell/browser/ui/cocoa/electron_touch_bar.h" #include "shell/browser/ui/cocoa/root_view_mac.h" #include "shell/browser/ui/cocoa/window_buttons_proxy.h" #include "shell/browser/ui/drag_util.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/window_list.h" #include "shell/common/gin_converters/gfx_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/node_includes.h" #include "shell/common/options_switches.h" #include "shell/common/process_util.h" #include "skia/ext/skia_utils_mac.h" #include "third_party/skia/include/core/SkRegion.h" #include "third_party/webrtc/modules/desktop_capture/mac/window_list_utils.h" #include "ui/base/hit_test.h" #include "ui/display/screen.h" #include "ui/gfx/skia_util.h" #include "ui/gl/gpu_switching_manager.h" #include "ui/views/background.h" #include "ui/views/cocoa/native_widget_mac_ns_window_host.h" #include "ui/views/widget/widget.h" #include "ui/views/window/native_frame_view_mac.h" @interface ElectronProgressBar : NSProgressIndicator @end @implementation ElectronProgressBar - (void)drawRect:(NSRect)dirtyRect { if (self.style != NSProgressIndicatorStyleBar) return; // Draw edges of rounded rect. NSRect rect = NSInsetRect([self bounds], 1.0, 1.0); CGFloat radius = rect.size.height / 2; NSBezierPath* bezier_path = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [bezier_path setLineWidth:2.0]; [[NSColor grayColor] set]; [bezier_path stroke]; // Fill the rounded rect. rect = NSInsetRect(rect, 2.0, 2.0); radius = rect.size.height / 2; bezier_path = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [bezier_path setLineWidth:1.0]; [bezier_path addClip]; // Calculate the progress width. rect.size.width = floor(rect.size.width * ([self doubleValue] / [self maxValue])); // Fill the progress bar with color blue. [[NSColor colorWithSRGBRed:0.2 green:0.6 blue:1 alpha:1] set]; NSRectFill(rect); } @end namespace gin { template <> struct Converter<electron::NativeWindowMac::VisualEffectState> { static bool FromV8(v8::Isolate* isolate, v8::Handle<v8::Value> val, electron::NativeWindowMac::VisualEffectState* out) { using VisualEffectState = electron::NativeWindowMac::VisualEffectState; std::string visual_effect_state; if (!ConvertFromV8(isolate, val, &visual_effect_state)) return false; if (visual_effect_state == "followWindow") { *out = VisualEffectState::kFollowWindow; } else if (visual_effect_state == "active") { *out = VisualEffectState::kActive; } else if (visual_effect_state == "inactive") { *out = VisualEffectState::kInactive; } else { return false; } return true; } }; } // namespace gin namespace electron { namespace { bool IsFramelessWindow(NSView* view) { NSWindow* nswindow = [view window]; if (![nswindow respondsToSelector:@selector(shell)]) return false; NativeWindow* window = [static_cast<ElectronNSWindow*>(nswindow) shell]; return window && !window->has_frame(); } IMP original_set_frame_size = nullptr; IMP original_view_did_move_to_superview = nullptr; // This method is directly called by NSWindow during a window resize on OSX // 10.10.0, beta 2. We must override it to prevent the content view from // shrinking. void SetFrameSize(NSView* self, SEL _cmd, NSSize size) { if (!IsFramelessWindow(self)) { auto original = reinterpret_cast<decltype(&SetFrameSize)>(original_set_frame_size); return original(self, _cmd, size); } // For frameless window, resize the view to cover full window. if ([self superview]) size = [[self superview] bounds].size; auto super_impl = reinterpret_cast<decltype(&SetFrameSize)>( [[self superclass] instanceMethodForSelector:_cmd]); super_impl(self, _cmd, size); } // The contentView gets moved around during certain full-screen operations. // This is less than ideal, and should eventually be removed. void ViewDidMoveToSuperview(NSView* self, SEL _cmd) { if (!IsFramelessWindow(self)) { // [BridgedContentView viewDidMoveToSuperview]; auto original = reinterpret_cast<decltype(&ViewDidMoveToSuperview)>( original_view_did_move_to_superview); if (original) original(self, _cmd); return; } [self setFrame:[[self superview] bounds]]; } // -[NSWindow orderWindow] does not handle reordering for children // windows. Their order is fixed to the attachment order (the last attached // window is on the top). Therefore, work around it by re-parenting in our // desired order. void ReorderChildWindowAbove(NSWindow* child_window, NSWindow* other_window) { NSWindow* parent = [child_window parentWindow]; DCHECK(parent); // `ordered_children` sorts children windows back to front. NSArray<NSWindow*>* children = [[child_window parentWindow] childWindows]; std::vector<std::pair<NSInteger, NSWindow*>> ordered_children; for (NSWindow* child in children) ordered_children.push_back({[child orderedIndex], child}); std::sort(ordered_children.begin(), ordered_children.end(), std::greater<>()); // If `other_window` is nullptr, place `child_window` in front of // all other children windows. if (other_window == nullptr) other_window = ordered_children.back().second; if (child_window == other_window) return; for (NSWindow* child in children) [parent removeChildWindow:child]; const bool relative_to_parent = parent == other_window; if (relative_to_parent) [parent addChildWindow:child_window ordered:NSWindowAbove]; // Re-parent children windows in the desired order. for (auto [ordered_index, child] : ordered_children) { if (child != child_window && child != other_window) { [parent addChildWindow:child ordered:NSWindowAbove]; } else if (child == other_window && !relative_to_parent) { [parent addChildWindow:other_window ordered:NSWindowAbove]; [parent addChildWindow:child_window ordered:NSWindowAbove]; } } } } // namespace NativeWindowMac::NativeWindowMac(const gin_helper::Dictionary& options, NativeWindow* parent) : NativeWindow(options, parent), root_view_(new RootViewMac(this)) { ui::NativeTheme::GetInstanceForNativeUi()->AddObserver(this); display::Screen::GetScreen()->AddObserver(this); int width = 800, height = 600; options.Get(options::kWidth, &width); options.Get(options::kHeight, &height); NSRect main_screen_rect = [[[NSScreen screens] firstObject] frame]; gfx::Rect bounds(round((NSWidth(main_screen_rect) - width) / 2), round((NSHeight(main_screen_rect) - height) / 2), width, height); bool resizable = true; options.Get(options::kResizable, &resizable); options.Get(options::kZoomToPageWidth, &zoom_to_page_width_); options.Get(options::kSimpleFullScreen, &always_simple_fullscreen_); options.GetOptional(options::kTrafficLightPosition, &traffic_light_position_); options.Get(options::kVisualEffectState, &visual_effect_state_); if (options.Has(options::kFullscreenWindowTitle)) { EmitWarning( node::Environment::GetCurrent(JavascriptEnvironment::GetIsolate()), "\"fullscreenWindowTitle\" option has been deprecated and is " "no-op now.", "electron"); } bool minimizable = true; options.Get(options::kMinimizable, &minimizable); bool maximizable = true; options.Get(options::kMaximizable, &maximizable); bool closable = true; options.Get(options::kClosable, &closable); std::string tabbingIdentifier; options.Get(options::kTabbingIdentifier, &tabbingIdentifier); std::string windowType; options.Get(options::kType, &windowType); bool hiddenInMissionControl = false; options.Get(options::kHiddenInMissionControl, &hiddenInMissionControl); bool useStandardWindow = true; // eventually deprecate separate "standardWindow" option in favor of // standard / textured window types options.Get(options::kStandardWindow, &useStandardWindow); if (windowType == "textured") { useStandardWindow = false; } // The window without titlebar is treated the same with frameless window. if (title_bar_style_ != TitleBarStyle::kNormal) set_has_frame(false); NSUInteger styleMask = NSWindowStyleMaskTitled; // The NSWindowStyleMaskFullSizeContentView style removes rounded corners // for frameless window. bool rounded_corner = true; options.Get(options::kRoundedCorners, &rounded_corner); if (!rounded_corner && !has_frame()) styleMask = NSWindowStyleMaskBorderless; if (minimizable) styleMask |= NSWindowStyleMaskMiniaturizable; if (closable) styleMask |= NSWindowStyleMaskClosable; if (resizable) styleMask |= NSWindowStyleMaskResizable; if (!useStandardWindow || transparent() || !has_frame()) styleMask |= NSWindowStyleMaskTexturedBackground; // Create views::Widget and assign window_ with it. // TODO(zcbenz): Get rid of the window_ in future. 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.native_widget = new ElectronNativeWidgetMac(this, windowType, styleMask, widget()); widget()->Init(std::move(params)); SetCanResize(resizable); window_ = static_cast<ElectronNSWindow*>( widget()->GetNativeWindow().GetNativeNSWindow()); RegisterDeleteDelegateCallback(base::BindOnce( [](NativeWindowMac* window) { if (window->window_) window->window_ = nil; if (window->buttons_proxy_) window->buttons_proxy_ = nil; }, this)); [window_ setEnableLargerThanScreen:enable_larger_than_screen()]; window_delegate_ = [[ElectronNSWindowDelegate alloc] initWithShell:this]; [window_ setDelegate:window_delegate_]; // Only use native parent window for non-modal windows. if (parent && !is_modal()) { SetParentWindow(parent); } if (transparent()) { // Setting the background color to clear will also hide the shadow. [window_ setBackgroundColor:[NSColor clearColor]]; } if (windowType == "desktop") { [window_ setLevel:kCGDesktopWindowLevel - 1]; [window_ setDisableKeyOrMainWindow:YES]; [window_ setCollectionBehavior:(NSWindowCollectionBehaviorCanJoinAllSpaces | NSWindowCollectionBehaviorStationary | NSWindowCollectionBehaviorIgnoresCycle)]; } if (windowType == "panel") { [window_ setLevel:NSFloatingWindowLevel]; } bool focusable; if (options.Get(options::kFocusable, &focusable) && !focusable) [window_ setDisableKeyOrMainWindow:YES]; if (transparent() || !has_frame()) { // Don't show title bar. [window_ setTitlebarAppearsTransparent:YES]; [window_ setTitleVisibility:NSWindowTitleHidden]; // Remove non-transparent corners, see // https://github.com/electron/electron/issues/517. [window_ setOpaque:NO]; // Show window buttons if titleBarStyle is not "normal". if (title_bar_style_ == TitleBarStyle::kNormal) { InternalSetWindowButtonVisibility(false); } else { buttons_proxy_ = [[WindowButtonsProxy alloc] initWithWindow:window_]; [buttons_proxy_ setHeight:titlebar_overlay_height()]; if (traffic_light_position_) { [buttons_proxy_ setMargin:*traffic_light_position_]; } else if (title_bar_style_ == TitleBarStyle::kHiddenInset) { // For macOS >= 11, while this value does not match official macOS apps // like Safari or Notes, it matches titleBarStyle's old implementation // before Electron <= 12. [buttons_proxy_ setMargin:gfx::Point(12, 11)]; } if (title_bar_style_ == TitleBarStyle::kCustomButtonsOnHover) { [buttons_proxy_ setShowOnHover:YES]; } else { // customButtonsOnHover does not show buttons initially. InternalSetWindowButtonVisibility(true); } } } // Create a tab only if tabbing identifier is specified and window has // a native title bar. if (tabbingIdentifier.empty() || transparent() || !has_frame()) { [window_ setTabbingMode:NSWindowTabbingModeDisallowed]; } else { [window_ setTabbingIdentifier:base::SysUTF8ToNSString(tabbingIdentifier)]; } // Resize to content bounds. bool use_content_size = false; options.Get(options::kUseContentSize, &use_content_size); if (!has_frame() || use_content_size) SetContentSize(gfx::Size(width, height)); // Enable the NSView to accept first mouse event. bool acceptsFirstMouse = false; options.Get(options::kAcceptFirstMouse, &acceptsFirstMouse); [window_ setAcceptsFirstMouse:acceptsFirstMouse]; // Disable auto-hiding cursor. bool disableAutoHideCursor = false; options.Get(options::kDisableAutoHideCursor, &disableAutoHideCursor); [window_ setDisableAutoHideCursor:disableAutoHideCursor]; SetHiddenInMissionControl(hiddenInMissionControl); // Set maximizable state last to ensure zoom button does not get reset // by calls to other APIs. SetMaximizable(maximizable); // Default content view. SetContentView(new views::View()); AddContentViewLayers(); UpdateWindowOriginalFrame(); original_level_ = [window_ level]; } NativeWindowMac::~NativeWindowMac() = default; void NativeWindowMac::SetContentView(views::View* view) { views::View* root_view = GetContentsView(); if (content_view()) root_view->RemoveChildView(content_view()); set_content_view(view); root_view->AddChildView(content_view()); root_view->Layout(); } void NativeWindowMac::Close() { if (!IsClosable()) { WindowList::WindowCloseCancelled(this); return; } if (fullscreen_transition_state() != FullScreenTransitionState::kNone) { SetHasDeferredWindowClose(true); return; } // Ensure we're detached from the parent window before closing. RemoveChildFromParentWindow(); while (!child_windows_.empty()) { auto* child = child_windows_.back(); child->RemoveChildFromParentWindow(); } // If a sheet is attached to the window when we call // [window_ performClose:nil], the window won't close properly // even after the user has ended the sheet. // Ensure it's closed before calling [window_ performClose:nil]. if ([window_ attachedSheet]) [window_ endSheet:[window_ attachedSheet]]; [window_ performClose:nil]; // Closing a sheet doesn't trigger windowShouldClose, // so we need to manually call it ourselves here. if (is_modal() && parent() && IsVisible()) { NotifyWindowCloseButtonClicked(); } } void NativeWindowMac::CloseImmediately() { // Ensure we're detached from the parent window before closing. RemoveChildFromParentWindow(); while (!child_windows_.empty()) { auto* child = child_windows_.back(); child->RemoveChildFromParentWindow(); } [window_ close]; } void NativeWindowMac::Focus(bool focus) { if (!IsVisible()) return; if (focus) { [[NSApplication sharedApplication] activateIgnoringOtherApps:NO]; [window_ makeKeyAndOrderFront:nil]; } else { [window_ orderOut:nil]; [window_ orderBack:nil]; } } bool NativeWindowMac::IsFocused() { return [window_ isKeyWindow]; } void NativeWindowMac::Show() { if (is_modal() && parent()) { NSWindow* window = parent()->GetNativeWindow().GetNativeNSWindow(); if ([window_ sheetParent] == nil) [window beginSheet:window_ completionHandler:^(NSModalResponse){ }]; return; } // Reattach the window to the parent to actually show it. if (parent()) InternalSetParentWindow(parent(), true); // This method is supposed to put focus on window, however if the app does not // have focus then "makeKeyAndOrderFront" will only show the window. [NSApp activateIgnoringOtherApps:YES]; [window_ makeKeyAndOrderFront:nil]; } void NativeWindowMac::ShowInactive() { // Reattach the window to the parent to actually show it. if (parent()) InternalSetParentWindow(parent(), true); [window_ orderFrontRegardless]; } void NativeWindowMac::Hide() { // If a sheet is attached to the window when we call [window_ orderOut:nil], // the sheet won't be able to show again on the same window. // Ensure it's closed before calling [window_ orderOut:nil]. if ([window_ attachedSheet]) [window_ endSheet:[window_ attachedSheet]]; if (is_modal() && parent()) { [window_ orderOut:nil]; [parent()->GetNativeWindow().GetNativeNSWindow() endSheet:window_]; return; } DetachChildren(); // Detach the window from the parent before. if (parent()) InternalSetParentWindow(parent(), false); [window_ orderOut:nil]; } bool NativeWindowMac::IsVisible() { bool occluded = [window_ occlusionState] == NSWindowOcclusionStateVisible; return [window_ isVisible] && !occluded && !IsMinimized(); } bool NativeWindowMac::IsEnabled() { return [window_ attachedSheet] == nil; } void NativeWindowMac::SetEnabled(bool enable) { if (!enable) { NSRect frame = [window_ frame]; NSWindow* window = [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, frame.size.width, frame.size.height) styleMask:NSWindowStyleMaskTitled backing:NSBackingStoreBuffered defer:NO]; [window setAlphaValue:0.5]; [window_ beginSheet:window completionHandler:^(NSModalResponse returnCode) { NSLog(@"main window disabled"); return; }]; } else if ([window_ attachedSheet]) { [window_ endSheet:[window_ attachedSheet]]; } } void NativeWindowMac::Maximize() { const bool is_visible = [window_ isVisible]; if (IsMaximized()) { if (!is_visible) ShowInactive(); return; } // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); [window_ zoom:nil]; if (!is_visible) { ShowInactive(); NotifyWindowMaximize(); } } void NativeWindowMac::Unmaximize() { // Bail if the last user set bounds were the same size as the window // screen (e.g. the user set the window to maximized via setBounds) // // Per docs during zoom: // > If there’s no saved user state because there has been no previous // > zoom,the size and location of the window don’t change. // // However, in classic Apple fashion, this is not the case in practice, // and the frame inexplicably becomes very tiny. We should prevent // zoom from being called if the window is being unmaximized and its // unmaximized window bounds are themselves functionally maximized. if (!IsMaximized() || user_set_bounds_maximized_) return; [window_ zoom:nil]; } bool NativeWindowMac::IsMaximized() { // It's possible for [window_ isZoomed] to be true // when the window is minimized or fullscreened. if (IsMinimized() || IsFullscreen()) return false; if (HasStyleMask(NSWindowStyleMaskResizable) != 0) return [window_ isZoomed]; NSRect rectScreen = GetAspectRatio() > 0.0 ? default_frame_for_zoom() : [[NSScreen mainScreen] visibleFrame]; return NSEqualRects([window_ frame], rectScreen); } void NativeWindowMac::Minimize() { if (IsMinimized()) return; // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); [window_ miniaturize:nil]; } void NativeWindowMac::Restore() { [window_ deminiaturize:nil]; } bool NativeWindowMac::IsMinimized() { return [window_ isMiniaturized]; } bool NativeWindowMac::HandleDeferredClose() { if (has_deferred_window_close_) { SetHasDeferredWindowClose(false); Close(); return true; } return false; } void NativeWindowMac::RemoveChildWindow(NativeWindow* child) { child_windows_.remove_if([&child](NativeWindow* w) { return (w == child); }); [window_ removeChildWindow:child->GetNativeWindow().GetNativeNSWindow()]; } void NativeWindowMac::RemoveChildFromParentWindow() { if (parent() && !is_modal()) { parent()->RemoveChildWindow(this); NativeWindow::SetParentWindow(nullptr); } } void NativeWindowMac::AttachChildren() { for (auto* child : child_windows_) { auto* child_nswindow = child->GetNativeWindow().GetNativeNSWindow(); if ([child_nswindow parentWindow] == window_) continue; // Attaching a window as a child window resets its window level, so // save and restore it afterwards. NSInteger level = window_.level; [window_ addChildWindow:child_nswindow ordered:NSWindowAbove]; [window_ setLevel:level]; } } void NativeWindowMac::DetachChildren() { DCHECK(child_windows_.size() == [[window_ childWindows] count]); // Hide all children before hiding/minimizing the window. // NativeWidgetNSWindowBridge::NotifyVisibilityChangeDown() // will DCHECK otherwise. for (auto* child : child_windows_) { [child->GetNativeWindow().GetNativeNSWindow() orderOut:nil]; } } void NativeWindowMac::SetFullScreen(bool fullscreen) { if (!has_frame() && !HasStyleMask(NSWindowStyleMaskTitled)) return; // [NSWindow -toggleFullScreen] is an asynchronous operation, which means // that it's possible to call it while a fullscreen transition is currently // in process. This can create weird behavior (incl. phantom windows), // so we want to schedule a transition for when the current one has completed. if (fullscreen_transition_state() != FullScreenTransitionState::kNone) { if (!pending_transitions_.empty()) { bool last_pending = pending_transitions_.back(); // Only push new transitions if they're different than the last transition // in the queue. if (last_pending != fullscreen) pending_transitions_.push(fullscreen); } else { pending_transitions_.push(fullscreen); } return; } if (fullscreen == IsFullscreen() || !IsFullScreenable()) return; // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); // This needs to be set here because it can be the case that // SetFullScreen is called by a user before windowWillEnterFullScreen // or windowWillExitFullScreen are invoked, and so a potential transition // could be dropped. fullscreen_transition_state_ = fullscreen ? FullScreenTransitionState::kEntering : FullScreenTransitionState::kExiting; [window_ toggleFullScreenMode:nil]; } bool NativeWindowMac::IsFullscreen() const { return HasStyleMask(NSWindowStyleMaskFullScreen); } void NativeWindowMac::SetBounds(const gfx::Rect& bounds, bool animate) { // Do nothing if in fullscreen mode. if (IsFullscreen()) return; // Check size constraints since setFrame does not check it. gfx::Size size = bounds.size(); size.SetToMax(GetMinimumSize()); gfx::Size max_size = GetMaximumSize(); if (!max_size.IsEmpty()) size.SetToMin(max_size); NSRect cocoa_bounds = NSMakeRect(bounds.x(), 0, size.width(), size.height()); // Flip coordinates based on the primary screen. NSScreen* screen = [[NSScreen screens] firstObject]; cocoa_bounds.origin.y = NSHeight([screen frame]) - size.height() - bounds.y(); [window_ setFrame:cocoa_bounds display:YES animate:animate]; user_set_bounds_maximized_ = IsMaximized() ? true : false; UpdateWindowOriginalFrame(); } gfx::Rect NativeWindowMac::GetBounds() { NSRect frame = [window_ frame]; gfx::Rect bounds(frame.origin.x, 0, NSWidth(frame), NSHeight(frame)); NSScreen* screen = [[NSScreen screens] firstObject]; bounds.set_y(NSHeight([screen frame]) - NSMaxY(frame)); return bounds; } bool NativeWindowMac::IsNormal() { return NativeWindow::IsNormal() && !IsSimpleFullScreen(); } gfx::Rect NativeWindowMac::GetNormalBounds() { if (IsNormal()) { return GetBounds(); } NSRect frame = original_frame_; gfx::Rect bounds(frame.origin.x, 0, NSWidth(frame), NSHeight(frame)); NSScreen* screen = [[NSScreen screens] firstObject]; bounds.set_y(NSHeight([screen frame]) - NSMaxY(frame)); return bounds; // Works on OS_WIN ! // return widget()->GetRestoredBounds(); } void NativeWindowMac::SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints) { auto convertSize = [this](const gfx::Size& size) { // Our frameless window still has titlebar attached, so setting contentSize // will result in actual content size being larger. if (!has_frame()) { NSRect frame = NSMakeRect(0, 0, size.width(), size.height()); NSRect content = [window_ originalContentRectForFrameRect:frame]; return content.size; } else { return NSMakeSize(size.width(), size.height()); } }; NSView* content = [window_ contentView]; if (size_constraints.HasMinimumSize()) { NSSize min_size = convertSize(size_constraints.GetMinimumSize()); [window_ setContentMinSize:[content convertSize:min_size toView:nil]]; } if (size_constraints.HasMaximumSize()) { NSSize max_size = convertSize(size_constraints.GetMaximumSize()); [window_ setContentMaxSize:[content convertSize:max_size toView:nil]]; } NativeWindow::SetContentSizeConstraints(size_constraints); } bool NativeWindowMac::MoveAbove(const std::string& sourceId) { const content::DesktopMediaID id = content::DesktopMediaID::Parse(sourceId); if (id.type != content::DesktopMediaID::TYPE_WINDOW) return false; // Check if the window source is valid. const CGWindowID window_id = id.id; if (!webrtc::GetWindowOwnerPid(window_id)) return false; if (!parent() || is_modal()) { [window_ orderWindow:NSWindowAbove relativeTo:window_id]; } else { NSWindow* other_window = [NSApp windowWithWindowNumber:window_id]; ReorderChildWindowAbove(window_, other_window); } return true; } void NativeWindowMac::MoveTop() { if (!parent() || is_modal()) { [window_ orderWindow:NSWindowAbove relativeTo:0]; } else { ReorderChildWindowAbove(window_, nullptr); } } void NativeWindowMac::SetResizable(bool resizable) { ScopedDisableResize disable_resize; SetStyleMask(resizable, NSWindowStyleMaskResizable); // Right now, resizable and fullscreenable are decoupled in // documentation and on Windows/Linux. Chromium disables // fullscreenability if resizability is false on macOS as well // as disabling the maximize traffic light unless the window // is both resizable and maximizable. To work around this, we want // to match behavior on other platforms by disabiliting the maximize // button but keeping fullscreenability enabled. // TODO(codebytere): refactor this once we have a better solution. SetCanResize(resizable); if (!resizable) { SetFullScreenable(true); [[window_ standardWindowButton:NSWindowZoomButton] setEnabled:false]; } else { SetFullScreenable(true); [[window_ standardWindowButton:NSWindowZoomButton] setEnabled:IsFullScreenable()]; } } bool NativeWindowMac::IsResizable() { bool in_fs_transition = fullscreen_transition_state() != FullScreenTransitionState::kNone; bool has_rs_mask = HasStyleMask(NSWindowStyleMaskResizable); return has_rs_mask && !IsFullscreen() && !in_fs_transition; } void NativeWindowMac::SetMovable(bool movable) { [window_ setMovable:movable]; } bool NativeWindowMac::IsMovable() { return [window_ isMovable]; } void NativeWindowMac::SetMinimizable(bool minimizable) { SetStyleMask(minimizable, NSWindowStyleMaskMiniaturizable); } bool NativeWindowMac::IsMinimizable() { return HasStyleMask(NSWindowStyleMaskMiniaturizable); } void NativeWindowMac::SetMaximizable(bool maximizable) { maximizable_ = maximizable; [[window_ standardWindowButton:NSWindowZoomButton] setEnabled:maximizable]; } bool NativeWindowMac::IsMaximizable() { return [[window_ standardWindowButton:NSWindowZoomButton] isEnabled]; } void NativeWindowMac::SetFullScreenable(bool fullscreenable) { SetCollectionBehavior(fullscreenable, NSWindowCollectionBehaviorFullScreenPrimary); // On EL Capitan this flag is required to hide fullscreen button. SetCollectionBehavior(!fullscreenable, NSWindowCollectionBehaviorFullScreenAuxiliary); } bool NativeWindowMac::IsFullScreenable() { NSUInteger collectionBehavior = [window_ collectionBehavior]; return collectionBehavior & NSWindowCollectionBehaviorFullScreenPrimary; } void NativeWindowMac::SetClosable(bool closable) { SetStyleMask(closable, NSWindowStyleMaskClosable); } bool NativeWindowMac::IsClosable() { return HasStyleMask(NSWindowStyleMaskClosable); } void NativeWindowMac::SetAlwaysOnTop(ui::ZOrderLevel z_order, const std::string& level_name, int relative_level) { if (z_order == ui::ZOrderLevel::kNormal) { SetWindowLevel(NSNormalWindowLevel); return; } int level = NSNormalWindowLevel; if (level_name == "floating") { level = NSFloatingWindowLevel; } else if (level_name == "torn-off-menu") { level = NSTornOffMenuWindowLevel; } else if (level_name == "modal-panel") { level = NSModalPanelWindowLevel; } else if (level_name == "main-menu") { level = NSMainMenuWindowLevel; } else if (level_name == "status") { level = NSStatusWindowLevel; } else if (level_name == "pop-up-menu") { level = NSPopUpMenuWindowLevel; } else if (level_name == "screen-saver") { level = NSScreenSaverWindowLevel; } SetWindowLevel(level + relative_level); } std::string NativeWindowMac::GetAlwaysOnTopLevel() { std::string level_name = "normal"; int level = [window_ level]; if (level == NSFloatingWindowLevel) { level_name = "floating"; } else if (level == NSTornOffMenuWindowLevel) { level_name = "torn-off-menu"; } else if (level == NSModalPanelWindowLevel) { level_name = "modal-panel"; } else if (level == NSMainMenuWindowLevel) { level_name = "main-menu"; } else if (level == NSStatusWindowLevel) { level_name = "status"; } else if (level == NSPopUpMenuWindowLevel) { level_name = "pop-up-menu"; } else if (level == NSScreenSaverWindowLevel) { level_name = "screen-saver"; } return level_name; } void NativeWindowMac::SetWindowLevel(int unbounded_level) { int level = std::min( std::max(unbounded_level, CGWindowLevelForKey(kCGMinimumWindowLevelKey)), CGWindowLevelForKey(kCGMaximumWindowLevelKey)); ui::ZOrderLevel z_order_level = level == NSNormalWindowLevel ? ui::ZOrderLevel::kNormal : ui::ZOrderLevel::kFloatingWindow; bool did_z_order_level_change = z_order_level != GetZOrderLevel(); was_maximizable_ = IsMaximizable(); // We need to explicitly keep the NativeWidget up to date, since it stores the // window level in a local variable, rather than reading it from the NSWindow. // Unfortunately, it results in a second setLevel call. It's not ideal, but we // don't expect this to cause any user-visible jank. widget()->SetZOrderLevel(z_order_level); [window_ setLevel:level]; // Set level will make the zoom button revert to default, probably // a bug of Cocoa or macOS. SetMaximizable(was_maximizable_); // This must be notified at the very end or IsAlwaysOnTop // will not yet have been updated to reflect the new status if (did_z_order_level_change) NativeWindow::NotifyWindowAlwaysOnTopChanged(); } ui::ZOrderLevel NativeWindowMac::GetZOrderLevel() { return widget()->GetZOrderLevel(); } void NativeWindowMac::Center() { [window_ center]; } void NativeWindowMac::Invalidate() { [[window_ contentView] setNeedsDisplay:YES]; } void NativeWindowMac::SetTitle(const std::string& title) { [window_ setTitle:base::SysUTF8ToNSString(title)]; if (buttons_proxy_) [buttons_proxy_ redraw]; } std::string NativeWindowMac::GetTitle() { return base::SysNSStringToUTF8([window_ title]); } void NativeWindowMac::FlashFrame(bool flash) { if (flash) { attention_request_id_ = [NSApp requestUserAttention:NSInformationalRequest]; } else { [NSApp cancelUserAttentionRequest:attention_request_id_]; attention_request_id_ = 0; } } void NativeWindowMac::SetSkipTaskbar(bool skip) {} bool NativeWindowMac::IsExcludedFromShownWindowsMenu() { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); return [window isExcludedFromWindowsMenu]; } void NativeWindowMac::SetExcludedFromShownWindowsMenu(bool excluded) { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); [window setExcludedFromWindowsMenu:excluded]; } void NativeWindowMac::OnDisplayMetricsChanged(const display::Display& display, uint32_t changed_metrics) { // We only want to force screen recalibration if we're in simpleFullscreen // mode. if (!is_simple_fullscreen_) return; content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&NativeWindow::UpdateFrame, GetWeakPtr())); } void NativeWindowMac::SetSimpleFullScreen(bool simple_fullscreen) { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); if (simple_fullscreen && !is_simple_fullscreen_) { is_simple_fullscreen_ = true; // Take note of the current window size and level if (IsNormal()) { UpdateWindowOriginalFrame(); original_level_ = [window_ level]; } simple_fullscreen_options_ = [NSApp currentSystemPresentationOptions]; simple_fullscreen_mask_ = [window styleMask]; // We can simulate the pre-Lion fullscreen by auto-hiding the dock and menu // bar NSApplicationPresentationOptions options = NSApplicationPresentationAutoHideDock | NSApplicationPresentationAutoHideMenuBar; [NSApp setPresentationOptions:options]; was_maximizable_ = IsMaximizable(); was_movable_ = IsMovable(); NSRect fullscreenFrame = [window.screen frame]; // If our app has dock hidden, set the window level higher so another app's // menu bar doesn't appear on top of our fullscreen app. if ([[NSRunningApplication currentApplication] activationPolicy] != NSApplicationActivationPolicyRegular) { window.level = NSPopUpMenuWindowLevel; } // Always hide the titlebar in simple fullscreen mode. // // Note that we must remove the NSWindowStyleMaskTitled style instead of // using the [window_ setTitleVisibility:], as the latter would leave the // window with rounded corners. SetStyleMask(false, NSWindowStyleMaskTitled); if (!window_button_visibility_.has_value()) { // Lets keep previous behaviour - hide window controls in titled // fullscreen mode when not specified otherwise. InternalSetWindowButtonVisibility(false); } [window setFrame:fullscreenFrame display:YES animate:YES]; // Fullscreen windows can't be resized, minimized, maximized, or moved SetMinimizable(false); SetResizable(false); SetMaximizable(false); SetMovable(false); } else if (!simple_fullscreen && is_simple_fullscreen_) { is_simple_fullscreen_ = false; [window setFrame:original_frame_ display:YES animate:YES]; window.level = original_level_; [NSApp setPresentationOptions:simple_fullscreen_options_]; // Restore original style mask ScopedDisableResize disable_resize; [window_ setStyleMask:simple_fullscreen_mask_]; // Restore window manipulation abilities SetMaximizable(was_maximizable_); SetMovable(was_movable_); // Restore default window controls visibility state. if (!window_button_visibility_.has_value()) { bool visibility; if (has_frame()) visibility = true; else visibility = title_bar_style_ != TitleBarStyle::kNormal; InternalSetWindowButtonVisibility(visibility); } if (buttons_proxy_) [buttons_proxy_ redraw]; } } bool NativeWindowMac::IsSimpleFullScreen() { return is_simple_fullscreen_; } void NativeWindowMac::SetKiosk(bool kiosk) { if (kiosk && !is_kiosk_) { kiosk_options_ = [NSApp currentSystemPresentationOptions]; NSApplicationPresentationOptions options = NSApplicationPresentationHideDock | NSApplicationPresentationHideMenuBar | NSApplicationPresentationDisableAppleMenu | NSApplicationPresentationDisableProcessSwitching | NSApplicationPresentationDisableForceQuit | NSApplicationPresentationDisableSessionTermination | NSApplicationPresentationDisableHideApplication; [NSApp setPresentationOptions:options]; is_kiosk_ = true; fullscreen_before_kiosk_ = IsFullscreen(); if (!fullscreen_before_kiosk_) SetFullScreen(true); } else if (!kiosk && is_kiosk_) { is_kiosk_ = false; if (!fullscreen_before_kiosk_) SetFullScreen(false); // Set presentation options *after* asynchronously exiting // fullscreen to ensure they take effect. [NSApp setPresentationOptions:kiosk_options_]; } } bool NativeWindowMac::IsKiosk() { return is_kiosk_; } void NativeWindowMac::SetBackgroundColor(SkColor color) { base::ScopedCFTypeRef<CGColorRef> cgcolor( skia::CGColorCreateFromSkColor(color)); [[[window_ contentView] layer] setBackgroundColor:cgcolor]; } SkColor NativeWindowMac::GetBackgroundColor() { CGColorRef color = [[[window_ contentView] layer] backgroundColor]; if (!color) return SK_ColorTRANSPARENT; return skia::CGColorRefToSkColor(color); } void NativeWindowMac::SetHasShadow(bool has_shadow) { [window_ setHasShadow:has_shadow]; } bool NativeWindowMac::HasShadow() { return [window_ hasShadow]; } void NativeWindowMac::InvalidateShadow() { [window_ invalidateShadow]; } void NativeWindowMac::SetOpacity(const double opacity) { const double boundedOpacity = std::clamp(opacity, 0.0, 1.0); [window_ setAlphaValue:boundedOpacity]; } double NativeWindowMac::GetOpacity() { return [window_ alphaValue]; } void NativeWindowMac::SetRepresentedFilename(const std::string& filename) { [window_ setRepresentedFilename:base::SysUTF8ToNSString(filename)]; if (buttons_proxy_) [buttons_proxy_ redraw]; } std::string NativeWindowMac::GetRepresentedFilename() { return base::SysNSStringToUTF8([window_ representedFilename]); } void NativeWindowMac::SetDocumentEdited(bool edited) { [window_ setDocumentEdited:edited]; if (buttons_proxy_) [buttons_proxy_ redraw]; } bool NativeWindowMac::IsDocumentEdited() { return [window_ isDocumentEdited]; } bool NativeWindowMac::IsHiddenInMissionControl() { NSUInteger collectionBehavior = [window_ collectionBehavior]; return collectionBehavior & NSWindowCollectionBehaviorTransient; } void NativeWindowMac::SetHiddenInMissionControl(bool hidden) { SetCollectionBehavior(hidden, NSWindowCollectionBehaviorTransient); } void NativeWindowMac::SetIgnoreMouseEvents(bool ignore, bool forward) { [window_ setIgnoresMouseEvents:ignore]; if (!ignore) { SetForwardMouseMessages(NO); } else { SetForwardMouseMessages(forward); } } void NativeWindowMac::SetContentProtection(bool enable) { [window_ setSharingType:enable ? NSWindowSharingNone : NSWindowSharingReadOnly]; } void NativeWindowMac::SetFocusable(bool focusable) { // No known way to unfocus the window if it had the focus. Here we do not // want to call Focus(false) because it moves the window to the back, i.e. // at the bottom in term of z-order. [window_ setDisableKeyOrMainWindow:!focusable]; } bool NativeWindowMac::IsFocusable() { return ![window_ disableKeyOrMainWindow]; } void NativeWindowMac::AddBrowserView(NativeBrowserView* view) { [CATransaction begin]; [CATransaction setDisableActions:YES]; if (!view) { [CATransaction commit]; return; } add_browser_view(view); if (view->GetInspectableWebContentsView()) { auto* native_view = view->GetInspectableWebContentsView() ->GetNativeView() .GetNativeNSView(); [[window_ contentView] addSubview:native_view positioned:NSWindowAbove relativeTo:nil]; native_view.hidden = NO; } [CATransaction commit]; } void NativeWindowMac::RemoveBrowserView(NativeBrowserView* view) { [CATransaction begin]; [CATransaction setDisableActions:YES]; if (!view) { [CATransaction commit]; return; } if (view->GetInspectableWebContentsView()) [view->GetInspectableWebContentsView()->GetNativeView().GetNativeNSView() removeFromSuperview]; remove_browser_view(view); [CATransaction commit]; } void NativeWindowMac::SetTopBrowserView(NativeBrowserView* view) { [CATransaction begin]; [CATransaction setDisableActions:YES]; if (!view) { [CATransaction commit]; return; } remove_browser_view(view); add_browser_view(view); if (view->GetInspectableWebContentsView()) { auto* native_view = view->GetInspectableWebContentsView() ->GetNativeView() .GetNativeNSView(); [[window_ contentView] addSubview:native_view positioned:NSWindowAbove relativeTo:nil]; native_view.hidden = NO; } [CATransaction commit]; } void NativeWindowMac::SetParentWindow(NativeWindow* parent) { InternalSetParentWindow(parent, IsVisible()); } gfx::NativeView NativeWindowMac::GetNativeView() const { return [window_ contentView]; } gfx::NativeWindow NativeWindowMac::GetNativeWindow() const { return window_; } gfx::AcceleratedWidget NativeWindowMac::GetAcceleratedWidget() const { return [window_ windowNumber]; } content::DesktopMediaID NativeWindowMac::GetDesktopMediaID() const { auto desktop_media_id = content::DesktopMediaID( content::DesktopMediaID::TYPE_WINDOW, GetAcceleratedWidget()); // c.f. // https://source.chromium.org/chromium/chromium/src/+/main:chrome/browser/media/webrtc/native_desktop_media_list.cc;l=775-780;drc=79502ab47f61bff351426f57f576daef02b1a8dc // Refs https://github.com/electron/electron/pull/30507 // TODO(deepak1556): Match upstream for `kWindowCaptureMacV2` #if 0 if (remote_cocoa::ScopedCGWindowID::Get(desktop_media_id.id)) { desktop_media_id.window_id = desktop_media_id.id; } #endif return desktop_media_id; } NativeWindowHandle NativeWindowMac::GetNativeWindowHandle() const { return [window_ contentView]; } void NativeWindowMac::SetProgressBar(double progress, const NativeWindow::ProgressState state) { NSDockTile* dock_tile = [NSApp dockTile]; // Sometimes macOS would install a default contentView for dock, we must // verify whether NSProgressIndicator has been installed. bool first_time = !dock_tile.contentView || [[dock_tile.contentView subviews] count] == 0 || ![[[dock_tile.contentView subviews] lastObject] isKindOfClass:[NSProgressIndicator class]]; // For the first time API invoked, we need to create a ContentView in // DockTile. if (first_time) { NSImageView* image_view = [[NSImageView alloc] init]; [image_view setImage:[NSApp applicationIconImage]]; [dock_tile setContentView:image_view]; NSRect frame = NSMakeRect(0.0f, 0.0f, dock_tile.size.width, 15.0); NSProgressIndicator* progress_indicator = [[ElectronProgressBar alloc] initWithFrame:frame]; [progress_indicator setStyle:NSProgressIndicatorStyleBar]; [progress_indicator setIndeterminate:NO]; [progress_indicator setBezeled:YES]; [progress_indicator setMinValue:0]; [progress_indicator setMaxValue:1]; [progress_indicator setHidden:NO]; [dock_tile.contentView addSubview:progress_indicator]; } NSProgressIndicator* progress_indicator = static_cast<NSProgressIndicator*>( [[[dock_tile contentView] subviews] lastObject]); if (progress < 0) { [progress_indicator setHidden:YES]; } else if (progress > 1) { [progress_indicator setHidden:NO]; [progress_indicator setIndeterminate:YES]; [progress_indicator setDoubleValue:1]; } else { [progress_indicator setHidden:NO]; [progress_indicator setDoubleValue:progress]; } [dock_tile display]; } void NativeWindowMac::SetOverlayIcon(const gfx::Image& overlay, const std::string& description) {} void NativeWindowMac::SetVisibleOnAllWorkspaces(bool visible, bool visibleOnFullScreen, bool skipTransformProcessType) { // In order for NSWindows to be visible on fullscreen we need to invoke // app.dock.hide() since Apple changed the underlying functionality of // NSWindows starting with 10.14 to disallow NSWindows from floating on top of // fullscreen apps. if (!skipTransformProcessType) { if (visibleOnFullScreen) { Browser::Get()->DockHide(); } else { Browser::Get()->DockShow(JavascriptEnvironment::GetIsolate()); } } SetCollectionBehavior(visible, NSWindowCollectionBehaviorCanJoinAllSpaces); SetCollectionBehavior(visibleOnFullScreen, NSWindowCollectionBehaviorFullScreenAuxiliary); } bool NativeWindowMac::IsVisibleOnAllWorkspaces() { NSUInteger collectionBehavior = [window_ collectionBehavior]; return collectionBehavior & NSWindowCollectionBehaviorCanJoinAllSpaces; } void NativeWindowMac::SetAutoHideCursor(bool auto_hide) { [window_ setDisableAutoHideCursor:!auto_hide]; } void NativeWindowMac::UpdateVibrancyRadii(bool fullscreen) { NSVisualEffectView* vibrantView = [window_ vibrantView]; if (vibrantView != nil && !vibrancy_type_.empty()) { const bool no_rounded_corner = !HasStyleMask(NSWindowStyleMaskTitled); if (!has_frame() && !is_modal() && !no_rounded_corner) { CGFloat radius; if (fullscreen) { radius = 0.0f; } else if (@available(macOS 11.0, *)) { radius = 9.0f; } else { // Smaller corner radius on versions prior to Big Sur. radius = 5.0f; } CGFloat dimension = 2 * radius + 1; NSSize size = NSMakeSize(dimension, dimension); NSImage* maskImage = [NSImage imageWithSize:size flipped:NO drawingHandler:^BOOL(NSRect rect) { NSBezierPath* bezierPath = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [[NSColor blackColor] set]; [bezierPath fill]; return YES; }]; [maskImage setCapInsets:NSEdgeInsetsMake(radius, radius, radius, radius)]; [maskImage setResizingMode:NSImageResizingModeStretch]; [vibrantView setMaskImage:maskImage]; [window_ setCornerMask:maskImage]; } } } void NativeWindowMac::UpdateWindowOriginalFrame() { original_frame_ = [window_ frame]; } void NativeWindowMac::SetVibrancy(const std::string& type) { NSVisualEffectView* vibrantView = [window_ vibrantView]; if (type.empty()) { if (vibrantView == nil) return; [vibrantView removeFromSuperview]; [window_ setVibrantView:nil]; return; } NSVisualEffectMaterial vibrancyType{}; if (type == "titlebar") { vibrancyType = NSVisualEffectMaterialTitlebar; } else if (type == "selection") { vibrancyType = NSVisualEffectMaterialSelection; } else if (type == "menu") { vibrancyType = NSVisualEffectMaterialMenu; } else if (type == "popover") { vibrancyType = NSVisualEffectMaterialPopover; } else if (type == "sidebar") { vibrancyType = NSVisualEffectMaterialSidebar; } else if (type == "header") { vibrancyType = NSVisualEffectMaterialHeaderView; } else if (type == "sheet") { vibrancyType = NSVisualEffectMaterialSheet; } else if (type == "window") { vibrancyType = NSVisualEffectMaterialWindowBackground; } else if (type == "hud") { vibrancyType = NSVisualEffectMaterialHUDWindow; } else if (type == "fullscreen-ui") { vibrancyType = NSVisualEffectMaterialFullScreenUI; } else if (type == "tooltip") { vibrancyType = NSVisualEffectMaterialToolTip; } else if (type == "content") { vibrancyType = NSVisualEffectMaterialContentBackground; } else if (type == "under-window") { vibrancyType = NSVisualEffectMaterialUnderWindowBackground; } else if (type == "under-page") { vibrancyType = NSVisualEffectMaterialUnderPageBackground; } if (vibrancyType) { vibrancy_type_ = type; if (vibrantView == nil) { vibrantView = [[NSVisualEffectView alloc] initWithFrame:[[window_ contentView] bounds]]; [window_ setVibrantView:vibrantView]; [vibrantView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable]; [vibrantView setBlendingMode:NSVisualEffectBlendingModeBehindWindow]; if (visual_effect_state_ == VisualEffectState::kActive) { [vibrantView setState:NSVisualEffectStateActive]; } else if (visual_effect_state_ == VisualEffectState::kInactive) { [vibrantView setState:NSVisualEffectStateInactive]; } else { [vibrantView setState:NSVisualEffectStateFollowsWindowActiveState]; } [[window_ contentView] addSubview:vibrantView positioned:NSWindowBelow relativeTo:nil]; UpdateVibrancyRadii(IsFullscreen()); } [vibrantView setMaterial:vibrancyType]; } } void NativeWindowMac::SetWindowButtonVisibility(bool visible) { window_button_visibility_ = visible; if (buttons_proxy_) { if (visible) [buttons_proxy_ redraw]; [buttons_proxy_ setVisible:visible]; } if (title_bar_style_ != TitleBarStyle::kCustomButtonsOnHover) InternalSetWindowButtonVisibility(visible); NotifyLayoutWindowControlsOverlay(); } bool NativeWindowMac::GetWindowButtonVisibility() const { return ![window_ standardWindowButton:NSWindowZoomButton].hidden || ![window_ standardWindowButton:NSWindowMiniaturizeButton].hidden || ![window_ standardWindowButton:NSWindowCloseButton].hidden; } void NativeWindowMac::SetWindowButtonPosition( absl::optional<gfx::Point> position) { traffic_light_position_ = std::move(position); if (buttons_proxy_) { [buttons_proxy_ setMargin:traffic_light_position_]; NotifyLayoutWindowControlsOverlay(); } } absl::optional<gfx::Point> NativeWindowMac::GetWindowButtonPosition() const { return traffic_light_position_; } void NativeWindowMac::RedrawTrafficLights() { if (buttons_proxy_ && !IsFullscreen()) [buttons_proxy_ redraw]; } // In simpleFullScreen mode, update the frame for new bounds. void NativeWindowMac::UpdateFrame() { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); NSRect fullscreenFrame = [window.screen frame]; [window setFrame:fullscreenFrame display:YES animate:YES]; } void NativeWindowMac::SetTouchBar( std::vector<gin_helper::PersistentDictionary> items) { touch_bar_ = [[ElectronTouchBar alloc] initWithDelegate:window_delegate_ window:this settings:std::move(items)]; [window_ setTouchBar:nil]; } void NativeWindowMac::RefreshTouchBarItem(const std::string& item_id) { if (touch_bar_ && [window_ touchBar]) [touch_bar_ refreshTouchBarItem:[window_ touchBar] id:item_id]; } void NativeWindowMac::SetEscapeTouchBarItem( gin_helper::PersistentDictionary item) { if (touch_bar_ && [window_ touchBar]) [touch_bar_ setEscapeTouchBarItem:std::move(item) forTouchBar:[window_ touchBar]]; } void NativeWindowMac::SelectPreviousTab() { [window_ selectPreviousTab:nil]; } void NativeWindowMac::SelectNextTab() { [window_ selectNextTab:nil]; } void NativeWindowMac::ShowAllTabs() { [window_ toggleTabOverview:nil]; } void NativeWindowMac::MergeAllWindows() { [window_ mergeAllWindows:nil]; } void NativeWindowMac::MoveTabToNewWindow() { [window_ moveTabToNewWindow:nil]; } void NativeWindowMac::ToggleTabBar() { [window_ toggleTabBar:nil]; } bool NativeWindowMac::AddTabbedWindow(NativeWindow* window) { if (window_ == window->GetNativeWindow().GetNativeNSWindow()) { return false; } else { [window_ addTabbedWindow:window->GetNativeWindow().GetNativeNSWindow() ordered:NSWindowAbove]; } return true; } void NativeWindowMac::SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) { NativeWindow::SetAspectRatio(aspect_ratio, extra_size); // Reset the behaviour to default if aspect_ratio is set to 0 or less. if (aspect_ratio > 0.0) { NSSize aspect_ratio_size = NSMakeSize(aspect_ratio, 1.0); if (has_frame()) [window_ setContentAspectRatio:aspect_ratio_size]; else [window_ setAspectRatio:aspect_ratio_size]; } else { [window_ setResizeIncrements:NSMakeSize(1.0, 1.0)]; } } void NativeWindowMac::PreviewFile(const std::string& path, const std::string& display_name) { preview_item_ = [[ElectronPreviewItem alloc] initWithURL:[NSURL fileURLWithPath:base::SysUTF8ToNSString(path)] title:base::SysUTF8ToNSString(display_name)]; [[QLPreviewPanel sharedPreviewPanel] makeKeyAndOrderFront:nil]; } void NativeWindowMac::CloseFilePreview() { if ([QLPreviewPanel sharedPreviewPanelExists]) { [[QLPreviewPanel sharedPreviewPanel] close]; } } gfx::Rect NativeWindowMac::ContentBoundsToWindowBounds( const gfx::Rect& bounds) const { if (has_frame()) { gfx::Rect window_bounds( [window_ frameRectForContentRect:bounds.ToCGRect()]); int frame_height = window_bounds.height() - bounds.height(); window_bounds.set_y(window_bounds.y() - frame_height); return window_bounds; } else { return bounds; } } gfx::Rect NativeWindowMac::WindowBoundsToContentBounds( const gfx::Rect& bounds) const { if (has_frame()) { gfx::Rect content_bounds( [window_ contentRectForFrameRect:bounds.ToCGRect()]); int frame_height = bounds.height() - content_bounds.height(); content_bounds.set_y(content_bounds.y() + frame_height); return content_bounds; } else { return bounds; } } void NativeWindowMac::NotifyWindowEnterFullScreen() { NativeWindow::NotifyWindowEnterFullScreen(); // Restore the window title under fullscreen mode. if (buttons_proxy_) [window_ setTitleVisibility:NSWindowTitleVisible]; } void NativeWindowMac::NotifyWindowLeaveFullScreen() { NativeWindow::NotifyWindowLeaveFullScreen(); // Restore window buttons. if (buttons_proxy_ && window_button_visibility_.value_or(true)) { [buttons_proxy_ redraw]; [buttons_proxy_ setVisible:YES]; } } void NativeWindowMac::NotifyWindowWillEnterFullScreen() { UpdateVibrancyRadii(true); } void NativeWindowMac::NotifyWindowWillLeaveFullScreen() { if (buttons_proxy_) { // Hide window title when leaving fullscreen. [window_ setTitleVisibility:NSWindowTitleHidden]; // Hide the container otherwise traffic light buttons jump. [buttons_proxy_ setVisible:NO]; } UpdateVibrancyRadii(false); } void NativeWindowMac::SetActive(bool is_key) { is_active_ = is_key; } bool NativeWindowMac::IsActive() const { return is_active_; } void NativeWindowMac::Cleanup() { DCHECK(!IsClosed()); ui::NativeTheme::GetInstanceForNativeUi()->RemoveObserver(this); display::Screen::GetScreen()->RemoveObserver(this); } class NativeAppWindowFrameViewMac : public views::NativeFrameViewMac { public: NativeAppWindowFrameViewMac(views::Widget* frame, NativeWindowMac* window) : views::NativeFrameViewMac(frame), native_window_(window) {} NativeAppWindowFrameViewMac(const NativeAppWindowFrameViewMac&) = delete; NativeAppWindowFrameViewMac& operator=(const NativeAppWindowFrameViewMac&) = delete; ~NativeAppWindowFrameViewMac() override = default; // NonClientFrameView: int NonClientHitTest(const gfx::Point& point) override { if (!bounds().Contains(point)) return HTNOWHERE; if (GetWidget()->IsFullscreen()) return HTCLIENT; // Check for possible draggable region in the client area for the frameless // window. int contents_hit_test = native_window_->NonClientHitTest(point); if (contents_hit_test != HTNOWHERE) return contents_hit_test; return HTCLIENT; } private: // Weak. raw_ptr<NativeWindowMac> const native_window_; }; std::unique_ptr<views::NonClientFrameView> NativeWindowMac::CreateNonClientFrameView(views::Widget* widget) { return std::make_unique<NativeAppWindowFrameViewMac>(widget, this); } bool NativeWindowMac::HasStyleMask(NSUInteger flag) const { return [window_ styleMask] & flag; } void NativeWindowMac::SetStyleMask(bool on, NSUInteger flag) { // Changing the styleMask of a frameless windows causes it to change size so // we explicitly disable resizing while setting it. ScopedDisableResize disable_resize; if (on) [window_ setStyleMask:[window_ styleMask] | flag]; else [window_ setStyleMask:[window_ styleMask] & (~flag)]; // Change style mask will make the zoom button revert to default, probably // a bug of Cocoa or macOS. SetMaximizable(maximizable_); } void NativeWindowMac::SetCollectionBehavior(bool on, NSUInteger flag) { if (on) [window_ setCollectionBehavior:[window_ collectionBehavior] | flag]; else [window_ setCollectionBehavior:[window_ collectionBehavior] & (~flag)]; // Change collectionBehavior will make the zoom button revert to default, // probably a bug of Cocoa or macOS. SetMaximizable(maximizable_); } views::View* NativeWindowMac::GetContentsView() { return root_view_.get(); } bool NativeWindowMac::CanMaximize() const { return maximizable_; } void NativeWindowMac::OnNativeThemeUpdated(ui::NativeTheme* observed_theme) { content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&NativeWindow::RedrawTrafficLights, GetWeakPtr())); } void NativeWindowMac::AddContentViewLayers() { // Make sure the bottom corner is rounded for non-modal windows: // http://crbug.com/396264. if (!is_modal()) { // For normal window, we need to explicitly set layer for contentView to // make setBackgroundColor work correctly. // There is no need to do so for frameless window, and doing so would make // titleBarStyle stop working. if (has_frame()) { CALayer* background_layer = [[CALayer alloc] init]; [background_layer setAutoresizingMask:kCALayerWidthSizable | kCALayerHeightSizable]; [[window_ contentView] setLayer:background_layer]; } [[window_ contentView] setWantsLayer:YES]; } } void NativeWindowMac::InternalSetWindowButtonVisibility(bool visible) { [[window_ standardWindowButton:NSWindowCloseButton] setHidden:!visible]; [[window_ standardWindowButton:NSWindowMiniaturizeButton] setHidden:!visible]; [[window_ standardWindowButton:NSWindowZoomButton] setHidden:!visible]; } void NativeWindowMac::InternalSetParentWindow(NativeWindow* new_parent, bool attach) { if (is_modal()) return; // Do not remove/add if we are already properly attached. if (attach && new_parent && [window_ parentWindow] == new_parent->GetNativeWindow().GetNativeNSWindow()) return; // Remove current parent window. RemoveChildFromParentWindow(); // Set new parent window. if (new_parent) { new_parent->add_child_window(this); if (attach) new_parent->AttachChildren(); } NativeWindow::SetParentWindow(new_parent); } void NativeWindowMac::SetForwardMouseMessages(bool forward) { [window_ setAcceptsMouseMovedEvents:forward]; } gfx::Rect NativeWindowMac::GetWindowControlsOverlayRect() { if (titlebar_overlay_ && buttons_proxy_ && window_button_visibility_.value_or(true)) { NSRect buttons = [buttons_proxy_ getButtonsContainerBounds]; gfx::Rect overlay; overlay.set_width(GetContentSize().width() - NSWidth(buttons)); if ([buttons_proxy_ useCustomHeight]) { overlay.set_height(titlebar_overlay_height()); } else { overlay.set_height(NSHeight(buttons)); } if (!base::i18n::IsRTL()) overlay.set_x(NSMaxX(buttons)); return overlay; } return gfx::Rect(); } // static NativeWindow* NativeWindow::Create(const gin_helper::Dictionary& options, NativeWindow* parent) { return new NativeWindowMac(options, parent); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
39,614
[Bug]: non-fullscreenable, non-resizable child windows get fullscreened when being shown if the parent window is fullscreened
### 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 26.0.0 ### What operating system are you using? macOS ### Operating System Version macOS Ventura 13.2.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior I expect that if a child window that's configured to be non-fullscreenable is shown while the parent window is fullscreened, the child window won't get fullscreened. ### Actual Behavior Child window opens fullscreened for some reason and the main window crashes when the child is closed. ### Testcase Gist URL https://gist.github.com/pushkin-/3b4bcdb219eee85789e95f6d94ec8a92 ### Additional Information 1. full screen main window 2. click open window 3. notice that child window is fullscreened even though it shouldn't be able to get fullscreen 4. closing the window makes the parent window go black seems like the invocation of `BrowserWindow::show()` causes the `enter-full-screen` event to get emitted for some reason. https://github.com/electron/electron/assets/6374473/f96e2680-4938-4de6-b562-94f80c46ecfb
https://github.com/electron/electron/issues/39614
https://github.com/electron/electron/pull/39620
2affecd4dd26b9f0cf2644ec115635559f920480
33e66b5cd02d2b258b956022c482024c74c13b4b
2023-08-22T22:41:12Z
c++
2023-08-24T20:54:08Z
spec/api-browser-window-spec.ts
import { expect } from 'chai'; import * as childProcess from 'node:child_process'; import * as path from 'node:path'; import * as fs from 'node:fs'; import * as qs from 'node:querystring'; import * as http from 'node:http'; import * as os from 'node:os'; import { AddressInfo } from 'node:net'; import { app, BrowserWindow, BrowserView, dialog, ipcMain, OnBeforeSendHeadersListenerDetails, protocol, screen, webContents, webFrameMain, session, WebContents, WebFrameMain } from 'electron/main'; import { emittedUntil, emittedNTimes } from './lib/events-helpers'; import { ifit, ifdescribe, defer, listen } from './lib/spec-helpers'; import { closeWindow, closeAllWindows } from './lib/window-helpers'; import { areColorsSimilar, captureScreen, HexColors, getPixelColor } from './lib/screen-helpers'; import { once } from 'node:events'; import { setTimeout } from 'node:timers/promises'; const fixtures = path.resolve(__dirname, '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', () => { it('sets the correct class name on the prototype', () => { expect(BrowserWindow.prototype.constructor.name).to.equal('BrowserWindow'); }); 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(fixtures, 'apps', 'xwindow-icon'); const appProcess = childProcess.spawn(process.execPath, [appPath]); await once(appProcess, 'exit'); }); 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. const wr = new WeakRef(w); await setTimeout(); // 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 setTimeout(); expect(wr.deref()).to.not.be.undefined(); }); }); describe('BrowserWindow.close()', () => { let w: 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 = once(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 = once(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 allow access to id after destruction', async () => { const closed = once(w, 'closed'); w.destroy(); await closed; expect(w.id).to.be.a('number'); }); it('should emit unload handler', async () => { await w.loadFile(path.join(fixtures, 'api', 'unload.html')); const closed = once(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 once(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 = once(w, 'closed'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' }); w.close(); await closed; }); describe('when invoked synchronously inside navigation observer', () => { let server: http.Server; let url: string; before(async () => { 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}`); } }); url = (await listen(server)).url; }); 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 = once(w.webContents, 'destroyed'); w.webContents.loadURL(url + path); await destroyed; }); } }); }); describe('window.close()', () => { let w: 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 once(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 once(w.webContents, 'before-unload-fired'); }); }); describe('BrowserWindow.destroy()', () => { let w: 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: 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: http.Server; let url: string; let postData = null as any; before(async () => { 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(req.url && req.url.includes('slow') ? 200 : 0).then(respond); }); url = (await listen(server)).url; }); after(() => { server.close(); }); it('should emit did-start-loading event', async () => { const didStartLoading = once(w.webContents, 'did-start-loading'); w.loadURL('about:blank'); await didStartLoading; }); it('should emit ready-to-show event', async () => { const readyToShow = once(w, 'ready-to-show'); w.loadURL('about:blank'); await readyToShow; }); // DISABLED-FIXME(deepak1556): The error code now seems to be `ERR_FAILED`, verify what // changed and adjust the test. it('should emit did-fail-load event for files that do not exist', async () => { const didFailLoad = once(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 = once(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 not emit did-fail-load for a successfully loaded media file', async () => { w.webContents.on('did-fail-load', () => { expect.fail('did-fail-load should not emit on media file loads'); }); const mediaStarted = once(w.webContents, 'media-started-playing'); w.loadFile(path.join(fixtures, 'cat-spin.mp4')); await mediaStarted; }); it('should set `mainFrame = false` on did-fail-load events in iframes', async () => { const didFailLoad = once(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 = once(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: 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: http.Server; let url: string; before(async () => { server = http.createServer((req, res) => { if (req.url === '/navigate-top') { res.end('<a target=_top href="/">navigate _top</a>'); } else { res.end(''); } }); url = (await listen(server)).url; }); after(() => { server.close(); }); it('allows the window to be closed from the event listener', async () => { const event = once(w.webContents, 'will-navigate'); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); await event; w.close(); }); 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 () => { w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-top"></iframe>`); await emittedUntil(w.webContents, 'did-frame-finish-load', (e: any, isMainFrame: boolean) => !isMainFrame); let initiator: WebFrameMain | undefined; w.webContents.on('will-navigate', (e) => { initiator = e.initiator; }); const subframe = w.webContents.mainFrame.frames[0]; subframe.executeJavaScript('document.getElementsByTagName("a")[0].click()', true); await once(w.webContents, 'did-navigate'); expect(initiator).not.to.be.undefined(); expect(initiator).to.equal(subframe); }); }); describe('will-frame-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 if (req.url === '/navigate-iframe') { res.end('<a href="/test">navigate iframe</a>'); } else if (req.url === '/navigate-iframe?navigated') { res.end('Successfully navigated'); } else if (req.url === '/navigate-iframe-immediately') { res.end(` <script type="text/javascript" charset="utf-8"> location.href += '?navigated' </script> `); } else if (req.url === '/navigate-iframe-immediately?navigated') { res.end('Successfully navigated'); } 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-frame-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-frame-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('can be prevented when navigating subframe', (done) => { let willNavigate = false; w.webContents.on('did-frame-navigate', (_event, _url, _httpResponseCode, _httpStatusText, isMainFrame, frameProcessId, frameRoutingId) => { if (isMainFrame) return; w.webContents.once('will-frame-navigate', (e) => { willNavigate = true; e.preventDefault(); }); w.webContents.on('did-stop-loading', () => { const frame = webFrameMain.fromId(frameProcessId, frameRoutingId); expect(frame).to.not.be.undefined(); if (willNavigate) { // i.e. it shouldn't have had '?navigated' appended to it. try { expect(frame!.url.endsWith('/navigate-iframe-immediately')).to.be.true(); done(); } catch (e) { done(e); } } }); }); w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-iframe-immediately"></iframe>`); }); 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-frame-navigate', (e) => { e.preventDefault(); resolve(e.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-frame-navigate', (e) => { e.preventDefault(); resolve(e.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 setTimeout(1000); let willFrameNavigateEmitted = false; let isMainFrameValue; w.webContents.on('will-frame-navigate', (event) => { willFrameNavigateEmitted = true; isMainFrameValue = event.isMainFrame; }); const didNavigatePromise = once(w.webContents, 'did-navigate'); 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); await didNavigatePromise; expect(willFrameNavigateEmitted).to.be.true(); expect(isMainFrameValue).to.be.true(); }); it('is triggered when a cross-origin iframe navigates itself', async () => { await w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-iframe"></iframe>`); await setTimeout(1000); let willNavigateEmitted = false; let isMainFrameValue; w.webContents.on('will-frame-navigate', (event) => { willNavigateEmitted = true; isMainFrameValue = event.isMainFrame; }); const didNavigatePromise = once(w.webContents, 'did-frame-navigate'); 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); await didNavigatePromise; expect(willNavigateEmitted).to.be.true(); expect(isMainFrameValue).to.be.false(); }); it('can cancel when a cross-origin iframe navigates itself', async () => { }); }); describe('will-redirect event', () => { let server: http.Server; let url: string; before(async () => { 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(); } }); url = (await listen(server)).url; }); after(() => { server.close(); }); it('is emitted on redirects', async () => { const willRedirect = once(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 = once(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 = once(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', async () => { const event = once(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await event; w.close(); }); 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('ordering', () => { let server = null as unknown as http.Server; let url = null as unknown as string; const navigationEvents = [ 'did-start-navigation', 'did-navigate-in-page', 'will-frame-navigate', 'will-navigate', 'will-redirect', 'did-redirect-navigation', 'did-frame-navigate', 'did-navigate' ]; before((done) => { server = http.createServer((req, res) => { if (req.url === '/navigate') { res.end('<a href="/">navigate</a>'); } else if (req.url === '/redirect') { res.end('<a href="/redirect2">redirect</a>'); } else if (req.url === '/redirect2') { res.statusCode = 302; res.setHeader('location', url); res.end(); } else if (req.url === '/in-page') { res.end('<a href="#in-page">redirect</a><div id="in-page"></div>'); } else { res.end(''); } }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/`; done(); }); }); it('for initial navigation, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'did-frame-navigate', 'did-navigate' ]; const allEvents = Promise.all(navigationEvents.map(event => once(w.webContents, event).then(() => firedEvents.push(event)) )); const timeout = setTimeout(1000); w.loadURL(url); await Promise.race([allEvents, timeout]); expect(firedEvents).to.deep.equal(expectedEventOrder); }); it('for second navigation, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'will-frame-navigate', 'will-navigate', 'did-frame-navigate', 'did-navigate' ]; w.loadURL(`${url}navigate`); await once(w.webContents, 'did-navigate'); await setTimeout(2000); Promise.all(navigationEvents.map(event => once(w.webContents, event).then(() => firedEvents.push(event)) )); const navigationFinished = once(w.webContents, 'did-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: pageTarget.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); await navigationFinished; expect(firedEvents).to.deep.equal(expectedEventOrder); }); it('when navigating with redirection, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'will-frame-navigate', 'will-navigate', 'will-redirect', 'did-redirect-navigation', 'did-frame-navigate', 'did-navigate' ]; w.loadURL(`${url}redirect`); await once(w.webContents, 'did-navigate'); await setTimeout(2000); Promise.all(navigationEvents.map(event => once(w.webContents, event).then(() => firedEvents.push(event)) )); const navigationFinished = once(w.webContents, 'did-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: pageTarget.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); await navigationFinished; expect(firedEvents).to.deep.equal(expectedEventOrder); }); it('when navigating in-page, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'did-navigate-in-page' ]; w.loadURL(`${url}in-page`); await once(w.webContents, 'did-navigate'); await setTimeout(2000); Promise.all(navigationEvents.map(event => once(w.webContents, event).then(() => firedEvents.push(event)) )); const navigationFinished = once(w.webContents, 'did-navigate-in-page'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: pageTarget.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); await navigationFinished; expect(firedEvents).to.deep.equal(expectedEventOrder); }); }); }); } describe('focus and visibility', () => { let w: 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', async () => { const p = once(w, 'focus'); w.show(); await p; expect(w.isFocused()).to.equal(true); }); it('should make the window visible', async () => { const p = once(w, 'focus'); w.show(); await p; expect(w.isVisible()).to.equal(true); }); it('emits when window is shown', async () => { const show = once(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 = once(w, 'show'); w.show(); await shown; const hidden = once(w, 'hide'); w.hide(); await hidden; expect(w.isVisible()).to.equal(false); }); }); describe('BrowserWindow.minimize()', () => { // TODO(codebytere): Enable for Linux once maximize/minimize events work in CI. ifit(process.platform !== 'linux')('should not be visible when the window is minimized', async () => { const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMinimized()).to.equal(true); 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 = once(w, 'maximize'); const shown = once(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 setTimeout(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); }); ifit(process.platform !== 'win32')('focuses a blurred window', async () => { { const isBlurred = once(w, 'blur'); const isShown = once(w, 'show'); w.show(); w.blur(); await isShown; await isBlurred; } expect(w.isFocused()).to.equal(false); w.focus(); expect(w.isFocused()).to.equal(true); }); ifit(process.platform !== 'linux')('acquires focus status from the other windows', async () => { const w1 = new BrowserWindow({ show: false }); const w2 = new BrowserWindow({ show: false }); const w3 = new BrowserWindow({ show: false }); { const isFocused3 = once(w3, 'focus'); const isShown1 = once(w1, 'show'); const isShown2 = once(w2, 'show'); const isShown3 = once(w3, 'show'); w1.show(); w2.show(); w3.show(); await isShown1; await isShown2; await isShown3; await isFocused3; } // TODO(RaisinTen): Investigate why this assertion fails only on Linux. expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); w1.focus(); expect(w1.isFocused()).to.equal(true); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(false); w2.focus(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(true); expect(w3.isFocused()).to.equal(false); w3.focus(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); { const isClosed1 = once(w1, 'closed'); const isClosed2 = once(w2, 'closed'); const isClosed3 = once(w3, 'closed'); w1.destroy(); w2.destroy(); w3.destroy(); await isClosed1; await isClosed2; await isClosed3; } }); }); // TODO(RaisinTen): Make this work on Windows too. // Refs: https://github.com/electron/electron/issues/20464. ifdescribe(process.platform !== 'win32')('BrowserWindow.blur()', () => { it('removes focus from window', async () => { { const isFocused = once(w, 'focus'); const isShown = once(w, 'show'); w.show(); await isShown; await isFocused; } expect(w.isFocused()).to.equal(true); w.blur(); expect(w.isFocused()).to.equal(false); }); ifit(process.platform !== 'linux')('transfers focus status to the next window', async () => { const w1 = new BrowserWindow({ show: false }); const w2 = new BrowserWindow({ show: false }); const w3 = new BrowserWindow({ show: false }); { const isFocused3 = once(w3, 'focus'); const isShown1 = once(w1, 'show'); const isShown2 = once(w2, 'show'); const isShown3 = once(w3, 'show'); w1.show(); w2.show(); w3.show(); await isShown1; await isShown2; await isShown3; await isFocused3; } // TODO(RaisinTen): Investigate why this assertion fails only on Linux. expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); w3.blur(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(true); expect(w3.isFocused()).to.equal(false); w2.blur(); expect(w1.isFocused()).to.equal(true); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(false); w1.blur(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); { const isClosed1 = once(w1, 'closed'); const isClosed2 = once(w2, 'closed'); const isClosed3 = once(w3, 'closed'); w1.destroy(); w2.destroy(); w3.destroy(); await isClosed1; await isClosed2; await isClosed3; } }); }); describe('BrowserWindow.getFocusedWindow()', () => { it('returns the opener window when dev tools window is focused', async () => { const p = once(w, 'focus'); w.show(); await p; w.webContents.openDevTools({ mode: 'undocked' }); await once(w.webContents, 'devtools-focused'); expect(BrowserWindow.getFocusedWindow()).to.equal(w); }); }); describe('BrowserWindow.moveTop()', () => { afterEach(closeAllWindows); it('should not steal focus', async () => { const posDelta = 50; const wShownInactive = once(w, 'show'); w.showInactive(); await wShownInactive; expect(w.isFocused()).to.equal(false); const otherWindow = new BrowserWindow({ show: false, title: 'otherWindow' }); const otherWindowShown = once(otherWindow, 'show'); const otherWindowFocused = once(otherWindow, 'focus'); otherWindow.show(); await otherWindowShown; await otherWindowFocused; expect(otherWindow.isFocused()).to.equal(true); w.moveTop(); const wPos = w.getPosition(); const wMoving = once(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 = once(w, 'focus'); const otherWindowBlurred = once(otherWindow, 'blur'); w.focus(); await wFocused; await otherWindowBlurred; expect(w.isFocused()).to.equal(true); otherWindow.moveTop(); const otherWindowPos = otherWindow.getPosition(); const otherWindowMoving = once(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); }); it('should not crash when called on a modal child window', async () => { const shown = once(w, 'show'); w.show(); await shown; const child = new BrowserWindow({ modal: true, parent: w }); expect(() => { child.moveTop(); }).to.not.throw(); }); }); describe('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 = once(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 = once(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: 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 = { ...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(once(w, 'resized')).to.eventually.be.fulfilled(); }); }); }); describe('BrowserWindow.setSize(width, height)', () => { it('sets the window size', async () => { const size = [300, 400]; const resized = once(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(once(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 = once(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 = once(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 = once(w, 'resize'); w.setContentBounds(bounds); await resize; await setTimeout(); 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 = once(w, 'resize'); w.setContentBounds(bounds); await resize; await setTimeout(); 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); }); it('returns correct color with multiple passed formats', () => { w.destroy(); w = new BrowserWindow({}); w.setBackgroundColor('#AABBFF'); expect(w.getBackgroundColor()).to.equal('#AABBFF'); w.setBackgroundColor('blueviolet'); expect(w.getBackgroundColor()).to.equal('#8A2BE2'); w.setBackgroundColor('rgb(255, 0, 185)'); expect(w.getBackgroundColor()).to.equal('#FF00B9'); w.setBackgroundColor('rgba(245, 40, 145, 0.8)'); expect(w.getBackgroundColor()).to.equal('#F52891'); w.setBackgroundColor('hsl(155, 100%, 50%)'); expect(w.getBackgroundColor()).to.equal('#00FF95'); }); }); describe('BrowserWindow.getNormalBounds()', () => { describe('Normal state', () => { it('checks normal bounds after resize', async () => { const size = [300, 400]; const resize = once(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 = once(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 = once(w, 'maximize'); w.show(); w.maximize(); await maximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after resize and maximize', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('updates normal bounds after move and maximize', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('checks normal bounds when unmaximized', async () => { const bounds = w.getBounds(); w.once('maximize', () => { w.unmaximize(); }); const unmaximize = once(w, 'unmaximize'); w.show(); w.maximize(); await unmaximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('correctly reports maximized state after maximizing then minimizing', async () => { w.destroy(); w = new BrowserWindow({ show: false }); w.show(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMaximized()).to.equal(false); expect(w.isMinimized()).to.equal(true); }); it('correctly reports maximized state after maximizing then fullscreening', async () => { w.destroy(); w = new BrowserWindow({ show: false }); w.show(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; expect(w.isMaximized()).to.equal(false); expect(w.isFullScreen()).to.equal(true); }); it('checks normal bounds for maximized transparent window', async () => { w.destroy(); w = new BrowserWindow({ transparent: true, show: false }); w.show(); const bounds = w.getNormalBounds(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; 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 = once(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 = once(w, 'maximize'); w.show(); w.maximize(); await maximize; expect(w.isMaximized()).to.equal(true); const unmaximize = once(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 = once(w, 'maximize'); 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 = once(w, 'minimize'); w.show(); w.minimize(); await minimize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after move and minimize', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const minimize = once(w, 'minimize'); w.minimize(); await minimize; const normal = w.getNormalBounds(); expect(original).to.deep.equal(normal); expectBoundsEqual(normal, w.getBounds()); }); it('updates normal bounds after resize and minimize', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const minimize = once(w, 'minimize'); w.minimize(); await minimize; const normal = w.getNormalBounds(); expect(original).to.deep.equal(normal); expectBoundsEqual(normal, w.getBounds()); }); it('checks normal bounds when restored', async () => { const bounds = w.getBounds(); w.once('minimize', () => { w.restore(); }); const restore = once(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 = once(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('does not go fullscreen if roundedCorners are enabled', async () => { w = new BrowserWindow({ frame: false, roundedCorners: false, fullscreen: true }); expect(w.fullScreen).to.be.false(); }); 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 = once(w, 'enter-full-screen'); w.show(); w.fullScreen = true; await enterFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after resize and fullscreen', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.fullScreen = true; await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('updates normal bounds after move and fullscreen', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.fullScreen = true; await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('checks normal bounds when unfullscreen\'ed', async () => { const bounds = w.getBounds(); w.once('enter-full-screen', () => { w.fullScreen = false; }); const leaveFullScreen = once(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 = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after resize and fullscreen', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.setFullScreen(true); await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('updates normal bounds after move and fullscreen', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.setFullScreen(true); await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('checks normal bounds when unfullscreen\'ed', async () => { const bounds = w.getBounds(); w.show(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); }); }); }); ifdescribe(process.platform === 'darwin')('tabbed windows', () => { let w: 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.showAllTabs()', () => { it('does not throw', () => { expect(() => { w.showAllTabs(); }).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); }); ifit(process.platform === 'darwin')('honors the stayHidden argument', async () => { const w = new BrowserWindow({ webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.hide(); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } await w.capturePage({ x: 0, y: 0, width: 0, height: 0 }, { stayHidden: true }); const visible = await w.webContents.executeJavaScript('document.visibilityState'); expect(visible).to.equal('hidden'); }); it('resolves after the window is hidden', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixtures, 'pages', 'a.html')); await once(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('resolves after the window is hidden and capturer count is non-zero', async () => { const w = new BrowserWindow({ show: false }); w.webContents.setBackgroundThrottling(false); w.loadFile(path.join(fixtures, 'pages', 'a.html')); await once(w, 'ready-to-show'); const image = await w.capturePage(); expect(image.isEmpty()).to.equal(false); }); it('preserves transparency', async () => { const w = new BrowserWindow({ show: false, transparent: true }); w.loadFile(path.join(fixtures, 'pages', 'theme-color.html')); await once(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: 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: 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', async () => { expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); const minimized = once(w, 'minimize'); w.minimize(); await minimized; expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); const restored = once(w, 'restore'); w.restore(); await restored; 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 = once(w, 'always-on-top-changed') as Promise<[any, boolean]>; 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: BrowserWindow; let server: http.Server; let url: 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++; }); url = (await listen(server)).url; }); 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 = once(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: 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); }); it('correctly updates when entering/exiting fullscreen for hidden style', async () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hidden' }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; const leaveFS = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFS; w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); it('correctly updates when entering/exiting fullscreen for hiddenInset style', async () => { 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); const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; const leaveFS = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFS; w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setVibrancy(type)', () => { afterEach(closeAllWindows); it('allows setting, changing, and removing the vibrancy', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setVibrancy('titlebar'); w.setVibrancy('selection'); w.setVibrancy(null); w.setVibrancy('menu'); 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(); }); }); ifdescribe(process.platform === 'darwin')('trafficLightPosition', () => { const pos = { x: 10, y: 10 }; afterEach(closeAllWindows); describe('BrowserWindow.getWindowButtonPosition(pos)', () => { it('returns null when there is no custom position', () => { const w = new BrowserWindow({ show: false }); expect(w.getWindowButtonPosition()).to.be.null('getWindowButtonPosition'); }); it('gets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); expect(w.getWindowButtonPosition()).to.deep.equal(pos); }); it('gets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); expect(w.getWindowButtonPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setWindowButtonPosition(pos)', () => { it('resets the position when null is passed', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); w.setWindowButtonPosition(null); expect(w.getWindowButtonPosition()).to.be.null('setWindowButtonPosition'); }); it('sets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setWindowButtonPosition(newPos); expect(w.getWindowButtonPosition()).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.setWindowButtonPosition(newPos); expect(w.getWindowButtonPosition()).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('Opening a BrowserWindow from a link', () => { let appProcess: childProcess.ChildProcessWithoutNullStreams | undefined; afterEach(() => { if (appProcess && !appProcess.killed) { appProcess.kill(); appProcess = undefined; } }); it('can properly open and load a new window from a link', async () => { const appPath = path.join(__dirname, 'fixtures', 'apps', 'open-new-window-from-link'); appProcess = childProcess.spawn(process.execPath, [appPath]); const [code] = await once(appProcess, 'exit'); expect(code).to.equal(0); }); }); 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 typeof ElectronInternal.WebContents).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.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 = once(w.webContents, 'did-attach-webview'); const [, webviewContents] = await once(app, 'web-contents-created') as [any, WebContents]; expect(BrowserWindow.fromWebContents(webviewContents)!.id).to.equal(w.id); await p; }); it('is usable immediately on browser-window-created', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.executeJavaScript('window.open(""); null'); const [win, winFromWebContents] = await new Promise<any>((resolve) => { app.once('browser-window-created', (e, win) => { resolve([win, BrowserWindow.fromWebContents(win.webContents)]); }); }); expect(winFromWebContents).to.equal(win); }); }); 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.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.destroy(); bv2.webContents.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.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(['win32', 'darwin'].includes(process.platform))('"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 = once(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 = once(ipcMain, 'geometrychange'); w.setBounds({ width: 800 }); const [, newOverlayRect] = await geometryChange; expect(newOverlayRect.width).to.equal(overlayRect.width + 400); }; afterEach(async () => { await closeAllWindows(); 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')('when an invalid titleBarStyle is initially set', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { color: '#0000f0', symbolColor: '#ffffff' }, titleBarStyle: 'hiddenInset' }); }); afterEach(async () => { await closeAllWindows(); }); it('does not crash changing minimizability ', () => { expect(() => { w.setMinimizable(false); }).to.not.throw(); }); it('does not crash changing maximizability', () => { expect(() => { w.setMaximizable(false); }).to.not.throw(); }); }); }); ifdescribe(['win32', 'darwin'].includes(process.platform))('"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 = once(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()'); if (!w.isMaximized()) { const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; } expect(w.isMaximized()).to.be.true('not maximized'); 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(async () => { await closeAllWindows(); ipcMain.removeAllListeners('geometrychange'); }); it('sets Window Control Overlay with title bar height of 40', async () => { await testWindowsOverlayHeight(40); }); }); ifdescribe(process.platform === 'win32')('BrowserWindow.setTitlebarOverlay', () => { afterEach(async () => { await closeAllWindows(); ipcMain.removeAllListeners('geometrychange'); }); it('does not crash when an invalid titleBarStyle was initially set', () => { const win = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { color: '#0000f0', symbolColor: '#ffffff' }, titleBarStyle: 'hiddenInset' }); expect(() => { win.setTitleBarOverlay({ color: '#000000' }); }).to.not.throw(); }); it('correctly updates the height of the overlay', async () => { const testOverlay = async (w: BrowserWindow, size: Number, firstRun: boolean) => { const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); const overlayReady = once(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); if (firstRun) { await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const { height: preMaxHeight } = await w.webContents.executeJavaScript('getJSOverlayProperties()'); if (!w.isMaximized()) { const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; } expect(w.isMaximized()).to.be.true('not maximized'); const { x, y, width, height } = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(x).to.equal(0); expect(y).to.equal(0); expect(width).to.be.greaterThan(0); expect(height).to.equal(size); expect(preMaxHeight).to.equal(size); }; const INITIAL_SIZE = 40; const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden', webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { height: INITIAL_SIZE } }); await testOverlay(w, INITIAL_SIZE, true); w.setTitleBarOverlay({ height: INITIAL_SIZE + 10 }); await testOverlay(w, INITIAL_SIZE + 10, false); }); }); 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-next-line no-new */ new BrowserWindow({ tabbingIdentifier: 'group1' }); /* eslint-disable-next-line no-new */ new BrowserWindow({ tabbingIdentifier: 'group2', frame: false }); }).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 once(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 once(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 once(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-isolated 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 once(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 once(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 once(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 once(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 once(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 once(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; let serverUrl: string; before(async () => { 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}`); } }); serverUrl = (await listen(server)).url; }); 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 once(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 once(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 once(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 once(ipcMain, 'answer'); const expectedUrl = process.platform === 'win32' ? 'file:///' + htmlPath.replace(/\\/g, '/') : pageUrl; expect(url).to.equal(expectedUrl); }); it('exposes full EventEmitter object to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload: path.join(fixtures, 'module', 'preload-eventemitter.js') } }); w.loadURL('about:blank'); const [, rendererEventEmitterProperties] = await once(ipcMain, 'answer'); const { EventEmitter } = require('node:events'); const emitter = new EventEmitter(); const browserEventEmitterProperties = []; let currentObj = emitter; do { browserEventEmitterProperties.push(...Object.getOwnPropertyNames(currentObj)); } while ((currentObj = Object.getPrototypeOf(currentObj))); expect(rendererEventEmitterProperties).to.deep.equal(browserEventEmitterProperties); }); 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 = once(ipcMain, 'answer'); w.loadURL(pageUrl); const [, { url, frameName, options }] = await once(w.webContents, 'did-create-window') as [BrowserWindow, Electron.DidCreateWindowDetails]; 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 once(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 once(app, 'browser-window-created') as [any, BrowserWindow]; // Ask the popup window for details. const detailsAnswer = once(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 = once(ipcMain, 'answer'); w.webContents.send('touch-the-popup'); const [, popupAccessMessage] = await touchPopupResult; // Ask the popup to access the opener. const touchOpenerResult = once(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 once(ipcMain, 'answer'); expect(argv).to.include('--enable-sandbox'); }); it('should open windows with the options configured via setWindowOpenHandler handlers', 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([ once(app, 'web-contents-created') as Promise<[any, WebContents]>, once(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 => once(ipcMain, name))); w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'verify-ipc-sender' }); await done; }); describe('event handling', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); }); it('works for window events', async () => { const pageTitleUpdated = once(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 => once(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 => once(w.webContents, name))); w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'webcontents-events' }); await done; }); }); 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 once(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'); expect(test.nodeEvents).to.equal(true); expect(test.nodeTimers).to.equal(true); expect(test.nodeUrl).to.equal(true); 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 = once(w.webContents, 'did-attach-webview') as Promise<[any, WebContents]>; const webviewDomReady = once(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; 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 = once(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 = once(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 = once(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 = once(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 once(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 once(ipcMain, 'answer'); expect(content).to.equal('function'); } w.reload(); { const [, content] = await once(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, preload } } })); const webviewLoaded = once(ipcMain, 'webview-loaded'); w.loadFile(path.join(fixtures, 'api', 'new-window-webview.html')); await webviewLoaded; }); it('should open windows with the options configured via setWindowOpenHandler handlers', 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([ once(app, 'web-contents-created') as Promise<[any, WebContents]>, once(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 once(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 once(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 = once(w.webContents, 'enter-html-full-screen'); w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true); await enterHtmlFullScreen; expect(w.getSize()).to.deep.equal(size); }); }); describe('"defaultFontFamily" option', () => { it('can change the standard font family', async () => { const w = new BrowserWindow({ show: false, webPreferences: { defaultFontFamily: { standard: 'Impact' } } }); await w.loadFile(path.join(fixtures, 'pages', 'content.html')); const fontFamily = await w.webContents.executeJavaScript("window.getComputedStyle(document.getElementsByTagName('p')[0])['font-family']", true); expect(fontFamily).to.equal('Impact'); }); }); }); describe('beforeunload handler', function () { let w: 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 = once(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 once(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 once(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 once(w.webContents, 'console-message'); w.close(); await once(w.webContents, 'before-unload-fired'); w.close(); await once(w.webContents, 'before-unload-fired'); w.webContents.removeListener('destroyed', destroyListener); const wait = once(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 once(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 once(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 once(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'); }); }); // TODO(codebytere): figure out how to make these pass in CI on Windows. ifdescribe(process.platform !== 'win32')('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 once(ipcMain, 'pong'); expect(readyToShow).to.be.false('ready to show'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); }); it('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 once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.hide(); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } }); it('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 once(w, 'show'); } w.hide(); w.show(); const [, visibilityState] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); }); it('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 once(w, 'show'); } w.hide(); w.showInactive(); const [, visibilityState] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); }); 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 once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.minimize(); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } }); it('visibilityState remains visible if backgroundThrottling is disabled', async () => { const w = new BrowserWindow({ show: false, width: 100, height: 100, webPreferences: { backgroundThrottling: false, nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await once(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 = once(w, 'show'); w.show(); await shown1; const hidden = once(w, 'hide'); w.hide(); await hidden; const shown2 = once(w, 'show'); w.show(); await shown2; } finally { ipcMain.removeAllListeners('pong'); } }); }); 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 = once(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 = once(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 = once(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 = once(w, 'maximize'); const unmaximize = once(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 = once(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 }); let called = false; w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); w.webContents.on('dom-ready', () => { w.webContents.beginFrameSubscription(function () { // This callback might be called twice. if (called) return; called = true; // Pending endFrameSubscription to next tick can reliably reproduce // a crash which happens when nothing is returned in the callback. setTimeout().then(() => { 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 () => { /* Use temp directory for saving MHTML file since the write handle * gets passed to untrusted process and chromium will deny exec access to * the path. To perform this task, chromium requires that the path is one * of the browser controlled paths, refs https://chromium-review.googlesource.com/c/chromium/src/+/3774416 */ const tmpDir = await fs.promises.mkdtemp(path.resolve(os.tmpdir(), 'electron-mhtml-save-')); const savePageMHTMLPath = path.join(tmpDir, 'save_page.html'); const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageMHTMLPath, 'MHTML'); expect(fs.existsSync(savePageMHTMLPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.false('js path'); expect(fs.existsSync(savePageCssPath)).to.be.false('css path'); try { await fs.promises.unlink(savePageMHTMLPath); await fs.promises.rmdir(tmpDir); } catch {} }); 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(); }); // TODO(zcbenz): // This test does not run on Linux CI. See: // https://github.com/electron/electron/issues/28699 ifit(process.platform === 'linux' && !process.env.CI)('should bring a minimized maximized window back to maximized state', async () => { const w = new BrowserWindow({}); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMaximized()).to.equal(false); const restore = once(w, 'restore'); w.restore(); await restore; expect(w.isMaximized()).to.equal(true); }); }); // TODO(dsanders11): Enable once maximize event works on Linux again on CI ifdescribe(process.platform !== 'linux')('BrowserWindow.maximize()', () => { afterEach(closeAllWindows); it('should show the window if it is not currently shown', async () => { const w = new BrowserWindow({ show: false }); const hidden = once(w, 'hide'); let shown = once(w, 'show'); const maximize = once(w, 'maximize'); expect(w.isVisible()).to.be.false('visible'); w.maximize(); await maximize; await shown; expect(w.isMaximized()).to.be.true('maximized'); expect(w.isVisible()).to.be.true('visible'); // Even if the window is already maximized w.hide(); await hidden; expect(w.isVisible()).to.be.false('visible'); shown = once(w, 'show'); w.maximize(); await shown; expect(w.isVisible()).to.be.true('visible'); }); }); 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 = once(w, 'minimize'); w.minimize(); await minimize; w.unmaximize(); await setTimeout(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 setTimeout(1000); expectBoundsEqual(w.getSize(), initialSize); expectBoundsEqual(w.getPosition(), initialPosition); }); ifit(process.platform === 'darwin')('should not change size or position of a window which is functionally maximized', async () => { const { workArea } = screen.getPrimaryDisplay(); const bounds = { x: workArea.x, y: workArea.y, width: workArea.width, height: workArea.height }; const w = new BrowserWindow(bounds); w.unmaximize(); await setTimeout(1000); expectBoundsEqual(w.getBounds(), bounds); }); }); 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 = once(w, 'show'); // start fullscreen and hidden w.setFullScreen(true); w.show(); await shown; const leftFullScreen = once(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 = once(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 once(w, 'enter-full-screen'); // Wait a tick for the full-screen state to 'stick' await setTimeout(); w.setFullScreen(false); await once(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 = once(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 = once(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 = once(c, 'closed'); c.close(); await closed; // The child window list is not immediately cleared, so wait a tick until it's ready. await setTimeout(); expect(w.getChildWindows().length).to.equal(0); }); it('can handle child window close and reparent multiple times', async () => { const w = new BrowserWindow({ show: false }); let c: BrowserWindow | null; for (let i = 0; i < 5; i++) { c = new BrowserWindow({ show: false, parent: w }); const closed = once(c, 'closed'); c.close(); await closed; } await setTimeout(); expect(w.getChildWindows().length).to.equal(0); }); ifit(process.platform === 'darwin')('child window matches visibility when visibility changes', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); const wShow = once(w, 'show'); const cShow = once(c, 'show'); w.show(); c.show(); await Promise.all([wShow, cShow]); const minimized = once(w, 'minimize'); w.minimize(); await minimized; expect(w.isVisible()).to.be.false('parent is visible'); expect(c.isVisible()).to.be.false('child is visible'); const restored = once(w, 'restore'); w.restore(); await restored; expect(w.isVisible()).to.be.true('parent is visible'); expect(c.isVisible()).to.be.true('child is visible'); }); ifit(process.platform === 'darwin')('matches child window visibility when visibility changes', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); const wShow = once(w, 'show'); const cShow = once(c, 'show'); w.show(); c.show(); await Promise.all([wShow, cShow]); const minimized = once(c, 'minimize'); c.minimize(); await minimized; expect(c.isVisible()).to.be.false('child is visible'); const restored = once(c, 'restore'); c.restore(); await restored; expect(w.isVisible()).to.be.true('parent is visible'); expect(c.isVisible()).to.be.true('child is visible'); }); it('closes a grandchild window when a middle child window is destroyed', (done) => { const w = new BrowserWindow(); w.loadFile(path.join(fixtures, 'pages', 'base-page.html')); w.webContents.executeJavaScript('window.open("")'); w.webContents.on('did-create-window', async (window) => { const childWindow = new BrowserWindow({ parent: window }); await setTimeout(); window.close(); childWindow.on('closed', () => { expect(() => { BrowserWindow.getFocusedWindow(); }).to.not.throw(); done(); }); }); }); 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 = once(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 setTimeout(); expect(w.getChildWindows().length).to.equal(0); }); ifit(process.platform === 'darwin')('can reparent when the first parent is destroyed', async () => { const w1 = new BrowserWindow({ show: false }); const w2 = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); c.setParentWindow(w1); expect(w1.getChildWindows().length).to.equal(1); const closed = once(w1, 'closed'); w1.destroy(); await closed; c.setParentWindow(w2); await setTimeout(); const children = w2.getChildWindows(); expect(children[0]).to.equal(c); }); }); 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 = once(two, 'show'); two.show(); await twoShown; setTimeout(500).then(() => two.close()); await once(two, 'closed'); }; const one = new BrowserWindow({ width: 600, height: 400, parent: parentWindow, modal: true, show: false }); const oneShown = once(one, 'show'); one.show(); await oneShown; setTimeout(500).then(() => one.destroy()); await once(one, 'closed'); await createTwo(); }); ifit(process.platform !== 'darwin')('can disable and enable a window', () => { const w = new BrowserWindow({ show: false }); w.setEnabled(false); expect(w.isEnabled()).to.be.false('w.isEnabled()'); w.setEnabled(true); expect(w.isEnabled()).to.be.true('!w.isEnabled()'); }); 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 = once(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 = once(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; let serverUrl: string; before(async () => { server = http.createServer((request, response) => { response.end(); }); serverUrl = (await listen(server)).url; }); after(() => { server.close(); }); it('is true when the main frame is loading', async () => { const w = new BrowserWindow({ show: false }); const didStartLoading = once(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 = once(w.webContents, 'did-stop-loading'); w.webContents.loadURL(serverUrl); await didStopLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); const didStartLoading = once(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 = once(w.webContents, 'did-stop-loading'); w.webContents.loadURL(serverUrl); await didStopLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); const didStartLoading = once(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')('when fullscreen state is changed', () => { it('correctly remembers state prior to fullscreen change', async () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); w.setMenuBarVisibility(false); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; expect(w.fullScreen).to.be.true('not fullscreen'); const exitFS = once(w, 'leave-full-screen'); w.setFullScreen(false); await exitFS; expect(w.fullScreen).to.be.false('not fullscreen'); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); }); it('correctly remembers state prior to fullscreen change with autoHide', async () => { const w = new BrowserWindow({ show: false }); expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); w.autoHideMenuBar = true; expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); w.setMenuBarVisibility(false); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; expect(w.fullScreen).to.be.true('not fullscreen'); const exitFS = once(w, 'leave-full-screen'); w.setFullScreen(false); await exitFS; expect(w.fullScreen).to.be.false('not fullscreen'); expect(w.isMenuBarVisible()).to.be.false('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'); }); }); }); ifdescribe(process.platform === 'darwin')('isHiddenInMissionControl state', () => { it('with functions', () => { it('can be set with ignoreMissionControl constructor option', () => { const w = new BrowserWindow({ show: false, hiddenInMissionControl: true }); expect(w.isHiddenInMissionControl()).to.be.true('isHiddenInMissionControl'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isHiddenInMissionControl()).to.be.false('isHiddenInMissionControl'); w.setHiddenInMissionControl(true); expect(w.isHiddenInMissionControl()).to.be.true('isHiddenInMissionControl'); w.setHiddenInMissionControl(false); expect(w.isHiddenInMissionControl()).to.be.false('isHiddenInMissionControl'); }); }); }); // 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 = once(w, 'enter-full-screen'); w.kiosk = true; expect(w.isKiosk()).to.be.true('isKiosk'); await enterFullScreen; await setTimeout(); const leaveFullScreen = once(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 = once(w, 'enter-full-screen'); w.setKiosk(true); expect(w.isKiosk()).to.be.true('isKiosk'); await enterFullScreen; await setTimeout(); const leaveFullScreen = once(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 false and restored', async () => { const w = new BrowserWindow({ resizable: false }); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.resizable).to.be.false('resizable'); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.resizable).to.be.false('resizable'); }); it('default resizable flag should be restored after entering/exiting fullscreen', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.resizable).to.be.false('resizable'); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.resizable).to.be.true('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 = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; }); it('should be able to load a URL while transitioning to fullscreen', async () => { const w = new BrowserWindow({ fullscreen: true }); w.loadFile(path.join(fixtures, 'pages', 'c.html')); const load = once(w.webContents, 'did-finish-load'); const enterFS = once(w, 'enter-full-screen'); await Promise.all([enterFS, load]); expect(w.fullScreen).to.be.true(); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; }); it('can be changed with setFullScreen method', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await setTimeout(); const leaveFullScreen = once(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 setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); }); it('handles several HTML fullscreen transitions', async () => { const w = new BrowserWindow(); await w.loadFile(path.join(fixtures, 'pages', 'a.html')); expect(w.isFullScreen()).to.be.false('is fullscreen'); const enterFullScreen = once(w, 'enter-full-screen'); const leaveFullScreen = once(w, 'leave-full-screen'); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await enterFullScreen; await w.webContents.executeJavaScript('document.exitFullscreen()', true); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); await setTimeout(); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await enterFullScreen; await w.webContents.executeJavaScript('document.exitFullscreen()', true); 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'); const enterFS = emittedNTimes(w, 'enter-full-screen', 2); const leaveFS = emittedNTimes(w, 'leave-full-screen', 2); w.setFullScreen(true); w.setFullScreen(false); w.setFullScreen(true); w.setFullScreen(false); await Promise.all([enterFS, leaveFS]); expect(w.isFullScreen()).to.be.false('not fullscreen'); }); it('handles several chromium-initiated transitions in close proximity', async () => { const w = new BrowserWindow(); await w.loadFile(path.join(fixtures, 'pages', 'a.html')); expect(w.isFullScreen()).to.be.false('is fullscreen'); let enterCount = 0; let exitCount = 0; const done = new Promise<void>(resolve => { const checkDone = () => { if (enterCount === 2 && exitCount === 2) resolve(); }; w.webContents.on('enter-html-full-screen', () => { enterCount++; checkDone(); }); w.webContents.on('leave-html-full-screen', () => { exitCount++; checkDone(); }); }); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await done; }); it('handles HTML fullscreen transitions when fullscreenable is false', async () => { const w = new BrowserWindow({ fullscreenable: false }); await w.loadFile(path.join(fixtures, 'pages', 'a.html')); expect(w.isFullScreen()).to.be.false('is fullscreen'); let enterCount = 0; let exitCount = 0; const done = new Promise<void>((resolve, reject) => { const checkDone = () => { if (enterCount === 2 && exitCount === 2) resolve(); }; w.webContents.on('enter-html-full-screen', async () => { enterCount++; if (w.isFullScreen()) reject(new Error('w.isFullScreen should be false')); const isFS = await w.webContents.executeJavaScript('!!document.fullscreenElement'); if (!isFS) reject(new Error('Document should have fullscreen element')); checkDone(); }); w.webContents.on('leave-html-full-screen', () => { exitCount++; if (w.isFullScreen()) reject(new Error('w.isFullScreen should be false')); checkDone(); }); }); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await expect(done).to.eventually.be.fulfilled(); }); it('does not crash when exiting simpleFullScreen (properties)', async () => { const w = new BrowserWindow(); w.setSimpleFullScreen(true); await setTimeout(1000); w.setFullScreen(!w.isFullScreen()); }); it('does not crash when exiting simpleFullScreen (functions)', async () => { const w = new BrowserWindow(); w.simpleFullScreen = true; await setTimeout(1000); w.setFullScreen(!w.isFullScreen()); }); it('should not be changed by setKiosk method', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setKiosk(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); const leaveFullScreen = once(w, 'leave-full-screen'); w.setKiosk(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('isFullScreen'); }); it('should stay fullscreen if fullscreen before kiosk', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); w.setKiosk(true); w.setKiosk(false); // Wait enough time for a fullscreen change to take effect. await setTimeout(2000); expect(w.isFullScreen()).to.be.true('isFullScreen'); }); it('multiple windows inherit correct fullscreen state', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await setTimeout(1000); const w2 = new BrowserWindow({ show: false }); const enterFullScreen2 = once(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 = once(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(); }); it('should not call BrowserWindow show event', async () => { const w = new BrowserWindow({ show: false }); const shown = once(w, 'show'); w.show(); await shown; let showCalled = false; w.on('show', () => { showCalled = true; }); w.previewFile(__filename); await setTimeout(500); expect(showCalled).to.equal(false, 'should not have called show twice'); }); }); // TODO (jkleinsc) renable these tests on mas arm64 ifdescribe(!process.mas || process.arch !== 'arm64')('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 = once(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 = once(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 = once(app, 'browser-window-created') as Promise<[any, BrowserWindow]>; 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 = once(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 = once(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 = once(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 = once(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 = once(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 = once(w1, 'focus'); w1.webContents.focus(); await w1Focused; expect(w1.webContents.isFocused()).to.be.true('focuses window'); }); }); describe('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 = once(w.webContents, 'paint') as Promise<[any, Electron.Rectangle, Electron.NativeImage]>; 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 = once(w.webContents, 'paint') as Promise<[any, Electron.Rectangle, Electron.NativeImage]>; 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 = once(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 = once(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.stopPainting(); w.webContents.startPainting(); await once(w.webContents, 'paint') as [any, Electron.Rectangle, Electron.NativeImage]; 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 once(w.webContents, 'paint') as [any, Electron.Rectangle, Electron.NativeImage]; expect(w.webContents.getFrameRate()).to.equal(60); }); it('has default frame rate (property)', async () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await once(w.webContents, 'paint') as [any, Electron.Rectangle, Electron.NativeImage]; expect(w.webContents.frameRate).to.equal(60); }); it('sets custom frame rate (function)', async () => { const domReady = once(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.setFrameRate(30); await once(w.webContents, 'paint') as [any, Electron.Rectangle, Electron.NativeImage]; expect(w.webContents.getFrameRate()).to.equal(30); }); it('sets custom frame rate (property)', async () => { const domReady = once(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.frameRate = 30; await once(w.webContents, 'paint') as [any, Electron.Rectangle, Electron.NativeImage]; expect(w.webContents.frameRate).to.equal(30); }); }); }); describe('"transparent" option', () => { afterEach(closeAllWindows); ifit(process.platform !== 'linux')('correctly returns isMaximized() when the window is maximized then minimized', async () => { const w = new BrowserWindow({ frame: false, transparent: true }); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMaximized()).to.be.false(); expect(w.isMinimized()).to.be.true(); }); // 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 once(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 === 'darwin' && process.arch === 'x64')('should not display a visible background', async () => { const display = screen.getPrimaryDisplay(); const backgroundWindow = new BrowserWindow({ ...display.bounds, frame: false, backgroundColor: HexColors.GREEN, hasShadow: false }); await backgroundWindow.loadURL('about:blank'); const foregroundWindow = new BrowserWindow({ ...display.bounds, show: true, transparent: true, frame: false, hasShadow: false }); const colorFile = path.join(__dirname, 'fixtures', 'pages', 'half-background-color.html'); await foregroundWindow.loadFile(colorFile); await setTimeout(1000); 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, HexColors.GREEN)).to.be.true(); expect(areColorsSimilar(rightHalfColor, HexColors.RED)).to.be.true(); }); ifit(process.platform === 'darwin')('Allows setting a transparent window via CSS', async () => { const display = screen.getPrimaryDisplay(); const backgroundWindow = new BrowserWindow({ ...display.bounds, frame: false, backgroundColor: HexColors.PURPLE, hasShadow: false }); await backgroundWindow.loadURL('about:blank'); const foregroundWindow = new BrowserWindow({ ...display.bounds, frame: false, transparent: true, hasShadow: false, webPreferences: { contextIsolation: false, nodeIntegration: true } }); foregroundWindow.loadFile(path.join(__dirname, 'fixtures', 'pages', 'css-transparent.html')); await once(ipcMain, 'set-transparent'); await setTimeout(); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); expect(areColorsSimilar(centerColor, HexColors.PURPLE)).to.be.true(); }); // Linux and arm64 platforms (WOA and macOS) do not return any capture sources ifit(process.platform === 'darwin' && process.arch === 'x64')('should not make background transparent if falsy', async () => { const display = screen.getPrimaryDisplay(); for (const transparent of [false, undefined]) { const window = new BrowserWindow({ ...display.bounds, transparent }); await once(window, 'show'); await window.webContents.loadURL('data:text/html,<head><meta name="color-scheme" content="dark"></head>'); await setTimeout(500); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); window.close(); // color-scheme is set to dark so background should not be white expect(areColorsSimilar(centerColor, HexColors.WHITE)).to.be.false(); } }); }); describe('"backgroundColor" option', () => { afterEach(closeAllWindows); // Linux/WOA doesn't return any capture sources. ifit(process.platform === 'darwin')('should display the set color', async () => { const display = screen.getPrimaryDisplay(); const w = new BrowserWindow({ ...display.bounds, show: true, backgroundColor: HexColors.BLUE }); w.loadURL('about:blank'); await once(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, HexColors.BLUE)).to.be.true(); }); }); });
closed
electron/electron
https://github.com/electron/electron
35,304
[Bug]: Unable to exit pdf present mode in WebView
### 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.4 ### 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 Should be able to exit pdf present mode, in Chrome it is possible to exit present mode by pressing Esc. ### Actual Behavior Unable to exit pdf present mode once it is selected. The Esc key only affects the windows full-screen mode, but the pdf view is unchanged. ![image](https://user-images.githubusercontent.com/111048903/184098506-5b1b63b6-c0ba-44ae-be74-e4a6bdafeb39.png) ### Testcase Gist URL https://gist.github.com/4868233713a4119d96c9273494157843 ### Additional Information _No response_
https://github.com/electron/electron/issues/35304
https://github.com/electron/electron/pull/39616
3bdc7ce64a79120c4001d0c614e4ad037246229e
d42a94dddeb86d349c050c2ee59b135bd6c8245c
2022-08-11T09:03:54Z
c++
2023-08-25T18:11:58Z
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 enable_reset_aspect_ratio.patch boringssl_build_gn.patch pepper_plugin_support.patch gtk_visibility.patch resource_file_conflict.patch scroll_bounce_flag.patch mas_blink_no_private_api.patch mas_no_private_api.patch mas-cgdisplayusesforcetogray.patch mas_disable_remote_layer.patch mas_disable_remote_accessibility.patch mas_disable_custom_window_frame.patch mas_avoid_usage_of_private_macos_apis.patch mas_use_public_apis_to_determine_if_a_font_is_a_system_font.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 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 allow_in-process_windows_to_have_different_web_prefs.patch refactor_expose_cursor_changes_to_the_webcontentsobserver.patch crash_allow_setting_more_options.patch upload_list_add_loadsync_method.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 export_gin_v8platform_pageallocator_for_usage_outside_of_the_gin.patch fix_export_zlib_symbols.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 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 process_singleton.patch add_ui_scopedcliboardwriter_writeunsaferawdata.patch feat_add_data_parameter_to_processsingleton.patch load_v8_snapshot_in_browser_process.patch fix_adapt_exclusive_access_for_electron_needs.patch fix_aspect_ratio_with_max_size.patch fix_crash_when_saving_edited_pdf_files.patch port_autofill_colors_to_the_color_pipeline.patch build_disable_partition_alloc_on_mac.patch fix_non-client_mouse_tracking_and_message_bubbling_on_windows.patch build_make_libcxx_abi_unstable_false_for_electron.patch introduce_ozoneplatform_electron_can_call_x11_property.patch make_gtk_getlibgtk_public.patch build_disable_print_content_analysis.patch custom_protocols_plzserviceworker.patch feat_filter_out_non-shareable_windows_in_the_current_application_in.patch fix_allow_guest_webcontents_to_enter_fullscreen.patch disable_freezing_flags_after_init_in_node.patch short-circuit_permissions_checks_in_mediastreamdevicescontroller.patch chore_add_electron_deps_to_gitignores.patch chore_allow_chromium_to_handle_synthetic_mouse_events_for_touch.patch add_maximized_parameter_to_linuxui_getwindowframeprovider.patch add_electron_deps_to_license_credits_file.patch fix_crash_loading_non-standard_schemes_in_iframes.patch create_browser_v8_snapshot_file_name_fuse.patch feat_configure_launch_options_for_service_process.patch feat_ensure_mas_builds_of_the_same_application_can_use_safestorage.patch fix_on-screen-keyboard_hides_on_input_blur_in_webview.patch preconnect_manager.patch fix_remove_caption-removing_style_call.patch build_allow_electron_to_use_exec_script.patch build_only_use_the_mas_build_config_in_the_required_components.patch chore_introduce_blocking_api_for_electron.patch chore_patch_out_partition_attribute_dcheck_for_webviews.patch expose_v8initializer_codegenerationcheckcallbackinmainthread.patch chore_patch_out_profile_methods_in_profile_selections_cc.patch add_gin_converter_support_for_arraybufferview.patch chore_defer_usb_service_getdevices_request_until_usb_service_is.patch fix_remove_profiles_from_spellcheck_service.patch chore_patch_out_profile_methods_in_chrome_browser_pdf.patch chore_patch_out_profile_methods_in_titlebar_config.patch fix_select_the_first_menu_item_when_opened_via_keyboard.patch fix_return_v8_value_from_localframe_requestexecutescript.patch fix_harden_blink_scriptstate_maybefrom.patch chore_add_buildflag_guard_around_new_include.patch fix_use_delegated_generic_capturer_when_available.patch build_remove_ent_content_analysis_assert.patch
closed
electron/electron
https://github.com/electron/electron
35,304
[Bug]: Unable to exit pdf present mode in WebView
### 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.4 ### 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 Should be able to exit pdf present mode, in Chrome it is possible to exit present mode by pressing Esc. ### Actual Behavior Unable to exit pdf present mode once it is selected. The Esc key only affects the windows full-screen mode, but the pdf view is unchanged. ![image](https://user-images.githubusercontent.com/111048903/184098506-5b1b63b6-c0ba-44ae-be74-e4a6bdafeb39.png) ### Testcase Gist URL https://gist.github.com/4868233713a4119d96c9273494157843 ### Additional Information _No response_
https://github.com/electron/electron/issues/35304
https://github.com/electron/electron/pull/39616
3bdc7ce64a79120c4001d0c614e4ad037246229e
d42a94dddeb86d349c050c2ee59b135bd6c8245c
2022-08-11T09:03:54Z
c++
2023-08-25T18:11:58Z
patches/chromium/fix_allow_guest_webcontents_to_enter_fullscreen.patch
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: Samuel Attard <[email protected]> Date: Mon, 6 Jun 2022 14:25:15 -0700 Subject: fix: allow guest webcontents to enter fullscreen This can be upstreamed, a guest webcontents can't technically become the focused webContents. This DCHECK should allow all guest webContents to request fullscreen entrance. diff --git a/content/browser/web_contents/web_contents_impl.cc b/content/browser/web_contents/web_contents_impl.cc index 8d5a0e6aa6ea3a0965ed6abb76368d1f8e3ea91e..36cd52f18c83adc007d6f896a4136a93f0fa1c83 100644 --- a/content/browser/web_contents/web_contents_impl.cc +++ b/content/browser/web_contents/web_contents_impl.cc @@ -3715,7 +3715,7 @@ void WebContentsImpl::EnterFullscreenMode( OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::EnterFullscreenMode"); DCHECK(CanEnterFullscreenMode(requesting_frame, options)); DCHECK(requesting_frame->IsActive()); - DCHECK(ContainsOrIsFocusedWebContents()); + DCHECK(ContainsOrIsFocusedWebContents() || IsGuest()); // When WebView is the `delegate_` we can end up with VisualProperties changes // synchronously. Notify the view ahead so it can handle the transition.
closed
electron/electron
https://github.com/electron/electron
35,304
[Bug]: Unable to exit pdf present mode in WebView
### 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.4 ### 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 Should be able to exit pdf present mode, in Chrome it is possible to exit present mode by pressing Esc. ### Actual Behavior Unable to exit pdf present mode once it is selected. The Esc key only affects the windows full-screen mode, but the pdf view is unchanged. ![image](https://user-images.githubusercontent.com/111048903/184098506-5b1b63b6-c0ba-44ae-be74-e4a6bdafeb39.png) ### Testcase Gist URL https://gist.github.com/4868233713a4119d96c9273494157843 ### Additional Information _No response_
https://github.com/electron/electron/issues/35304
https://github.com/electron/electron/pull/39616
3bdc7ce64a79120c4001d0c614e4ad037246229e
d42a94dddeb86d349c050c2ee59b135bd6c8245c
2022-08-11T09:03:54Z
c++
2023-08-25T18:11:58Z
patches/chromium/fix_on-screen-keyboard_hides_on_input_blur_in_webview.patch
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: Kyrylo Hrechykhin <[email protected]> Date: Thu, 6 Oct 2022 18:30:53 +0200 Subject: fix: on-screen-keyboard hides on input blur in webview Changes introduced by this patch fix issue where OSK does not hide on input rendered inside webview is blurred. This patch should be removed when proper fix in chromium repo is available. Note: the issue still occurs if input rendered in webview blurred due to touch outside of webview. It is caused by webview implementation details. Specificaly due to webview has its own tree nodes and focused node does not change in this case. chromium-bug: https://crbug.com/1369605 diff --git a/content/browser/renderer_host/render_widget_host_view_child_frame.cc b/content/browser/renderer_host/render_widget_host_view_child_frame.cc index 7f713269d7234448a7e59c8d3acdeeb74cb6a412..fe042289beb7d0239521f580aff9478a79719477 100644 --- a/content/browser/renderer_host/render_widget_host_view_child_frame.cc +++ b/content/browser/renderer_host/render_widget_host_view_child_frame.cc @@ -1006,6 +1006,12 @@ RenderWidgetHostViewChildFrame::DidUpdateVisualProperties( return viz::ScopedSurfaceIdAllocator(std::move(allocation_task)); } +void RenderWidgetHostViewChildFrame::FocusedNodeChanged( + bool is_editable_node, + const gfx::Rect& node_bounds_in_screen) { + NOTREACHED(); +} + ui::TextInputType RenderWidgetHostViewChildFrame::GetTextInputType() const { if (!text_input_manager_) return ui::TEXT_INPUT_TYPE_NONE; diff --git a/content/browser/renderer_host/render_widget_host_view_child_frame.h b/content/browser/renderer_host/render_widget_host_view_child_frame.h index 1e9dcbb9f0a5e401a50d63be490755bc3eeaa1a3..1e2e0a321df6fe9dea4401ed327c93730a4fea07 100644 --- a/content/browser/renderer_host/render_widget_host_view_child_frame.h +++ b/content/browser/renderer_host/render_widget_host_view_child_frame.h @@ -182,6 +182,8 @@ class CONTENT_EXPORT RenderWidgetHostViewChildFrame void DisableAutoResize(const gfx::Size& new_size) override; viz::ScopedSurfaceIdAllocator DidUpdateVisualProperties( const cc::RenderFrameMetadata& metadata) override; + void FocusedNodeChanged(bool is_editable_node, + const gfx::Rect& node_bounds_in_screen) override; // RenderFrameMetadataProvider::Observer implementation. void OnRenderFrameMetadataChangedBeforeActivation( diff --git a/content/browser/web_contents/web_contents_impl.cc b/content/browser/web_contents/web_contents_impl.cc index 36cd52f18c83adc007d6f896a4136a93f0fa1c83..99f6e45fe48449c2dbe88514648a4d907999e282 100644 --- a/content/browser/web_contents/web_contents_impl.cc +++ b/content/browser/web_contents/web_contents_impl.cc @@ -8319,7 +8319,7 @@ void WebContentsImpl::OnFocusedElementChangedInFrame( "WebContentsImpl::OnFocusedElementChangedInFrame", "render_frame_host", frame); RenderWidgetHostViewBase* root_view = - static_cast<RenderWidgetHostViewBase*>(GetRenderWidgetHostView()); + static_cast<RenderWidgetHostViewBase*>(GetTopLevelRenderWidgetHostView()); if (!root_view || !frame->GetView()) return; // Convert to screen coordinates from window coordinates by adding the
closed
electron/electron
https://github.com/electron/electron
35,304
[Bug]: Unable to exit pdf present mode in WebView
### 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.4 ### 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 Should be able to exit pdf present mode, in Chrome it is possible to exit present mode by pressing Esc. ### Actual Behavior Unable to exit pdf present mode once it is selected. The Esc key only affects the windows full-screen mode, but the pdf view is unchanged. ![image](https://user-images.githubusercontent.com/111048903/184098506-5b1b63b6-c0ba-44ae-be74-e4a6bdafeb39.png) ### Testcase Gist URL https://gist.github.com/4868233713a4119d96c9273494157843 ### Additional Information _No response_
https://github.com/electron/electron/issues/35304
https://github.com/electron/electron/pull/39616
3bdc7ce64a79120c4001d0c614e4ad037246229e
d42a94dddeb86d349c050c2ee59b135bd6c8245c
2022-08-11T09:03:54Z
c++
2023-08-25T18:11:58Z
patches/chromium/webview_fullscreen.patch
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: Cheng Zhao <[email protected]> Date: Thu, 4 Oct 2018 14:57:02 -0700 Subject: fix: also propagate fullscreen state for outer frame When entering fullscreen with Element.requestFullscreen in child frames, the parent frame should also enter fullscreen mode too. Chromium handles this for iframes, but not for webviews as they are essentially main frames instead of child frames. This patch makes webviews propagate the fullscreen state to embedder. Note that we also need to manually update embedder's `api::WebContents::IsFullscreenForTabOrPending` value. diff --git a/content/browser/renderer_host/render_frame_host_impl.cc b/content/browser/renderer_host/render_frame_host_impl.cc index 01eb116b51037bff5da7a87d119b78387f5e72c6..7ab5609215ce352b2595b4953e1b9ca027c62b47 100644 --- a/content/browser/renderer_host/render_frame_host_impl.cc +++ b/content/browser/renderer_host/render_frame_host_impl.cc @@ -7281,6 +7281,17 @@ void RenderFrameHostImpl::EnterFullscreen( } } + // Entering fullscreen from webview should also notify its outer frame. + if (frame_tree_node()->render_manager()->IsMainFrameForInnerDelegate()) { + RenderFrameProxyHost* outer_proxy = + frame_tree_node()->render_manager()->GetProxyToOuterDelegate(); + DCHECK(outer_proxy); + if (outer_proxy->is_render_frame_proxy_live()) { + outer_proxy->GetAssociatedRemoteFrame()->WillEnterFullscreen( + options.Clone()); + } + } + // Focus the window if another frame may have delegated the capability. if (had_fullscreen_token && !GetView()->HasFocus()) GetView()->Focus();
closed
electron/electron
https://github.com/electron/electron
35,304
[Bug]: Unable to exit pdf present mode in WebView
### 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.4 ### 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 Should be able to exit pdf present mode, in Chrome it is possible to exit present mode by pressing Esc. ### Actual Behavior Unable to exit pdf present mode once it is selected. The Esc key only affects the windows full-screen mode, but the pdf view is unchanged. ![image](https://user-images.githubusercontent.com/111048903/184098506-5b1b63b6-c0ba-44ae-be74-e4a6bdafeb39.png) ### Testcase Gist URL https://gist.github.com/4868233713a4119d96c9273494157843 ### Additional Information _No response_
https://github.com/electron/electron/issues/35304
https://github.com/electron/electron/pull/39616
3bdc7ce64a79120c4001d0c614e4ad037246229e
d42a94dddeb86d349c050c2ee59b135bd6c8245c
2022-08-11T09:03:54Z
c++
2023-08-25T18:11:58Z
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 enable_reset_aspect_ratio.patch boringssl_build_gn.patch pepper_plugin_support.patch gtk_visibility.patch resource_file_conflict.patch scroll_bounce_flag.patch mas_blink_no_private_api.patch mas_no_private_api.patch mas-cgdisplayusesforcetogray.patch mas_disable_remote_layer.patch mas_disable_remote_accessibility.patch mas_disable_custom_window_frame.patch mas_avoid_usage_of_private_macos_apis.patch mas_use_public_apis_to_determine_if_a_font_is_a_system_font.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 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 allow_in-process_windows_to_have_different_web_prefs.patch refactor_expose_cursor_changes_to_the_webcontentsobserver.patch crash_allow_setting_more_options.patch upload_list_add_loadsync_method.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 export_gin_v8platform_pageallocator_for_usage_outside_of_the_gin.patch fix_export_zlib_symbols.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 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 process_singleton.patch add_ui_scopedcliboardwriter_writeunsaferawdata.patch feat_add_data_parameter_to_processsingleton.patch load_v8_snapshot_in_browser_process.patch fix_adapt_exclusive_access_for_electron_needs.patch fix_aspect_ratio_with_max_size.patch fix_crash_when_saving_edited_pdf_files.patch port_autofill_colors_to_the_color_pipeline.patch build_disable_partition_alloc_on_mac.patch fix_non-client_mouse_tracking_and_message_bubbling_on_windows.patch build_make_libcxx_abi_unstable_false_for_electron.patch introduce_ozoneplatform_electron_can_call_x11_property.patch make_gtk_getlibgtk_public.patch build_disable_print_content_analysis.patch custom_protocols_plzserviceworker.patch feat_filter_out_non-shareable_windows_in_the_current_application_in.patch fix_allow_guest_webcontents_to_enter_fullscreen.patch disable_freezing_flags_after_init_in_node.patch short-circuit_permissions_checks_in_mediastreamdevicescontroller.patch chore_add_electron_deps_to_gitignores.patch chore_allow_chromium_to_handle_synthetic_mouse_events_for_touch.patch add_maximized_parameter_to_linuxui_getwindowframeprovider.patch add_electron_deps_to_license_credits_file.patch fix_crash_loading_non-standard_schemes_in_iframes.patch create_browser_v8_snapshot_file_name_fuse.patch feat_configure_launch_options_for_service_process.patch feat_ensure_mas_builds_of_the_same_application_can_use_safestorage.patch fix_on-screen-keyboard_hides_on_input_blur_in_webview.patch preconnect_manager.patch fix_remove_caption-removing_style_call.patch build_allow_electron_to_use_exec_script.patch build_only_use_the_mas_build_config_in_the_required_components.patch chore_introduce_blocking_api_for_electron.patch chore_patch_out_partition_attribute_dcheck_for_webviews.patch expose_v8initializer_codegenerationcheckcallbackinmainthread.patch chore_patch_out_profile_methods_in_profile_selections_cc.patch add_gin_converter_support_for_arraybufferview.patch chore_defer_usb_service_getdevices_request_until_usb_service_is.patch fix_remove_profiles_from_spellcheck_service.patch chore_patch_out_profile_methods_in_chrome_browser_pdf.patch chore_patch_out_profile_methods_in_titlebar_config.patch fix_select_the_first_menu_item_when_opened_via_keyboard.patch fix_return_v8_value_from_localframe_requestexecutescript.patch fix_harden_blink_scriptstate_maybefrom.patch chore_add_buildflag_guard_around_new_include.patch fix_use_delegated_generic_capturer_when_available.patch build_remove_ent_content_analysis_assert.patch
closed
electron/electron
https://github.com/electron/electron
35,304
[Bug]: Unable to exit pdf present mode in WebView
### 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.4 ### 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 Should be able to exit pdf present mode, in Chrome it is possible to exit present mode by pressing Esc. ### Actual Behavior Unable to exit pdf present mode once it is selected. The Esc key only affects the windows full-screen mode, but the pdf view is unchanged. ![image](https://user-images.githubusercontent.com/111048903/184098506-5b1b63b6-c0ba-44ae-be74-e4a6bdafeb39.png) ### Testcase Gist URL https://gist.github.com/4868233713a4119d96c9273494157843 ### Additional Information _No response_
https://github.com/electron/electron/issues/35304
https://github.com/electron/electron/pull/39616
3bdc7ce64a79120c4001d0c614e4ad037246229e
d42a94dddeb86d349c050c2ee59b135bd6c8245c
2022-08-11T09:03:54Z
c++
2023-08-25T18:11:58Z
patches/chromium/fix_allow_guest_webcontents_to_enter_fullscreen.patch
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: Samuel Attard <[email protected]> Date: Mon, 6 Jun 2022 14:25:15 -0700 Subject: fix: allow guest webcontents to enter fullscreen This can be upstreamed, a guest webcontents can't technically become the focused webContents. This DCHECK should allow all guest webContents to request fullscreen entrance. diff --git a/content/browser/web_contents/web_contents_impl.cc b/content/browser/web_contents/web_contents_impl.cc index 8d5a0e6aa6ea3a0965ed6abb76368d1f8e3ea91e..36cd52f18c83adc007d6f896a4136a93f0fa1c83 100644 --- a/content/browser/web_contents/web_contents_impl.cc +++ b/content/browser/web_contents/web_contents_impl.cc @@ -3715,7 +3715,7 @@ void WebContentsImpl::EnterFullscreenMode( OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::EnterFullscreenMode"); DCHECK(CanEnterFullscreenMode(requesting_frame, options)); DCHECK(requesting_frame->IsActive()); - DCHECK(ContainsOrIsFocusedWebContents()); + DCHECK(ContainsOrIsFocusedWebContents() || IsGuest()); // When WebView is the `delegate_` we can end up with VisualProperties changes // synchronously. Notify the view ahead so it can handle the transition.
closed
electron/electron
https://github.com/electron/electron
35,304
[Bug]: Unable to exit pdf present mode in WebView
### 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.4 ### 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 Should be able to exit pdf present mode, in Chrome it is possible to exit present mode by pressing Esc. ### Actual Behavior Unable to exit pdf present mode once it is selected. The Esc key only affects the windows full-screen mode, but the pdf view is unchanged. ![image](https://user-images.githubusercontent.com/111048903/184098506-5b1b63b6-c0ba-44ae-be74-e4a6bdafeb39.png) ### Testcase Gist URL https://gist.github.com/4868233713a4119d96c9273494157843 ### Additional Information _No response_
https://github.com/electron/electron/issues/35304
https://github.com/electron/electron/pull/39616
3bdc7ce64a79120c4001d0c614e4ad037246229e
d42a94dddeb86d349c050c2ee59b135bd6c8245c
2022-08-11T09:03:54Z
c++
2023-08-25T18:11:58Z
patches/chromium/fix_on-screen-keyboard_hides_on_input_blur_in_webview.patch
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: Kyrylo Hrechykhin <[email protected]> Date: Thu, 6 Oct 2022 18:30:53 +0200 Subject: fix: on-screen-keyboard hides on input blur in webview Changes introduced by this patch fix issue where OSK does not hide on input rendered inside webview is blurred. This patch should be removed when proper fix in chromium repo is available. Note: the issue still occurs if input rendered in webview blurred due to touch outside of webview. It is caused by webview implementation details. Specificaly due to webview has its own tree nodes and focused node does not change in this case. chromium-bug: https://crbug.com/1369605 diff --git a/content/browser/renderer_host/render_widget_host_view_child_frame.cc b/content/browser/renderer_host/render_widget_host_view_child_frame.cc index 7f713269d7234448a7e59c8d3acdeeb74cb6a412..fe042289beb7d0239521f580aff9478a79719477 100644 --- a/content/browser/renderer_host/render_widget_host_view_child_frame.cc +++ b/content/browser/renderer_host/render_widget_host_view_child_frame.cc @@ -1006,6 +1006,12 @@ RenderWidgetHostViewChildFrame::DidUpdateVisualProperties( return viz::ScopedSurfaceIdAllocator(std::move(allocation_task)); } +void RenderWidgetHostViewChildFrame::FocusedNodeChanged( + bool is_editable_node, + const gfx::Rect& node_bounds_in_screen) { + NOTREACHED(); +} + ui::TextInputType RenderWidgetHostViewChildFrame::GetTextInputType() const { if (!text_input_manager_) return ui::TEXT_INPUT_TYPE_NONE; diff --git a/content/browser/renderer_host/render_widget_host_view_child_frame.h b/content/browser/renderer_host/render_widget_host_view_child_frame.h index 1e9dcbb9f0a5e401a50d63be490755bc3eeaa1a3..1e2e0a321df6fe9dea4401ed327c93730a4fea07 100644 --- a/content/browser/renderer_host/render_widget_host_view_child_frame.h +++ b/content/browser/renderer_host/render_widget_host_view_child_frame.h @@ -182,6 +182,8 @@ class CONTENT_EXPORT RenderWidgetHostViewChildFrame void DisableAutoResize(const gfx::Size& new_size) override; viz::ScopedSurfaceIdAllocator DidUpdateVisualProperties( const cc::RenderFrameMetadata& metadata) override; + void FocusedNodeChanged(bool is_editable_node, + const gfx::Rect& node_bounds_in_screen) override; // RenderFrameMetadataProvider::Observer implementation. void OnRenderFrameMetadataChangedBeforeActivation( diff --git a/content/browser/web_contents/web_contents_impl.cc b/content/browser/web_contents/web_contents_impl.cc index 36cd52f18c83adc007d6f896a4136a93f0fa1c83..99f6e45fe48449c2dbe88514648a4d907999e282 100644 --- a/content/browser/web_contents/web_contents_impl.cc +++ b/content/browser/web_contents/web_contents_impl.cc @@ -8319,7 +8319,7 @@ void WebContentsImpl::OnFocusedElementChangedInFrame( "WebContentsImpl::OnFocusedElementChangedInFrame", "render_frame_host", frame); RenderWidgetHostViewBase* root_view = - static_cast<RenderWidgetHostViewBase*>(GetRenderWidgetHostView()); + static_cast<RenderWidgetHostViewBase*>(GetTopLevelRenderWidgetHostView()); if (!root_view || !frame->GetView()) return; // Convert to screen coordinates from window coordinates by adding the
closed
electron/electron
https://github.com/electron/electron
35,304
[Bug]: Unable to exit pdf present mode in WebView
### 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.4 ### 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 Should be able to exit pdf present mode, in Chrome it is possible to exit present mode by pressing Esc. ### Actual Behavior Unable to exit pdf present mode once it is selected. The Esc key only affects the windows full-screen mode, but the pdf view is unchanged. ![image](https://user-images.githubusercontent.com/111048903/184098506-5b1b63b6-c0ba-44ae-be74-e4a6bdafeb39.png) ### Testcase Gist URL https://gist.github.com/4868233713a4119d96c9273494157843 ### Additional Information _No response_
https://github.com/electron/electron/issues/35304
https://github.com/electron/electron/pull/39616
3bdc7ce64a79120c4001d0c614e4ad037246229e
d42a94dddeb86d349c050c2ee59b135bd6c8245c
2022-08-11T09:03:54Z
c++
2023-08-25T18:11:58Z
patches/chromium/webview_fullscreen.patch
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: Cheng Zhao <[email protected]> Date: Thu, 4 Oct 2018 14:57:02 -0700 Subject: fix: also propagate fullscreen state for outer frame When entering fullscreen with Element.requestFullscreen in child frames, the parent frame should also enter fullscreen mode too. Chromium handles this for iframes, but not for webviews as they are essentially main frames instead of child frames. This patch makes webviews propagate the fullscreen state to embedder. Note that we also need to manually update embedder's `api::WebContents::IsFullscreenForTabOrPending` value. diff --git a/content/browser/renderer_host/render_frame_host_impl.cc b/content/browser/renderer_host/render_frame_host_impl.cc index 01eb116b51037bff5da7a87d119b78387f5e72c6..7ab5609215ce352b2595b4953e1b9ca027c62b47 100644 --- a/content/browser/renderer_host/render_frame_host_impl.cc +++ b/content/browser/renderer_host/render_frame_host_impl.cc @@ -7281,6 +7281,17 @@ void RenderFrameHostImpl::EnterFullscreen( } } + // Entering fullscreen from webview should also notify its outer frame. + if (frame_tree_node()->render_manager()->IsMainFrameForInnerDelegate()) { + RenderFrameProxyHost* outer_proxy = + frame_tree_node()->render_manager()->GetProxyToOuterDelegate(); + DCHECK(outer_proxy); + if (outer_proxy->is_render_frame_proxy_live()) { + outer_proxy->GetAssociatedRemoteFrame()->WillEnterFullscreen( + options.Clone()); + } + } + // Focus the window if another frame may have delegated the capability. if (had_fullscreen_token && !GetView()->HasFocus()) GetView()->Focus();
closed
electron/electron
https://github.com/electron/electron
38,588
Flaky contentTracing v8 sampling spec
`contentTracing captured events include V8 samples from the main process` has been flaking a fair amount on Appveyor as of late. See [here](https://ci.appveyor.com/project/electron-bot/electron-x64-testing/builds/47184539/job/6ycj2f45a7flb0dc/tests) for example.
https://github.com/electron/electron/issues/38588
https://github.com/electron/electron/pull/39682
f27b0340454ada29977a7d08f2dbc8321923e1b1
4cc0f6fb781a3efe6b018aa4ef410e4196c03ecf
2023-06-05T09:38:39Z
c++
2023-09-04T12:08:26Z
spec/api-content-tracing-spec.ts
import { expect } from 'chai'; import { app, contentTracing, TraceConfig, TraceCategoriesAndOptions } from 'electron/main'; import * as fs from 'node:fs'; import * as path from 'node:path'; import { setTimeout } from 'node:timers/promises'; import { ifdescribe } from './lib/spec-helpers'; // FIXME: The tests are skipped on arm/arm64 and ia32. ifdescribe(!(['arm', 'arm64', 'ia32'].includes(process.arch)))('contentTracing', () => { const record = async (options: TraceConfig | TraceCategoriesAndOptions, outputFilePath: string | undefined, recordTimeInMilliseconds = 1e1) => { await app.whenReady(); await contentTracing.startRecording(options); await setTimeout(recordTimeInMilliseconds); const resultFilePath = await contentTracing.stopRecording(outputFilePath); return resultFilePath; }; const outputFilePath = path.join(app.getPath('temp'), 'trace.json'); beforeEach(() => { if (fs.existsSync(outputFilePath)) { fs.unlinkSync(outputFilePath); } }); describe('startRecording', function () { this.timeout(5e3); const getFileSizeInKiloBytes = (filePath: string) => { const stats = fs.statSync(filePath); const fileSizeInBytes = stats.size; const fileSizeInKiloBytes = fileSizeInBytes / 1024; return fileSizeInKiloBytes; }; it('accepts an empty config', async () => { const config = {}; await record(config, outputFilePath); expect(fs.existsSync(outputFilePath)).to.be.true('output exists'); const fileSizeInKiloBytes = getFileSizeInKiloBytes(outputFilePath); expect(fileSizeInKiloBytes).to.be.above(0, `the trace output file is empty, check "${outputFilePath}"`); }); it('accepts a trace config', async () => { // (alexeykuzmin): All categories are excluded on purpose, // so only metadata gets into the output file. const config = { excluded_categories: ['*'] }; await record(config, outputFilePath); // If the `excluded_categories` param above is not respected, categories // like `node,node.environment` will be included in the output. const content = fs.readFileSync(outputFilePath).toString(); expect(content.includes('"cat":"node,node.environment"')).to.be.false(); }); it('accepts "categoryFilter" and "traceOptions" as a config', async () => { // (alexeykuzmin): All categories are excluded on purpose, // so only metadata gets into the output file. const config = { categoryFilter: '__ThisIsANonexistentCategory__', traceOptions: '' }; await record(config, outputFilePath); expect(fs.existsSync(outputFilePath)).to.be.true('output exists'); // If the `categoryFilter` param above is not respected // the file size will be above 50KB. const fileSizeInKiloBytes = getFileSizeInKiloBytes(outputFilePath); const expectedMaximumFileSize = 10; // Depends on a platform. expect(fileSizeInKiloBytes).to.be.above(0, `the trace output file is empty, check "${outputFilePath}"`); expect(fileSizeInKiloBytes).to.be.below(expectedMaximumFileSize, `the trace output file is suspiciously large (${fileSizeInKiloBytes}KB), check "${outputFilePath}"`); }); }); describe('stopRecording', function () { this.timeout(5e3); it('does not crash on empty string', async () => { const options = { categoryFilter: '*', traceOptions: 'record-until-full,enable-sampling' }; await contentTracing.startRecording(options); const path = await contentTracing.stopRecording(''); expect(path).to.be.a('string').that.is.not.empty('result path'); expect(fs.statSync(path).isFile()).to.be.true('output exists'); }); it('calls its callback with a result file path', async () => { const resultFilePath = await record(/* options */ {}, outputFilePath); expect(resultFilePath).to.be.a('string').and.be.equal(outputFilePath); }); it('creates a temporary file when an empty string is passed', async function () { const resultFilePath = await record(/* options */ {}, /* outputFilePath */ ''); expect(resultFilePath).to.be.a('string').that.is.not.empty('result path'); }); it('creates a temporary file when no path is passed', async function () { const resultFilePath = await record(/* options */ {}, /* outputFilePath */ undefined); expect(resultFilePath).to.be.a('string').that.is.not.empty('result path'); }); it('rejects if no trace is happening', async () => { await expect(contentTracing.stopRecording()).to.be.rejectedWith('Failed to stop tracing - no trace in progress'); }); }); describe('captured events', () => { it('include V8 samples from the main process', async function () { // This test is flaky on macOS CI. this.retries(3); await contentTracing.startRecording({ categoryFilter: 'disabled-by-default-v8.cpu_profiler', traceOptions: 'record-until-full' }); { const start = Date.now(); let n = 0; const f = () => {}; while (Date.now() - start < 200 || n < 500) { await setTimeout(0); f(); n++; } } const path = await contentTracing.stopRecording(); const data = fs.readFileSync(path, 'utf8'); const parsed = JSON.parse(data); expect(parsed.traceEvents.some((x: any) => x.cat === 'disabled-by-default-v8.cpu_profiler' && x.name === 'ProfileChunk')).to.be.true(); }); }); });
closed
electron/electron
https://github.com/electron/electron
38,588
Flaky contentTracing v8 sampling spec
`contentTracing captured events include V8 samples from the main process` has been flaking a fair amount on Appveyor as of late. See [here](https://ci.appveyor.com/project/electron-bot/electron-x64-testing/builds/47184539/job/6ycj2f45a7flb0dc/tests) for example.
https://github.com/electron/electron/issues/38588
https://github.com/electron/electron/pull/39682
f27b0340454ada29977a7d08f2dbc8321923e1b1
4cc0f6fb781a3efe6b018aa4ef410e4196c03ecf
2023-06-05T09:38:39Z
c++
2023-09-04T12:08:26Z
spec/api-content-tracing-spec.ts
import { expect } from 'chai'; import { app, contentTracing, TraceConfig, TraceCategoriesAndOptions } from 'electron/main'; import * as fs from 'node:fs'; import * as path from 'node:path'; import { setTimeout } from 'node:timers/promises'; import { ifdescribe } from './lib/spec-helpers'; // FIXME: The tests are skipped on arm/arm64 and ia32. ifdescribe(!(['arm', 'arm64', 'ia32'].includes(process.arch)))('contentTracing', () => { const record = async (options: TraceConfig | TraceCategoriesAndOptions, outputFilePath: string | undefined, recordTimeInMilliseconds = 1e1) => { await app.whenReady(); await contentTracing.startRecording(options); await setTimeout(recordTimeInMilliseconds); const resultFilePath = await contentTracing.stopRecording(outputFilePath); return resultFilePath; }; const outputFilePath = path.join(app.getPath('temp'), 'trace.json'); beforeEach(() => { if (fs.existsSync(outputFilePath)) { fs.unlinkSync(outputFilePath); } }); describe('startRecording', function () { this.timeout(5e3); const getFileSizeInKiloBytes = (filePath: string) => { const stats = fs.statSync(filePath); const fileSizeInBytes = stats.size; const fileSizeInKiloBytes = fileSizeInBytes / 1024; return fileSizeInKiloBytes; }; it('accepts an empty config', async () => { const config = {}; await record(config, outputFilePath); expect(fs.existsSync(outputFilePath)).to.be.true('output exists'); const fileSizeInKiloBytes = getFileSizeInKiloBytes(outputFilePath); expect(fileSizeInKiloBytes).to.be.above(0, `the trace output file is empty, check "${outputFilePath}"`); }); it('accepts a trace config', async () => { // (alexeykuzmin): All categories are excluded on purpose, // so only metadata gets into the output file. const config = { excluded_categories: ['*'] }; await record(config, outputFilePath); // If the `excluded_categories` param above is not respected, categories // like `node,node.environment` will be included in the output. const content = fs.readFileSync(outputFilePath).toString(); expect(content.includes('"cat":"node,node.environment"')).to.be.false(); }); it('accepts "categoryFilter" and "traceOptions" as a config', async () => { // (alexeykuzmin): All categories are excluded on purpose, // so only metadata gets into the output file. const config = { categoryFilter: '__ThisIsANonexistentCategory__', traceOptions: '' }; await record(config, outputFilePath); expect(fs.existsSync(outputFilePath)).to.be.true('output exists'); // If the `categoryFilter` param above is not respected // the file size will be above 50KB. const fileSizeInKiloBytes = getFileSizeInKiloBytes(outputFilePath); const expectedMaximumFileSize = 10; // Depends on a platform. expect(fileSizeInKiloBytes).to.be.above(0, `the trace output file is empty, check "${outputFilePath}"`); expect(fileSizeInKiloBytes).to.be.below(expectedMaximumFileSize, `the trace output file is suspiciously large (${fileSizeInKiloBytes}KB), check "${outputFilePath}"`); }); }); describe('stopRecording', function () { this.timeout(5e3); it('does not crash on empty string', async () => { const options = { categoryFilter: '*', traceOptions: 'record-until-full,enable-sampling' }; await contentTracing.startRecording(options); const path = await contentTracing.stopRecording(''); expect(path).to.be.a('string').that.is.not.empty('result path'); expect(fs.statSync(path).isFile()).to.be.true('output exists'); }); it('calls its callback with a result file path', async () => { const resultFilePath = await record(/* options */ {}, outputFilePath); expect(resultFilePath).to.be.a('string').and.be.equal(outputFilePath); }); it('creates a temporary file when an empty string is passed', async function () { const resultFilePath = await record(/* options */ {}, /* outputFilePath */ ''); expect(resultFilePath).to.be.a('string').that.is.not.empty('result path'); }); it('creates a temporary file when no path is passed', async function () { const resultFilePath = await record(/* options */ {}, /* outputFilePath */ undefined); expect(resultFilePath).to.be.a('string').that.is.not.empty('result path'); }); it('rejects if no trace is happening', async () => { await expect(contentTracing.stopRecording()).to.be.rejectedWith('Failed to stop tracing - no trace in progress'); }); }); describe('captured events', () => { it('include V8 samples from the main process', async function () { // This test is flaky on macOS CI. this.retries(3); await contentTracing.startRecording({ categoryFilter: 'disabled-by-default-v8.cpu_profiler', traceOptions: 'record-until-full' }); { const start = Date.now(); let n = 0; const f = () => {}; while (Date.now() - start < 200 || n < 500) { await setTimeout(0); f(); n++; } } const path = await contentTracing.stopRecording(); const data = fs.readFileSync(path, 'utf8'); const parsed = JSON.parse(data); expect(parsed.traceEvents.some((x: any) => x.cat === 'disabled-by-default-v8.cpu_profiler' && x.name === 'ProfileChunk')).to.be.true(); }); }); });
closed
electron/electron
https://github.com/electron/electron
35,403
[Bug]: macOS - Using frame, roundedCorners, and fullscreen settings together automatically causes a 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 20.0.3 ### What operating system are you using? macOS ### Operating System Version Catalina (confirmed on Big Sur too) ### What arch are you using? x64 ### Last Known Working Electron version Not working in version 17-21 ### Expected Behavior Code such as the following should not crash Electron: ``` win = new BrowserWindow({ title: "Media Window", frame: false, // These 3 options can't be roundedCorners: false, // used concurrently on macOS fullscreen: true // without causing a crash }); ``` ### Actual Behavior The following code crashes Electron on macOS: ``` win = new BrowserWindow({ title: "Media Window", frame: false, // These 3 options can't be roundedCorners: false, // used concurrently on macOS fullscreen: true // without causing a crash }); ``` Any of the following 3 variants does **not** cause the crash: ``` win = new BrowserWindow({ title: "Media Window", // frame: false, roundedCorners: false, fullscreen: true }); ``` ``` win = new BrowserWindow({ title: "Media Window", frame: false, // roundedCorners: false, fullscreen: true }); ``` ``` win = new BrowserWindow({ title: "Media Window", frame: false, roundedCorners: false, // fullscreen: true }); ``` ### Testcase Gist URL https://gist.github.com/sircharlo/c78e81a20c3eb4167037197b3803d76e ### Additional Information Error looks like this: Electron[785:12045] *** Assertion failure in -[ElectronNSWindow titlebarAccessoryViewControllers], /AppleInternal/BuildRoot/Library/Caches/com.apple.xbs/Sources/AppKit/AppKit-1894.60.100/AppKit.subproj/NSWindow.m:3337
https://github.com/electron/electron/issues/35403
https://github.com/electron/electron/pull/39747
2324c4d8fd6f7b2cd336d4e93591464544e12953
ab185c058f894ddc556f67b2853de4adad2bb10c
2022-08-22T15:16:24Z
c++
2023-09-11T07:38:10Z
shell/browser/native_window_mac.mm
// 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_mac.h" #include <AvailabilityMacros.h> #include <objc/objc-runtime.h> #include <algorithm> #include <memory> #include <string> #include <utility> #include <vector> #include "base/apple/scoped_cftyperef.h" #include "base/mac/mac_util.h" #include "base/strings/sys_string_conversions.h" #include "components/remote_cocoa/app_shim/native_widget_ns_window_bridge.h" #include "components/remote_cocoa/browser/scoped_cg_window_id.h" #include "content/public/browser/browser_accessibility_state.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/desktop_media_id.h" #include "shell/browser/browser.h" #include "shell/browser/javascript_environment.h" #include "shell/browser/native_browser_view_mac.h" #include "shell/browser/ui/cocoa/electron_native_widget_mac.h" #include "shell/browser/ui/cocoa/electron_ns_window.h" #include "shell/browser/ui/cocoa/electron_ns_window_delegate.h" #include "shell/browser/ui/cocoa/electron_preview_item.h" #include "shell/browser/ui/cocoa/electron_touch_bar.h" #include "shell/browser/ui/cocoa/root_view_mac.h" #include "shell/browser/ui/cocoa/window_buttons_proxy.h" #include "shell/browser/ui/drag_util.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/window_list.h" #include "shell/common/gin_converters/gfx_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/node_includes.h" #include "shell/common/options_switches.h" #include "shell/common/process_util.h" #include "skia/ext/skia_utils_mac.h" #include "third_party/skia/include/core/SkRegion.h" #include "third_party/webrtc/modules/desktop_capture/mac/window_list_utils.h" #include "ui/base/hit_test.h" #include "ui/display/screen.h" #include "ui/gfx/skia_util.h" #include "ui/gl/gpu_switching_manager.h" #include "ui/views/background.h" #include "ui/views/cocoa/native_widget_mac_ns_window_host.h" #include "ui/views/widget/widget.h" #include "ui/views/window/native_frame_view_mac.h" @interface ElectronProgressBar : NSProgressIndicator @end @implementation ElectronProgressBar - (void)drawRect:(NSRect)dirtyRect { if (self.style != NSProgressIndicatorStyleBar) return; // Draw edges of rounded rect. NSRect rect = NSInsetRect([self bounds], 1.0, 1.0); CGFloat radius = rect.size.height / 2; NSBezierPath* bezier_path = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [bezier_path setLineWidth:2.0]; [[NSColor grayColor] set]; [bezier_path stroke]; // Fill the rounded rect. rect = NSInsetRect(rect, 2.0, 2.0); radius = rect.size.height / 2; bezier_path = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [bezier_path setLineWidth:1.0]; [bezier_path addClip]; // Calculate the progress width. rect.size.width = floor(rect.size.width * ([self doubleValue] / [self maxValue])); // Fill the progress bar with color blue. [[NSColor colorWithSRGBRed:0.2 green:0.6 blue:1 alpha:1] set]; NSRectFill(rect); } @end namespace gin { template <> struct Converter<electron::NativeWindowMac::VisualEffectState> { static bool FromV8(v8::Isolate* isolate, v8::Handle<v8::Value> val, electron::NativeWindowMac::VisualEffectState* out) { using VisualEffectState = electron::NativeWindowMac::VisualEffectState; std::string visual_effect_state; if (!ConvertFromV8(isolate, val, &visual_effect_state)) return false; if (visual_effect_state == "followWindow") { *out = VisualEffectState::kFollowWindow; } else if (visual_effect_state == "active") { *out = VisualEffectState::kActive; } else if (visual_effect_state == "inactive") { *out = VisualEffectState::kInactive; } else { return false; } return true; } }; } // namespace gin namespace electron { namespace { bool IsFramelessWindow(NSView* view) { NSWindow* nswindow = [view window]; if (![nswindow respondsToSelector:@selector(shell)]) return false; NativeWindow* window = [static_cast<ElectronNSWindow*>(nswindow) shell]; return window && !window->has_frame(); } IMP original_set_frame_size = nullptr; IMP original_view_did_move_to_superview = nullptr; // This method is directly called by NSWindow during a window resize on OSX // 10.10.0, beta 2. We must override it to prevent the content view from // shrinking. void SetFrameSize(NSView* self, SEL _cmd, NSSize size) { if (!IsFramelessWindow(self)) { auto original = reinterpret_cast<decltype(&SetFrameSize)>(original_set_frame_size); return original(self, _cmd, size); } // For frameless window, resize the view to cover full window. if ([self superview]) size = [[self superview] bounds].size; auto super_impl = reinterpret_cast<decltype(&SetFrameSize)>( [[self superclass] instanceMethodForSelector:_cmd]); super_impl(self, _cmd, size); } // The contentView gets moved around during certain full-screen operations. // This is less than ideal, and should eventually be removed. void ViewDidMoveToSuperview(NSView* self, SEL _cmd) { if (!IsFramelessWindow(self)) { // [BridgedContentView viewDidMoveToSuperview]; auto original = reinterpret_cast<decltype(&ViewDidMoveToSuperview)>( original_view_did_move_to_superview); if (original) original(self, _cmd); return; } [self setFrame:[[self superview] bounds]]; } // -[NSWindow orderWindow] does not handle reordering for children // windows. Their order is fixed to the attachment order (the last attached // window is on the top). Therefore, work around it by re-parenting in our // desired order. void ReorderChildWindowAbove(NSWindow* child_window, NSWindow* other_window) { NSWindow* parent = [child_window parentWindow]; DCHECK(parent); // `ordered_children` sorts children windows back to front. NSArray<NSWindow*>* children = [[child_window parentWindow] childWindows]; std::vector<std::pair<NSInteger, NSWindow*>> ordered_children; for (NSWindow* child in children) ordered_children.push_back({[child orderedIndex], child}); std::sort(ordered_children.begin(), ordered_children.end(), std::greater<>()); // If `other_window` is nullptr, place `child_window` in front of // all other children windows. if (other_window == nullptr) other_window = ordered_children.back().second; if (child_window == other_window) return; for (NSWindow* child in children) [parent removeChildWindow:child]; const bool relative_to_parent = parent == other_window; if (relative_to_parent) [parent addChildWindow:child_window ordered:NSWindowAbove]; // Re-parent children windows in the desired order. for (auto [ordered_index, child] : ordered_children) { if (child != child_window && child != other_window) { [parent addChildWindow:child ordered:NSWindowAbove]; } else if (child == other_window && !relative_to_parent) { [parent addChildWindow:other_window ordered:NSWindowAbove]; [parent addChildWindow:child_window ordered:NSWindowAbove]; } } } } // namespace NativeWindowMac::NativeWindowMac(const gin_helper::Dictionary& options, NativeWindow* parent) : NativeWindow(options, parent), root_view_(new RootViewMac(this)) { ui::NativeTheme::GetInstanceForNativeUi()->AddObserver(this); display::Screen::GetScreen()->AddObserver(this); int width = 800, height = 600; options.Get(options::kWidth, &width); options.Get(options::kHeight, &height); NSRect main_screen_rect = [[[NSScreen screens] firstObject] frame]; gfx::Rect bounds(round((NSWidth(main_screen_rect) - width) / 2), round((NSHeight(main_screen_rect) - height) / 2), width, height); bool resizable = true; options.Get(options::kResizable, &resizable); options.Get(options::kZoomToPageWidth, &zoom_to_page_width_); options.Get(options::kSimpleFullScreen, &always_simple_fullscreen_); options.GetOptional(options::kTrafficLightPosition, &traffic_light_position_); options.Get(options::kVisualEffectState, &visual_effect_state_); if (options.Has(options::kFullscreenWindowTitle)) { EmitWarning( node::Environment::GetCurrent(JavascriptEnvironment::GetIsolate()), "\"fullscreenWindowTitle\" option has been deprecated and is " "no-op now.", "electron"); } bool minimizable = true; options.Get(options::kMinimizable, &minimizable); bool maximizable = true; options.Get(options::kMaximizable, &maximizable); bool closable = true; options.Get(options::kClosable, &closable); std::string tabbingIdentifier; options.Get(options::kTabbingIdentifier, &tabbingIdentifier); std::string windowType; options.Get(options::kType, &windowType); bool hiddenInMissionControl = false; options.Get(options::kHiddenInMissionControl, &hiddenInMissionControl); bool useStandardWindow = true; // eventually deprecate separate "standardWindow" option in favor of // standard / textured window types options.Get(options::kStandardWindow, &useStandardWindow); if (windowType == "textured") { useStandardWindow = false; } // The window without titlebar is treated the same with frameless window. if (title_bar_style_ != TitleBarStyle::kNormal) set_has_frame(false); NSUInteger styleMask = NSWindowStyleMaskTitled; // The NSWindowStyleMaskFullSizeContentView style removes rounded corners // for frameless window. bool rounded_corner = true; options.Get(options::kRoundedCorners, &rounded_corner); if (!rounded_corner && !has_frame()) styleMask = NSWindowStyleMaskBorderless; if (minimizable) styleMask |= NSWindowStyleMaskMiniaturizable; if (closable) styleMask |= NSWindowStyleMaskClosable; if (resizable) styleMask |= NSWindowStyleMaskResizable; if (!useStandardWindow || transparent() || !has_frame()) styleMask |= NSWindowStyleMaskTexturedBackground; // Create views::Widget and assign window_ with it. // TODO(zcbenz): Get rid of the window_ in future. 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.native_widget = new ElectronNativeWidgetMac(this, windowType, styleMask, widget()); widget()->Init(std::move(params)); SetCanResize(resizable); window_ = static_cast<ElectronNSWindow*>( widget()->GetNativeWindow().GetNativeNSWindow()); RegisterDeleteDelegateCallback(base::BindOnce( [](NativeWindowMac* window) { if (window->window_) window->window_ = nil; if (window->buttons_proxy_) window->buttons_proxy_ = nil; }, this)); [window_ setEnableLargerThanScreen:enable_larger_than_screen()]; window_delegate_ = [[ElectronNSWindowDelegate alloc] initWithShell:this]; [window_ setDelegate:window_delegate_]; // Only use native parent window for non-modal windows. if (parent && !is_modal()) { SetParentWindow(parent); } if (transparent()) { // Setting the background color to clear will also hide the shadow. [window_ setBackgroundColor:[NSColor clearColor]]; } if (windowType == "desktop") { [window_ setLevel:kCGDesktopWindowLevel - 1]; [window_ setDisableKeyOrMainWindow:YES]; [window_ setCollectionBehavior:(NSWindowCollectionBehaviorCanJoinAllSpaces | NSWindowCollectionBehaviorStationary | NSWindowCollectionBehaviorIgnoresCycle)]; } if (windowType == "panel") { [window_ setLevel:NSFloatingWindowLevel]; } bool focusable; if (options.Get(options::kFocusable, &focusable) && !focusable) [window_ setDisableKeyOrMainWindow:YES]; if (transparent() || !has_frame()) { // Don't show title bar. [window_ setTitlebarAppearsTransparent:YES]; [window_ setTitleVisibility:NSWindowTitleHidden]; // Remove non-transparent corners, see // https://github.com/electron/electron/issues/517. [window_ setOpaque:NO]; // Show window buttons if titleBarStyle is not "normal". if (title_bar_style_ == TitleBarStyle::kNormal) { InternalSetWindowButtonVisibility(false); } else { buttons_proxy_ = [[WindowButtonsProxy alloc] initWithWindow:window_]; [buttons_proxy_ setHeight:titlebar_overlay_height()]; if (traffic_light_position_) { [buttons_proxy_ setMargin:*traffic_light_position_]; } else if (title_bar_style_ == TitleBarStyle::kHiddenInset) { // For macOS >= 11, while this value does not match official macOS apps // like Safari or Notes, it matches titleBarStyle's old implementation // before Electron <= 12. [buttons_proxy_ setMargin:gfx::Point(12, 11)]; } if (title_bar_style_ == TitleBarStyle::kCustomButtonsOnHover) { [buttons_proxy_ setShowOnHover:YES]; } else { // customButtonsOnHover does not show buttons initially. InternalSetWindowButtonVisibility(true); } } } // Create a tab only if tabbing identifier is specified and window has // a native title bar. if (tabbingIdentifier.empty() || transparent() || !has_frame()) { [window_ setTabbingMode:NSWindowTabbingModeDisallowed]; } else { [window_ setTabbingIdentifier:base::SysUTF8ToNSString(tabbingIdentifier)]; } // Resize to content bounds. bool use_content_size = false; options.Get(options::kUseContentSize, &use_content_size); if (!has_frame() || use_content_size) SetContentSize(gfx::Size(width, height)); // Enable the NSView to accept first mouse event. bool acceptsFirstMouse = false; options.Get(options::kAcceptFirstMouse, &acceptsFirstMouse); [window_ setAcceptsFirstMouse:acceptsFirstMouse]; // Disable auto-hiding cursor. bool disableAutoHideCursor = false; options.Get(options::kDisableAutoHideCursor, &disableAutoHideCursor); [window_ setDisableAutoHideCursor:disableAutoHideCursor]; SetHiddenInMissionControl(hiddenInMissionControl); // Set maximizable state last to ensure zoom button does not get reset // by calls to other APIs. SetMaximizable(maximizable); // Default content view. SetContentView(new views::View()); AddContentViewLayers(); UpdateWindowOriginalFrame(); original_level_ = [window_ level]; } NativeWindowMac::~NativeWindowMac() = default; void NativeWindowMac::SetContentView(views::View* view) { views::View* root_view = GetContentsView(); if (content_view()) root_view->RemoveChildView(content_view()); set_content_view(view); root_view->AddChildView(content_view()); root_view->Layout(); } void NativeWindowMac::Close() { if (!IsClosable()) { WindowList::WindowCloseCancelled(this); return; } if (fullscreen_transition_state() != FullScreenTransitionState::kNone) { SetHasDeferredWindowClose(true); return; } // Ensure we're detached from the parent window before closing. RemoveChildFromParentWindow(); while (!child_windows_.empty()) { auto* child = child_windows_.back(); child->RemoveChildFromParentWindow(); } // If a sheet is attached to the window when we call // [window_ performClose:nil], the window won't close properly // even after the user has ended the sheet. // Ensure it's closed before calling [window_ performClose:nil]. if ([window_ attachedSheet]) [window_ endSheet:[window_ attachedSheet]]; [window_ performClose:nil]; // Closing a sheet doesn't trigger windowShouldClose, // so we need to manually call it ourselves here. if (is_modal() && parent() && IsVisible()) { NotifyWindowCloseButtonClicked(); } } void NativeWindowMac::CloseImmediately() { // Ensure we're detached from the parent window before closing. RemoveChildFromParentWindow(); while (!child_windows_.empty()) { auto* child = child_windows_.back(); child->RemoveChildFromParentWindow(); } [window_ close]; } void NativeWindowMac::Focus(bool focus) { if (!IsVisible()) return; if (focus) { [[NSApplication sharedApplication] activateIgnoringOtherApps:NO]; [window_ makeKeyAndOrderFront:nil]; } else { [window_ orderOut:nil]; [window_ orderBack:nil]; } } bool NativeWindowMac::IsFocused() { return [window_ isKeyWindow]; } void NativeWindowMac::Show() { if (is_modal() && parent()) { NSWindow* window = parent()->GetNativeWindow().GetNativeNSWindow(); if ([window_ sheetParent] == nil) [window beginSheet:window_ completionHandler:^(NSModalResponse){ }]; return; } // Reattach the window to the parent to actually show it. if (parent()) InternalSetParentWindow(parent(), true); // This method is supposed to put focus on window, however if the app does not // have focus then "makeKeyAndOrderFront" will only show the window. [NSApp activateIgnoringOtherApps:YES]; [window_ makeKeyAndOrderFront:nil]; } void NativeWindowMac::ShowInactive() { // Reattach the window to the parent to actually show it. if (parent()) InternalSetParentWindow(parent(), true); [window_ orderFrontRegardless]; } void NativeWindowMac::Hide() { // If a sheet is attached to the window when we call [window_ orderOut:nil], // the sheet won't be able to show again on the same window. // Ensure it's closed before calling [window_ orderOut:nil]. if ([window_ attachedSheet]) [window_ endSheet:[window_ attachedSheet]]; if (is_modal() && parent()) { [window_ orderOut:nil]; [parent()->GetNativeWindow().GetNativeNSWindow() endSheet:window_]; return; } DetachChildren(); // Detach the window from the parent before. if (parent()) InternalSetParentWindow(parent(), false); [window_ orderOut:nil]; } bool NativeWindowMac::IsVisible() { bool occluded = [window_ occlusionState] == NSWindowOcclusionStateVisible; return [window_ isVisible] && !occluded && !IsMinimized(); } bool NativeWindowMac::IsEnabled() { return [window_ attachedSheet] == nil; } void NativeWindowMac::SetEnabled(bool enable) { if (!enable) { NSRect frame = [window_ frame]; NSWindow* window = [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, frame.size.width, frame.size.height) styleMask:NSWindowStyleMaskTitled backing:NSBackingStoreBuffered defer:NO]; [window setAlphaValue:0.5]; [window_ beginSheet:window completionHandler:^(NSModalResponse returnCode) { NSLog(@"main window disabled"); return; }]; } else if ([window_ attachedSheet]) { [window_ endSheet:[window_ attachedSheet]]; } } void NativeWindowMac::Maximize() { const bool is_visible = [window_ isVisible]; if (IsMaximized()) { if (!is_visible) ShowInactive(); return; } // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); [window_ zoom:nil]; if (!is_visible) { ShowInactive(); NotifyWindowMaximize(); } } void NativeWindowMac::Unmaximize() { // Bail if the last user set bounds were the same size as the window // screen (e.g. the user set the window to maximized via setBounds) // // Per docs during zoom: // > If there’s no saved user state because there has been no previous // > zoom,the size and location of the window don’t change. // // However, in classic Apple fashion, this is not the case in practice, // and the frame inexplicably becomes very tiny. We should prevent // zoom from being called if the window is being unmaximized and its // unmaximized window bounds are themselves functionally maximized. if (!IsMaximized() || user_set_bounds_maximized_) return; [window_ zoom:nil]; } bool NativeWindowMac::IsMaximized() { // It's possible for [window_ isZoomed] to be true // when the window is minimized or fullscreened. if (IsMinimized() || IsFullscreen()) return false; if (HasStyleMask(NSWindowStyleMaskResizable) != 0) return [window_ isZoomed]; NSRect rectScreen = GetAspectRatio() > 0.0 ? default_frame_for_zoom() : [[NSScreen mainScreen] visibleFrame]; return NSEqualRects([window_ frame], rectScreen); } void NativeWindowMac::Minimize() { if (IsMinimized()) return; // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); [window_ miniaturize:nil]; } void NativeWindowMac::Restore() { [window_ deminiaturize:nil]; } bool NativeWindowMac::IsMinimized() { return [window_ isMiniaturized]; } bool NativeWindowMac::HandleDeferredClose() { if (has_deferred_window_close_) { SetHasDeferredWindowClose(false); Close(); return true; } return false; } void NativeWindowMac::RemoveChildWindow(NativeWindow* child) { child_windows_.remove_if([&child](NativeWindow* w) { return (w == child); }); [window_ removeChildWindow:child->GetNativeWindow().GetNativeNSWindow()]; } void NativeWindowMac::RemoveChildFromParentWindow() { if (parent() && !is_modal()) { parent()->RemoveChildWindow(this); NativeWindow::SetParentWindow(nullptr); } } void NativeWindowMac::AttachChildren() { for (auto* child : child_windows_) { auto* child_nswindow = child->GetNativeWindow().GetNativeNSWindow(); if ([child_nswindow parentWindow] == window_) continue; // Attaching a window as a child window resets its window level, so // save and restore it afterwards. NSInteger level = window_.level; [window_ addChildWindow:child_nswindow ordered:NSWindowAbove]; [window_ setLevel:level]; } } void NativeWindowMac::DetachChildren() { DCHECK(child_windows_.size() == [[window_ childWindows] count]); // Hide all children before hiding/minimizing the window. // NativeWidgetNSWindowBridge::NotifyVisibilityChangeDown() // will DCHECK otherwise. for (auto* child : child_windows_) { [child->GetNativeWindow().GetNativeNSWindow() orderOut:nil]; } } void NativeWindowMac::SetFullScreen(bool fullscreen) { if (!has_frame() && !HasStyleMask(NSWindowStyleMaskTitled)) return; // [NSWindow -toggleFullScreen] is an asynchronous operation, which means // that it's possible to call it while a fullscreen transition is currently // in process. This can create weird behavior (incl. phantom windows), // so we want to schedule a transition for when the current one has completed. if (fullscreen_transition_state() != FullScreenTransitionState::kNone) { if (!pending_transitions_.empty()) { bool last_pending = pending_transitions_.back(); // Only push new transitions if they're different than the last transition // in the queue. if (last_pending != fullscreen) pending_transitions_.push(fullscreen); } else { pending_transitions_.push(fullscreen); } return; } if (fullscreen == IsFullscreen() || !IsFullScreenable()) return; // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); // This needs to be set here because it can be the case that // SetFullScreen is called by a user before windowWillEnterFullScreen // or windowWillExitFullScreen are invoked, and so a potential transition // could be dropped. fullscreen_transition_state_ = fullscreen ? FullScreenTransitionState::kEntering : FullScreenTransitionState::kExiting; [window_ toggleFullScreenMode:nil]; } bool NativeWindowMac::IsFullscreen() const { return HasStyleMask(NSWindowStyleMaskFullScreen); } void NativeWindowMac::SetBounds(const gfx::Rect& bounds, bool animate) { // Do nothing if in fullscreen mode. if (IsFullscreen()) return; // Check size constraints since setFrame does not check it. gfx::Size size = bounds.size(); size.SetToMax(GetMinimumSize()); gfx::Size max_size = GetMaximumSize(); if (!max_size.IsEmpty()) size.SetToMin(max_size); NSRect cocoa_bounds = NSMakeRect(bounds.x(), 0, size.width(), size.height()); // Flip coordinates based on the primary screen. NSScreen* screen = [[NSScreen screens] firstObject]; cocoa_bounds.origin.y = NSHeight([screen frame]) - size.height() - bounds.y(); [window_ setFrame:cocoa_bounds display:YES animate:animate]; user_set_bounds_maximized_ = IsMaximized() ? true : false; UpdateWindowOriginalFrame(); } gfx::Rect NativeWindowMac::GetBounds() { NSRect frame = [window_ frame]; gfx::Rect bounds(frame.origin.x, 0, NSWidth(frame), NSHeight(frame)); NSScreen* screen = [[NSScreen screens] firstObject]; bounds.set_y(NSHeight([screen frame]) - NSMaxY(frame)); return bounds; } bool NativeWindowMac::IsNormal() { return NativeWindow::IsNormal() && !IsSimpleFullScreen(); } gfx::Rect NativeWindowMac::GetNormalBounds() { if (IsNormal()) { return GetBounds(); } NSRect frame = original_frame_; gfx::Rect bounds(frame.origin.x, 0, NSWidth(frame), NSHeight(frame)); NSScreen* screen = [[NSScreen screens] firstObject]; bounds.set_y(NSHeight([screen frame]) - NSMaxY(frame)); return bounds; // Works on OS_WIN ! // return widget()->GetRestoredBounds(); } void NativeWindowMac::SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints) { auto convertSize = [this](const gfx::Size& size) { // Our frameless window still has titlebar attached, so setting contentSize // will result in actual content size being larger. if (!has_frame()) { NSRect frame = NSMakeRect(0, 0, size.width(), size.height()); NSRect content = [window_ originalContentRectForFrameRect:frame]; return content.size; } else { return NSMakeSize(size.width(), size.height()); } }; NSView* content = [window_ contentView]; if (size_constraints.HasMinimumSize()) { NSSize min_size = convertSize(size_constraints.GetMinimumSize()); [window_ setContentMinSize:[content convertSize:min_size toView:nil]]; } if (size_constraints.HasMaximumSize()) { NSSize max_size = convertSize(size_constraints.GetMaximumSize()); [window_ setContentMaxSize:[content convertSize:max_size toView:nil]]; } NativeWindow::SetContentSizeConstraints(size_constraints); } bool NativeWindowMac::MoveAbove(const std::string& sourceId) { const content::DesktopMediaID id = content::DesktopMediaID::Parse(sourceId); if (id.type != content::DesktopMediaID::TYPE_WINDOW) return false; // Check if the window source is valid. const CGWindowID window_id = id.id; if (!webrtc::GetWindowOwnerPid(window_id)) return false; if (!parent() || is_modal()) { [window_ orderWindow:NSWindowAbove relativeTo:window_id]; } else { NSWindow* other_window = [NSApp windowWithWindowNumber:window_id]; ReorderChildWindowAbove(window_, other_window); } return true; } void NativeWindowMac::MoveTop() { if (!parent() || is_modal()) { [window_ orderWindow:NSWindowAbove relativeTo:0]; } else { ReorderChildWindowAbove(window_, nullptr); } } void NativeWindowMac::SetResizable(bool resizable) { ScopedDisableResize disable_resize; SetStyleMask(resizable, NSWindowStyleMaskResizable); bool was_fullscreenable = IsFullScreenable(); // Right now, resizable and fullscreenable are decoupled in // documentation and on Windows/Linux. Chromium disables // fullscreen collection behavior as well as the maximize traffic // light in SetCanResize if resizability is false on macOS unless // the window is both resizable and maximizable. We want consistent // cross-platform behavior, so if resizability is disabled we disable // the maximize button and ensure fullscreenability matches user setting. SetCanResize(resizable); SetFullScreenable(was_fullscreenable); [[window_ standardWindowButton:NSWindowZoomButton] setEnabled:resizable ? was_fullscreenable : false]; } bool NativeWindowMac::IsResizable() { bool in_fs_transition = fullscreen_transition_state() != FullScreenTransitionState::kNone; bool has_rs_mask = HasStyleMask(NSWindowStyleMaskResizable); return has_rs_mask && !IsFullscreen() && !in_fs_transition; } void NativeWindowMac::SetMovable(bool movable) { [window_ setMovable:movable]; } bool NativeWindowMac::IsMovable() { return [window_ isMovable]; } void NativeWindowMac::SetMinimizable(bool minimizable) { SetStyleMask(minimizable, NSWindowStyleMaskMiniaturizable); } bool NativeWindowMac::IsMinimizable() { return HasStyleMask(NSWindowStyleMaskMiniaturizable); } void NativeWindowMac::SetMaximizable(bool maximizable) { maximizable_ = maximizable; [[window_ standardWindowButton:NSWindowZoomButton] setEnabled:maximizable]; } bool NativeWindowMac::IsMaximizable() { return [[window_ standardWindowButton:NSWindowZoomButton] isEnabled]; } void NativeWindowMac::SetFullScreenable(bool fullscreenable) { SetCollectionBehavior(fullscreenable, NSWindowCollectionBehaviorFullScreenPrimary); // On EL Capitan this flag is required to hide fullscreen button. SetCollectionBehavior(!fullscreenable, NSWindowCollectionBehaviorFullScreenAuxiliary); } bool NativeWindowMac::IsFullScreenable() { NSUInteger collectionBehavior = [window_ collectionBehavior]; return collectionBehavior & NSWindowCollectionBehaviorFullScreenPrimary; } void NativeWindowMac::SetClosable(bool closable) { SetStyleMask(closable, NSWindowStyleMaskClosable); } bool NativeWindowMac::IsClosable() { return HasStyleMask(NSWindowStyleMaskClosable); } void NativeWindowMac::SetAlwaysOnTop(ui::ZOrderLevel z_order, const std::string& level_name, int relative_level) { if (z_order == ui::ZOrderLevel::kNormal) { SetWindowLevel(NSNormalWindowLevel); return; } int level = NSNormalWindowLevel; if (level_name == "floating") { level = NSFloatingWindowLevel; } else if (level_name == "torn-off-menu") { level = NSTornOffMenuWindowLevel; } else if (level_name == "modal-panel") { level = NSModalPanelWindowLevel; } else if (level_name == "main-menu") { level = NSMainMenuWindowLevel; } else if (level_name == "status") { level = NSStatusWindowLevel; } else if (level_name == "pop-up-menu") { level = NSPopUpMenuWindowLevel; } else if (level_name == "screen-saver") { level = NSScreenSaverWindowLevel; } SetWindowLevel(level + relative_level); } std::string NativeWindowMac::GetAlwaysOnTopLevel() { std::string level_name = "normal"; int level = [window_ level]; if (level == NSFloatingWindowLevel) { level_name = "floating"; } else if (level == NSTornOffMenuWindowLevel) { level_name = "torn-off-menu"; } else if (level == NSModalPanelWindowLevel) { level_name = "modal-panel"; } else if (level == NSMainMenuWindowLevel) { level_name = "main-menu"; } else if (level == NSStatusWindowLevel) { level_name = "status"; } else if (level == NSPopUpMenuWindowLevel) { level_name = "pop-up-menu"; } else if (level == NSScreenSaverWindowLevel) { level_name = "screen-saver"; } return level_name; } void NativeWindowMac::SetWindowLevel(int unbounded_level) { int level = std::min( std::max(unbounded_level, CGWindowLevelForKey(kCGMinimumWindowLevelKey)), CGWindowLevelForKey(kCGMaximumWindowLevelKey)); ui::ZOrderLevel z_order_level = level == NSNormalWindowLevel ? ui::ZOrderLevel::kNormal : ui::ZOrderLevel::kFloatingWindow; bool did_z_order_level_change = z_order_level != GetZOrderLevel(); was_maximizable_ = IsMaximizable(); // We need to explicitly keep the NativeWidget up to date, since it stores the // window level in a local variable, rather than reading it from the NSWindow. // Unfortunately, it results in a second setLevel call. It's not ideal, but we // don't expect this to cause any user-visible jank. widget()->SetZOrderLevel(z_order_level); [window_ setLevel:level]; // Set level will make the zoom button revert to default, probably // a bug of Cocoa or macOS. SetMaximizable(was_maximizable_); // This must be notified at the very end or IsAlwaysOnTop // will not yet have been updated to reflect the new status if (did_z_order_level_change) NativeWindow::NotifyWindowAlwaysOnTopChanged(); } ui::ZOrderLevel NativeWindowMac::GetZOrderLevel() { return widget()->GetZOrderLevel(); } void NativeWindowMac::Center() { [window_ center]; } void NativeWindowMac::Invalidate() { [[window_ contentView] setNeedsDisplay:YES]; } void NativeWindowMac::SetTitle(const std::string& title) { [window_ setTitle:base::SysUTF8ToNSString(title)]; if (buttons_proxy_) [buttons_proxy_ redraw]; } std::string NativeWindowMac::GetTitle() { return base::SysNSStringToUTF8([window_ title]); } void NativeWindowMac::FlashFrame(bool flash) { if (flash) { attention_request_id_ = [NSApp requestUserAttention:NSInformationalRequest]; } else { [NSApp cancelUserAttentionRequest:attention_request_id_]; attention_request_id_ = 0; } } void NativeWindowMac::SetSkipTaskbar(bool skip) {} bool NativeWindowMac::IsExcludedFromShownWindowsMenu() { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); return [window isExcludedFromWindowsMenu]; } void NativeWindowMac::SetExcludedFromShownWindowsMenu(bool excluded) { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); [window setExcludedFromWindowsMenu:excluded]; } void NativeWindowMac::OnDisplayMetricsChanged(const display::Display& display, uint32_t changed_metrics) { // We only want to force screen recalibration if we're in simpleFullscreen // mode. if (!is_simple_fullscreen_) return; content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&NativeWindow::UpdateFrame, GetWeakPtr())); } void NativeWindowMac::SetSimpleFullScreen(bool simple_fullscreen) { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); if (simple_fullscreen && !is_simple_fullscreen_) { is_simple_fullscreen_ = true; // Take note of the current window size and level if (IsNormal()) { UpdateWindowOriginalFrame(); original_level_ = [window_ level]; } simple_fullscreen_options_ = [NSApp currentSystemPresentationOptions]; simple_fullscreen_mask_ = [window styleMask]; // We can simulate the pre-Lion fullscreen by auto-hiding the dock and menu // bar NSApplicationPresentationOptions options = NSApplicationPresentationAutoHideDock | NSApplicationPresentationAutoHideMenuBar; [NSApp setPresentationOptions:options]; was_maximizable_ = IsMaximizable(); was_movable_ = IsMovable(); NSRect fullscreenFrame = [window.screen frame]; // If our app has dock hidden, set the window level higher so another app's // menu bar doesn't appear on top of our fullscreen app. if ([[NSRunningApplication currentApplication] activationPolicy] != NSApplicationActivationPolicyRegular) { window.level = NSPopUpMenuWindowLevel; } // Always hide the titlebar in simple fullscreen mode. // // Note that we must remove the NSWindowStyleMaskTitled style instead of // using the [window_ setTitleVisibility:], as the latter would leave the // window with rounded corners. SetStyleMask(false, NSWindowStyleMaskTitled); if (!window_button_visibility_.has_value()) { // Lets keep previous behaviour - hide window controls in titled // fullscreen mode when not specified otherwise. InternalSetWindowButtonVisibility(false); } [window setFrame:fullscreenFrame display:YES animate:YES]; // Fullscreen windows can't be resized, minimized, maximized, or moved SetMinimizable(false); SetResizable(false); SetMaximizable(false); SetMovable(false); } else if (!simple_fullscreen && is_simple_fullscreen_) { is_simple_fullscreen_ = false; [window setFrame:original_frame_ display:YES animate:YES]; window.level = original_level_; [NSApp setPresentationOptions:simple_fullscreen_options_]; // Restore original style mask ScopedDisableResize disable_resize; [window_ setStyleMask:simple_fullscreen_mask_]; // Restore window manipulation abilities SetMaximizable(was_maximizable_); SetMovable(was_movable_); // Restore default window controls visibility state. if (!window_button_visibility_.has_value()) { bool visibility; if (has_frame()) visibility = true; else visibility = title_bar_style_ != TitleBarStyle::kNormal; InternalSetWindowButtonVisibility(visibility); } if (buttons_proxy_) [buttons_proxy_ redraw]; } } bool NativeWindowMac::IsSimpleFullScreen() { return is_simple_fullscreen_; } void NativeWindowMac::SetKiosk(bool kiosk) { if (kiosk && !is_kiosk_) { kiosk_options_ = [NSApp currentSystemPresentationOptions]; NSApplicationPresentationOptions options = NSApplicationPresentationHideDock | NSApplicationPresentationHideMenuBar | NSApplicationPresentationDisableAppleMenu | NSApplicationPresentationDisableProcessSwitching | NSApplicationPresentationDisableForceQuit | NSApplicationPresentationDisableSessionTermination | NSApplicationPresentationDisableHideApplication; [NSApp setPresentationOptions:options]; is_kiosk_ = true; fullscreen_before_kiosk_ = IsFullscreen(); if (!fullscreen_before_kiosk_) SetFullScreen(true); } else if (!kiosk && is_kiosk_) { is_kiosk_ = false; if (!fullscreen_before_kiosk_) SetFullScreen(false); // Set presentation options *after* asynchronously exiting // fullscreen to ensure they take effect. [NSApp setPresentationOptions:kiosk_options_]; } } bool NativeWindowMac::IsKiosk() { return is_kiosk_; } void NativeWindowMac::SetBackgroundColor(SkColor color) { base::apple::ScopedCFTypeRef<CGColorRef> cgcolor( skia::CGColorCreateFromSkColor(color)); [[[window_ contentView] layer] setBackgroundColor:cgcolor]; } SkColor NativeWindowMac::GetBackgroundColor() { CGColorRef color = [[[window_ contentView] layer] backgroundColor]; if (!color) return SK_ColorTRANSPARENT; return skia::CGColorRefToSkColor(color); } void NativeWindowMac::SetHasShadow(bool has_shadow) { [window_ setHasShadow:has_shadow]; } bool NativeWindowMac::HasShadow() { return [window_ hasShadow]; } void NativeWindowMac::InvalidateShadow() { [window_ invalidateShadow]; } void NativeWindowMac::SetOpacity(const double opacity) { const double boundedOpacity = std::clamp(opacity, 0.0, 1.0); [window_ setAlphaValue:boundedOpacity]; } double NativeWindowMac::GetOpacity() { return [window_ alphaValue]; } void NativeWindowMac::SetRepresentedFilename(const std::string& filename) { [window_ setRepresentedFilename:base::SysUTF8ToNSString(filename)]; if (buttons_proxy_) [buttons_proxy_ redraw]; } std::string NativeWindowMac::GetRepresentedFilename() { return base::SysNSStringToUTF8([window_ representedFilename]); } void NativeWindowMac::SetDocumentEdited(bool edited) { [window_ setDocumentEdited:edited]; if (buttons_proxy_) [buttons_proxy_ redraw]; } bool NativeWindowMac::IsDocumentEdited() { return [window_ isDocumentEdited]; } bool NativeWindowMac::IsHiddenInMissionControl() { NSUInteger collectionBehavior = [window_ collectionBehavior]; return collectionBehavior & NSWindowCollectionBehaviorTransient; } void NativeWindowMac::SetHiddenInMissionControl(bool hidden) { SetCollectionBehavior(hidden, NSWindowCollectionBehaviorTransient); } void NativeWindowMac::SetIgnoreMouseEvents(bool ignore, bool forward) { [window_ setIgnoresMouseEvents:ignore]; if (!ignore) { SetForwardMouseMessages(NO); } else { SetForwardMouseMessages(forward); } } void NativeWindowMac::SetContentProtection(bool enable) { [window_ setSharingType:enable ? NSWindowSharingNone : NSWindowSharingReadOnly]; } void NativeWindowMac::SetFocusable(bool focusable) { // No known way to unfocus the window if it had the focus. Here we do not // want to call Focus(false) because it moves the window to the back, i.e. // at the bottom in term of z-order. [window_ setDisableKeyOrMainWindow:!focusable]; } bool NativeWindowMac::IsFocusable() { return ![window_ disableKeyOrMainWindow]; } void NativeWindowMac::AddBrowserView(NativeBrowserView* view) { [CATransaction begin]; [CATransaction setDisableActions:YES]; if (!view) { [CATransaction commit]; return; } add_browser_view(view); if (view->GetInspectableWebContentsView()) { auto* native_view = view->GetInspectableWebContentsView() ->GetNativeView() .GetNativeNSView(); [[window_ contentView] addSubview:native_view positioned:NSWindowAbove relativeTo:nil]; native_view.hidden = NO; } [CATransaction commit]; } void NativeWindowMac::RemoveBrowserView(NativeBrowserView* view) { [CATransaction begin]; [CATransaction setDisableActions:YES]; if (!view) { [CATransaction commit]; return; } if (view->GetInspectableWebContentsView()) [view->GetInspectableWebContentsView()->GetNativeView().GetNativeNSView() removeFromSuperview]; remove_browser_view(view); [CATransaction commit]; } void NativeWindowMac::SetTopBrowserView(NativeBrowserView* view) { [CATransaction begin]; [CATransaction setDisableActions:YES]; if (!view) { [CATransaction commit]; return; } remove_browser_view(view); add_browser_view(view); if (view->GetInspectableWebContentsView()) { auto* native_view = view->GetInspectableWebContentsView() ->GetNativeView() .GetNativeNSView(); [[window_ contentView] addSubview:native_view positioned:NSWindowAbove relativeTo:nil]; native_view.hidden = NO; } [CATransaction commit]; } void NativeWindowMac::SetParentWindow(NativeWindow* parent) { InternalSetParentWindow(parent, IsVisible()); } gfx::NativeView NativeWindowMac::GetNativeView() const { return [window_ contentView]; } gfx::NativeWindow NativeWindowMac::GetNativeWindow() const { return window_; } gfx::AcceleratedWidget NativeWindowMac::GetAcceleratedWidget() const { return [window_ windowNumber]; } content::DesktopMediaID NativeWindowMac::GetDesktopMediaID() const { auto desktop_media_id = content::DesktopMediaID( content::DesktopMediaID::TYPE_WINDOW, GetAcceleratedWidget()); // c.f. // https://source.chromium.org/chromium/chromium/src/+/main:chrome/browser/media/webrtc/native_desktop_media_list.cc;l=775-780;drc=79502ab47f61bff351426f57f576daef02b1a8dc // Refs https://github.com/electron/electron/pull/30507 // TODO(deepak1556): Match upstream for `kWindowCaptureMacV2` #if 0 if (remote_cocoa::ScopedCGWindowID::Get(desktop_media_id.id)) { desktop_media_id.window_id = desktop_media_id.id; } #endif return desktop_media_id; } NativeWindowHandle NativeWindowMac::GetNativeWindowHandle() const { return [window_ contentView]; } void NativeWindowMac::SetProgressBar(double progress, const NativeWindow::ProgressState state) { NSDockTile* dock_tile = [NSApp dockTile]; // Sometimes macOS would install a default contentView for dock, we must // verify whether NSProgressIndicator has been installed. bool first_time = !dock_tile.contentView || [[dock_tile.contentView subviews] count] == 0 || ![[[dock_tile.contentView subviews] lastObject] isKindOfClass:[NSProgressIndicator class]]; // For the first time API invoked, we need to create a ContentView in // DockTile. if (first_time) { NSImageView* image_view = [[NSImageView alloc] init]; [image_view setImage:[NSApp applicationIconImage]]; [dock_tile setContentView:image_view]; NSRect frame = NSMakeRect(0.0f, 0.0f, dock_tile.size.width, 15.0); NSProgressIndicator* progress_indicator = [[ElectronProgressBar alloc] initWithFrame:frame]; [progress_indicator setStyle:NSProgressIndicatorStyleBar]; [progress_indicator setIndeterminate:NO]; [progress_indicator setBezeled:YES]; [progress_indicator setMinValue:0]; [progress_indicator setMaxValue:1]; [progress_indicator setHidden:NO]; [dock_tile.contentView addSubview:progress_indicator]; } NSProgressIndicator* progress_indicator = static_cast<NSProgressIndicator*>( [[[dock_tile contentView] subviews] lastObject]); if (progress < 0) { [progress_indicator setHidden:YES]; } else if (progress > 1) { [progress_indicator setHidden:NO]; [progress_indicator setIndeterminate:YES]; [progress_indicator setDoubleValue:1]; } else { [progress_indicator setHidden:NO]; [progress_indicator setDoubleValue:progress]; } [dock_tile display]; } void NativeWindowMac::SetOverlayIcon(const gfx::Image& overlay, const std::string& description) {} void NativeWindowMac::SetVisibleOnAllWorkspaces(bool visible, bool visibleOnFullScreen, bool skipTransformProcessType) { // In order for NSWindows to be visible on fullscreen we need to invoke // app.dock.hide() since Apple changed the underlying functionality of // NSWindows starting with 10.14 to disallow NSWindows from floating on top of // fullscreen apps. if (!skipTransformProcessType) { if (visibleOnFullScreen) { Browser::Get()->DockHide(); } else { Browser::Get()->DockShow(JavascriptEnvironment::GetIsolate()); } } SetCollectionBehavior(visible, NSWindowCollectionBehaviorCanJoinAllSpaces); SetCollectionBehavior(visibleOnFullScreen, NSWindowCollectionBehaviorFullScreenAuxiliary); } bool NativeWindowMac::IsVisibleOnAllWorkspaces() { NSUInteger collectionBehavior = [window_ collectionBehavior]; return collectionBehavior & NSWindowCollectionBehaviorCanJoinAllSpaces; } void NativeWindowMac::SetAutoHideCursor(bool auto_hide) { [window_ setDisableAutoHideCursor:!auto_hide]; } void NativeWindowMac::UpdateVibrancyRadii(bool fullscreen) { NSVisualEffectView* vibrantView = [window_ vibrantView]; if (vibrantView != nil && !vibrancy_type_.empty()) { const bool no_rounded_corner = !HasStyleMask(NSWindowStyleMaskTitled); if (!has_frame() && !is_modal() && !no_rounded_corner) { CGFloat radius; if (fullscreen) { radius = 0.0f; } else if (@available(macOS 11.0, *)) { radius = 9.0f; } else { // Smaller corner radius on versions prior to Big Sur. radius = 5.0f; } CGFloat dimension = 2 * radius + 1; NSSize size = NSMakeSize(dimension, dimension); NSImage* maskImage = [NSImage imageWithSize:size flipped:NO drawingHandler:^BOOL(NSRect rect) { NSBezierPath* bezierPath = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [[NSColor blackColor] set]; [bezierPath fill]; return YES; }]; [maskImage setCapInsets:NSEdgeInsetsMake(radius, radius, radius, radius)]; [maskImage setResizingMode:NSImageResizingModeStretch]; [vibrantView setMaskImage:maskImage]; [window_ setCornerMask:maskImage]; } } } void NativeWindowMac::UpdateWindowOriginalFrame() { original_frame_ = [window_ frame]; } void NativeWindowMac::SetVibrancy(const std::string& type) { NSVisualEffectView* vibrantView = [window_ vibrantView]; if (type.empty()) { if (vibrantView == nil) return; [vibrantView removeFromSuperview]; [window_ setVibrantView:nil]; return; } NSVisualEffectMaterial vibrancyType{}; if (type == "titlebar") { vibrancyType = NSVisualEffectMaterialTitlebar; } else if (type == "selection") { vibrancyType = NSVisualEffectMaterialSelection; } else if (type == "menu") { vibrancyType = NSVisualEffectMaterialMenu; } else if (type == "popover") { vibrancyType = NSVisualEffectMaterialPopover; } else if (type == "sidebar") { vibrancyType = NSVisualEffectMaterialSidebar; } else if (type == "header") { vibrancyType = NSVisualEffectMaterialHeaderView; } else if (type == "sheet") { vibrancyType = NSVisualEffectMaterialSheet; } else if (type == "window") { vibrancyType = NSVisualEffectMaterialWindowBackground; } else if (type == "hud") { vibrancyType = NSVisualEffectMaterialHUDWindow; } else if (type == "fullscreen-ui") { vibrancyType = NSVisualEffectMaterialFullScreenUI; } else if (type == "tooltip") { vibrancyType = NSVisualEffectMaterialToolTip; } else if (type == "content") { vibrancyType = NSVisualEffectMaterialContentBackground; } else if (type == "under-window") { vibrancyType = NSVisualEffectMaterialUnderWindowBackground; } else if (type == "under-page") { vibrancyType = NSVisualEffectMaterialUnderPageBackground; } if (vibrancyType) { vibrancy_type_ = type; if (vibrantView == nil) { vibrantView = [[NSVisualEffectView alloc] initWithFrame:[[window_ contentView] bounds]]; [window_ setVibrantView:vibrantView]; [vibrantView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable]; [vibrantView setBlendingMode:NSVisualEffectBlendingModeBehindWindow]; if (visual_effect_state_ == VisualEffectState::kActive) { [vibrantView setState:NSVisualEffectStateActive]; } else if (visual_effect_state_ == VisualEffectState::kInactive) { [vibrantView setState:NSVisualEffectStateInactive]; } else { [vibrantView setState:NSVisualEffectStateFollowsWindowActiveState]; } [[window_ contentView] addSubview:vibrantView positioned:NSWindowBelow relativeTo:nil]; UpdateVibrancyRadii(IsFullscreen()); } [vibrantView setMaterial:vibrancyType]; } } void NativeWindowMac::SetWindowButtonVisibility(bool visible) { window_button_visibility_ = visible; if (buttons_proxy_) { if (visible) [buttons_proxy_ redraw]; [buttons_proxy_ setVisible:visible]; } if (title_bar_style_ != TitleBarStyle::kCustomButtonsOnHover) InternalSetWindowButtonVisibility(visible); NotifyLayoutWindowControlsOverlay(); } bool NativeWindowMac::GetWindowButtonVisibility() const { return ![window_ standardWindowButton:NSWindowZoomButton].hidden || ![window_ standardWindowButton:NSWindowMiniaturizeButton].hidden || ![window_ standardWindowButton:NSWindowCloseButton].hidden; } void NativeWindowMac::SetWindowButtonPosition( absl::optional<gfx::Point> position) { traffic_light_position_ = std::move(position); if (buttons_proxy_) { [buttons_proxy_ setMargin:traffic_light_position_]; NotifyLayoutWindowControlsOverlay(); } } absl::optional<gfx::Point> NativeWindowMac::GetWindowButtonPosition() const { return traffic_light_position_; } void NativeWindowMac::RedrawTrafficLights() { if (buttons_proxy_ && !IsFullscreen()) [buttons_proxy_ redraw]; } // In simpleFullScreen mode, update the frame for new bounds. void NativeWindowMac::UpdateFrame() { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); NSRect fullscreenFrame = [window.screen frame]; [window setFrame:fullscreenFrame display:YES animate:YES]; } void NativeWindowMac::SetTouchBar( std::vector<gin_helper::PersistentDictionary> items) { touch_bar_ = [[ElectronTouchBar alloc] initWithDelegate:window_delegate_ window:this settings:std::move(items)]; [window_ setTouchBar:nil]; } void NativeWindowMac::RefreshTouchBarItem(const std::string& item_id) { if (touch_bar_ && [window_ touchBar]) [touch_bar_ refreshTouchBarItem:[window_ touchBar] id:item_id]; } void NativeWindowMac::SetEscapeTouchBarItem( gin_helper::PersistentDictionary item) { if (touch_bar_ && [window_ touchBar]) [touch_bar_ setEscapeTouchBarItem:std::move(item) forTouchBar:[window_ touchBar]]; } void NativeWindowMac::SelectPreviousTab() { [window_ selectPreviousTab:nil]; } void NativeWindowMac::SelectNextTab() { [window_ selectNextTab:nil]; } void NativeWindowMac::ShowAllTabs() { [window_ toggleTabOverview:nil]; } void NativeWindowMac::MergeAllWindows() { [window_ mergeAllWindows:nil]; } void NativeWindowMac::MoveTabToNewWindow() { [window_ moveTabToNewWindow:nil]; } void NativeWindowMac::ToggleTabBar() { [window_ toggleTabBar:nil]; } bool NativeWindowMac::AddTabbedWindow(NativeWindow* window) { if (window_ == window->GetNativeWindow().GetNativeNSWindow()) { return false; } else { [window_ addTabbedWindow:window->GetNativeWindow().GetNativeNSWindow() ordered:NSWindowAbove]; } return true; } void NativeWindowMac::SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) { NativeWindow::SetAspectRatio(aspect_ratio, extra_size); // Reset the behaviour to default if aspect_ratio is set to 0 or less. if (aspect_ratio > 0.0) { NSSize aspect_ratio_size = NSMakeSize(aspect_ratio, 1.0); if (has_frame()) [window_ setContentAspectRatio:aspect_ratio_size]; else [window_ setAspectRatio:aspect_ratio_size]; } else { [window_ setResizeIncrements:NSMakeSize(1.0, 1.0)]; } } void NativeWindowMac::PreviewFile(const std::string& path, const std::string& display_name) { preview_item_ = [[ElectronPreviewItem alloc] initWithURL:[NSURL fileURLWithPath:base::SysUTF8ToNSString(path)] title:base::SysUTF8ToNSString(display_name)]; [[QLPreviewPanel sharedPreviewPanel] makeKeyAndOrderFront:nil]; } void NativeWindowMac::CloseFilePreview() { if ([QLPreviewPanel sharedPreviewPanelExists]) { [[QLPreviewPanel sharedPreviewPanel] close]; } } gfx::Rect NativeWindowMac::ContentBoundsToWindowBounds( const gfx::Rect& bounds) const { if (has_frame()) { gfx::Rect window_bounds( [window_ frameRectForContentRect:bounds.ToCGRect()]); int frame_height = window_bounds.height() - bounds.height(); window_bounds.set_y(window_bounds.y() - frame_height); return window_bounds; } else { return bounds; } } gfx::Rect NativeWindowMac::WindowBoundsToContentBounds( const gfx::Rect& bounds) const { if (has_frame()) { gfx::Rect content_bounds( [window_ contentRectForFrameRect:bounds.ToCGRect()]); int frame_height = bounds.height() - content_bounds.height(); content_bounds.set_y(content_bounds.y() + frame_height); return content_bounds; } else { return bounds; } } void NativeWindowMac::NotifyWindowEnterFullScreen() { NativeWindow::NotifyWindowEnterFullScreen(); // Restore the window title under fullscreen mode. if (buttons_proxy_) [window_ setTitleVisibility:NSWindowTitleVisible]; if (transparent() || !has_frame()) [window_ setTitlebarAppearsTransparent:NO]; } void NativeWindowMac::NotifyWindowLeaveFullScreen() { NativeWindow::NotifyWindowLeaveFullScreen(); // Restore window buttons. if (buttons_proxy_ && window_button_visibility_.value_or(true)) { [buttons_proxy_ redraw]; [buttons_proxy_ setVisible:YES]; } if (transparent() || !has_frame()) [window_ setTitlebarAppearsTransparent:YES]; } void NativeWindowMac::NotifyWindowWillEnterFullScreen() { UpdateVibrancyRadii(true); } void NativeWindowMac::NotifyWindowWillLeaveFullScreen() { if (buttons_proxy_) { // Hide window title when leaving fullscreen. [window_ setTitleVisibility:NSWindowTitleHidden]; // Hide the container otherwise traffic light buttons jump. [buttons_proxy_ setVisible:NO]; } UpdateVibrancyRadii(false); } void NativeWindowMac::SetActive(bool is_key) { is_active_ = is_key; } bool NativeWindowMac::IsActive() const { return is_active_; } void NativeWindowMac::Cleanup() { DCHECK(!IsClosed()); ui::NativeTheme::GetInstanceForNativeUi()->RemoveObserver(this); display::Screen::GetScreen()->RemoveObserver(this); } class NativeAppWindowFrameViewMac : public views::NativeFrameViewMac { public: NativeAppWindowFrameViewMac(views::Widget* frame, NativeWindowMac* window) : views::NativeFrameViewMac(frame), native_window_(window) {} NativeAppWindowFrameViewMac(const NativeAppWindowFrameViewMac&) = delete; NativeAppWindowFrameViewMac& operator=(const NativeAppWindowFrameViewMac&) = delete; ~NativeAppWindowFrameViewMac() override = default; // NonClientFrameView: int NonClientHitTest(const gfx::Point& point) override { if (!bounds().Contains(point)) return HTNOWHERE; if (GetWidget()->IsFullscreen()) return HTCLIENT; // Check for possible draggable region in the client area for the frameless // window. int contents_hit_test = native_window_->NonClientHitTest(point); if (contents_hit_test != HTNOWHERE) return contents_hit_test; return HTCLIENT; } private: // Weak. raw_ptr<NativeWindowMac> const native_window_; }; std::unique_ptr<views::NonClientFrameView> NativeWindowMac::CreateNonClientFrameView(views::Widget* widget) { return std::make_unique<NativeAppWindowFrameViewMac>(widget, this); } bool NativeWindowMac::HasStyleMask(NSUInteger flag) const { return [window_ styleMask] & flag; } void NativeWindowMac::SetStyleMask(bool on, NSUInteger flag) { // Changing the styleMask of a frameless windows causes it to change size so // we explicitly disable resizing while setting it. ScopedDisableResize disable_resize; if (on) [window_ setStyleMask:[window_ styleMask] | flag]; else [window_ setStyleMask:[window_ styleMask] & (~flag)]; // Change style mask will make the zoom button revert to default, probably // a bug of Cocoa or macOS. SetMaximizable(maximizable_); } void NativeWindowMac::SetCollectionBehavior(bool on, NSUInteger flag) { if (on) [window_ setCollectionBehavior:[window_ collectionBehavior] | flag]; else [window_ setCollectionBehavior:[window_ collectionBehavior] & (~flag)]; // Change collectionBehavior will make the zoom button revert to default, // probably a bug of Cocoa or macOS. SetMaximizable(maximizable_); } views::View* NativeWindowMac::GetContentsView() { return root_view_.get(); } bool NativeWindowMac::CanMaximize() const { return maximizable_; } void NativeWindowMac::OnNativeThemeUpdated(ui::NativeTheme* observed_theme) { content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&NativeWindow::RedrawTrafficLights, GetWeakPtr())); } void NativeWindowMac::AddContentViewLayers() { // Make sure the bottom corner is rounded for non-modal windows: // http://crbug.com/396264. if (!is_modal()) { // For normal window, we need to explicitly set layer for contentView to // make setBackgroundColor work correctly. // There is no need to do so for frameless window, and doing so would make // titleBarStyle stop working. if (has_frame()) { CALayer* background_layer = [[CALayer alloc] init]; [background_layer setAutoresizingMask:kCALayerWidthSizable | kCALayerHeightSizable]; [[window_ contentView] setLayer:background_layer]; } [[window_ contentView] setWantsLayer:YES]; } } void NativeWindowMac::InternalSetWindowButtonVisibility(bool visible) { [[window_ standardWindowButton:NSWindowCloseButton] setHidden:!visible]; [[window_ standardWindowButton:NSWindowMiniaturizeButton] setHidden:!visible]; [[window_ standardWindowButton:NSWindowZoomButton] setHidden:!visible]; } void NativeWindowMac::InternalSetParentWindow(NativeWindow* new_parent, bool attach) { if (is_modal()) return; // Do not remove/add if we are already properly attached. if (attach && new_parent && [window_ parentWindow] == new_parent->GetNativeWindow().GetNativeNSWindow()) return; // Remove current parent window. RemoveChildFromParentWindow(); // Set new parent window. if (new_parent) { new_parent->add_child_window(this); if (attach) new_parent->AttachChildren(); } NativeWindow::SetParentWindow(new_parent); } void NativeWindowMac::SetForwardMouseMessages(bool forward) { [window_ setAcceptsMouseMovedEvents:forward]; } gfx::Rect NativeWindowMac::GetWindowControlsOverlayRect() { if (titlebar_overlay_ && buttons_proxy_ && window_button_visibility_.value_or(true)) { NSRect buttons = [buttons_proxy_ getButtonsContainerBounds]; gfx::Rect overlay; overlay.set_width(GetContentSize().width() - NSWidth(buttons)); if ([buttons_proxy_ useCustomHeight]) { overlay.set_height(titlebar_overlay_height()); } else { overlay.set_height(NSHeight(buttons)); } if (!base::i18n::IsRTL()) overlay.set_x(NSMaxX(buttons)); return overlay; } return gfx::Rect(); } // static NativeWindow* NativeWindow::Create(const gin_helper::Dictionary& options, NativeWindow* parent) { return new NativeWindowMac(options, parent); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
35,403
[Bug]: macOS - Using frame, roundedCorners, and fullscreen settings together automatically causes a 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 20.0.3 ### What operating system are you using? macOS ### Operating System Version Catalina (confirmed on Big Sur too) ### What arch are you using? x64 ### Last Known Working Electron version Not working in version 17-21 ### Expected Behavior Code such as the following should not crash Electron: ``` win = new BrowserWindow({ title: "Media Window", frame: false, // These 3 options can't be roundedCorners: false, // used concurrently on macOS fullscreen: true // without causing a crash }); ``` ### Actual Behavior The following code crashes Electron on macOS: ``` win = new BrowserWindow({ title: "Media Window", frame: false, // These 3 options can't be roundedCorners: false, // used concurrently on macOS fullscreen: true // without causing a crash }); ``` Any of the following 3 variants does **not** cause the crash: ``` win = new BrowserWindow({ title: "Media Window", // frame: false, roundedCorners: false, fullscreen: true }); ``` ``` win = new BrowserWindow({ title: "Media Window", frame: false, // roundedCorners: false, fullscreen: true }); ``` ``` win = new BrowserWindow({ title: "Media Window", frame: false, roundedCorners: false, // fullscreen: true }); ``` ### Testcase Gist URL https://gist.github.com/sircharlo/c78e81a20c3eb4167037197b3803d76e ### Additional Information Error looks like this: Electron[785:12045] *** Assertion failure in -[ElectronNSWindow titlebarAccessoryViewControllers], /AppleInternal/BuildRoot/Library/Caches/com.apple.xbs/Sources/AppKit/AppKit-1894.60.100/AppKit.subproj/NSWindow.m:3337
https://github.com/electron/electron/issues/35403
https://github.com/electron/electron/pull/39747
2324c4d8fd6f7b2cd336d4e93591464544e12953
ab185c058f894ddc556f67b2853de4adad2bb10c
2022-08-22T15:16:24Z
c++
2023-09-11T07:38:10Z
shell/browser/ui/cocoa/electron_ns_window.h
// Copyright (c) 2018 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_COCOA_ELECTRON_NS_WINDOW_H_ #define ELECTRON_SHELL_BROWSER_UI_COCOA_ELECTRON_NS_WINDOW_H_ #include "base/memory/raw_ptr.h" #include "components/remote_cocoa/app_shim/native_widget_mac_nswindow.h" #include "shell/browser/ui/cocoa/event_dispatching_window.h" #include "ui/views/widget/native_widget_mac.h" namespace electron { class NativeWindowMac; // Prevents window from resizing during the scope. class ScopedDisableResize { public: ScopedDisableResize() { disable_resize_++; } ~ScopedDisableResize() { disable_resize_--; } // True if there are 1+ nested ScopedDisableResize objects in the scope static bool IsResizeDisabled() { return disable_resize_ > 0; } private: static int disable_resize_; }; } // namespace electron @interface ElectronNSWindow : NativeWidgetMacNSWindow { @private raw_ptr<electron::NativeWindowMac> shell_; } @property BOOL acceptsFirstMouse; @property BOOL enableLargerThanScreen; @property BOOL disableAutoHideCursor; @property BOOL disableKeyOrMainWindow; @property(nonatomic, retain) NSVisualEffectView* vibrantView; @property(nonatomic, retain) NSImage* cornerMask; - (id)initWithShell:(electron::NativeWindowMac*)shell styleMask:(NSUInteger)styleMask; - (electron::NativeWindowMac*)shell; - (id)accessibilityFocusedUIElement; - (NSRect)originalContentRectForFrameRect:(NSRect)frameRect; - (void)toggleFullScreenMode:(id)sender; - (NSImage*)_cornerMask; @end #endif // ELECTRON_SHELL_BROWSER_UI_COCOA_ELECTRON_NS_WINDOW_H_
closed
electron/electron
https://github.com/electron/electron
35,403
[Bug]: macOS - Using frame, roundedCorners, and fullscreen settings together automatically causes a 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 20.0.3 ### What operating system are you using? macOS ### Operating System Version Catalina (confirmed on Big Sur too) ### What arch are you using? x64 ### Last Known Working Electron version Not working in version 17-21 ### Expected Behavior Code such as the following should not crash Electron: ``` win = new BrowserWindow({ title: "Media Window", frame: false, // These 3 options can't be roundedCorners: false, // used concurrently on macOS fullscreen: true // without causing a crash }); ``` ### Actual Behavior The following code crashes Electron on macOS: ``` win = new BrowserWindow({ title: "Media Window", frame: false, // These 3 options can't be roundedCorners: false, // used concurrently on macOS fullscreen: true // without causing a crash }); ``` Any of the following 3 variants does **not** cause the crash: ``` win = new BrowserWindow({ title: "Media Window", // frame: false, roundedCorners: false, fullscreen: true }); ``` ``` win = new BrowserWindow({ title: "Media Window", frame: false, // roundedCorners: false, fullscreen: true }); ``` ``` win = new BrowserWindow({ title: "Media Window", frame: false, roundedCorners: false, // fullscreen: true }); ``` ### Testcase Gist URL https://gist.github.com/sircharlo/c78e81a20c3eb4167037197b3803d76e ### Additional Information Error looks like this: Electron[785:12045] *** Assertion failure in -[ElectronNSWindow titlebarAccessoryViewControllers], /AppleInternal/BuildRoot/Library/Caches/com.apple.xbs/Sources/AppKit/AppKit-1894.60.100/AppKit.subproj/NSWindow.m:3337
https://github.com/electron/electron/issues/35403
https://github.com/electron/electron/pull/39747
2324c4d8fd6f7b2cd336d4e93591464544e12953
ab185c058f894ddc556f67b2853de4adad2bb10c
2022-08-22T15:16:24Z
c++
2023-09-11T07:38:10Z
shell/browser/ui/cocoa/electron_ns_window.mm
// Copyright (c) 2018 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/cocoa/electron_ns_window.h" #include "base/strings/sys_string_conversions.h" #include "shell/browser/native_window_mac.h" #include "shell/browser/ui/cocoa/electron_preview_item.h" #include "shell/browser/ui/cocoa/electron_touch_bar.h" #include "shell/browser/ui/cocoa/root_view_mac.h" #include "ui/base/cocoa/window_size_constants.h" #import <objc/message.h> #import <objc/runtime.h> namespace electron { int ScopedDisableResize::disable_resize_ = 0; } // namespace electron @interface NSWindow (PrivateAPI) - (NSImage*)_cornerMask; - (int64_t)_resizeDirectionForMouseLocation:(CGPoint)location; @end // See components/remote_cocoa/app_shim/native_widget_mac_nswindow.mm @interface NSView (CRFrameViewAdditions) - (void)cr_mouseDownOnFrameView:(NSEvent*)event; @end typedef void (*MouseDownImpl)(id, SEL, NSEvent*); namespace { MouseDownImpl g_nsthemeframe_mousedown; MouseDownImpl g_nsnextstepframe_mousedown; } // namespace // This class is never instantiated, it's just a container for our swizzled // mouseDown method. @interface SwizzledMethodsClass : NSView @end @implementation SwizzledMethodsClass - (void)swiz_nsthemeframe_mouseDown:(NSEvent*)event { if ([self.window respondsToSelector:@selector(shell)]) { electron::NativeWindowMac* shell = (electron::NativeWindowMac*)[(id)self.window shell]; if (shell && !shell->has_frame()) [self cr_mouseDownOnFrameView:event]; g_nsthemeframe_mousedown(self, @selector(mouseDown:), event); } } - (void)swiz_nsnextstepframe_mouseDown:(NSEvent*)event { if ([self.window respondsToSelector:@selector(shell)]) { electron::NativeWindowMac* shell = (electron::NativeWindowMac*)[(id)self.window shell]; if (shell && !shell->has_frame()) { [self cr_mouseDownOnFrameView:event]; } g_nsnextstepframe_mousedown(self, @selector(mouseDown:), event); } } - (void)swiz_nsview_swipeWithEvent:(NSEvent*)event { if ([self.window respondsToSelector:@selector(shell)]) { electron::NativeWindowMac* shell = (electron::NativeWindowMac*)[(id)self.window shell]; if (shell) { if (event.deltaY == 1.0) { shell->NotifyWindowSwipe("up"); } else if (event.deltaX == -1.0) { shell->NotifyWindowSwipe("right"); } else if (event.deltaY == -1.0) { shell->NotifyWindowSwipe("down"); } else if (event.deltaX == 1.0) { shell->NotifyWindowSwipe("left"); } } } } @end namespace { #if IS_MAS_BUILD() void SwizzleMouseDown(NSView* frame_view, SEL swiz_selector, MouseDownImpl* orig_impl) { Method original_mousedown = class_getInstanceMethod([frame_view class], @selector(mouseDown:)); *orig_impl = (MouseDownImpl)method_getImplementation(original_mousedown); Method new_mousedown = class_getInstanceMethod([SwizzledMethodsClass class], swiz_selector); method_setImplementation(original_mousedown, method_getImplementation(new_mousedown)); } #else // components/remote_cocoa/app_shim/bridged_content_view.h overrides // swipeWithEvent, so we can't just override the implementation // in ElectronNSWindow like we do with for ex. rotateWithEvent. void SwizzleSwipeWithEvent(NSView* view, SEL swiz_selector) { Method original_swipe_with_event = class_getInstanceMethod([view class], @selector(swipeWithEvent:)); Method new_swipe_with_event = class_getInstanceMethod([SwizzledMethodsClass class], swiz_selector); method_setImplementation(original_swipe_with_event, method_getImplementation(new_swipe_with_event)); } #endif } // namespace @implementation ElectronNSWindow @synthesize acceptsFirstMouse; @synthesize enableLargerThanScreen; @synthesize disableAutoHideCursor; @synthesize disableKeyOrMainWindow; @synthesize vibrantView; @synthesize cornerMask; - (id)initWithShell:(electron::NativeWindowMac*)shell styleMask:(NSUInteger)styleMask { if ((self = [super initWithContentRect:ui::kWindowSizeDeterminedLater styleMask:styleMask backing:NSBackingStoreBuffered defer:NO])) { #if IS_MAS_BUILD() // The first time we create a frameless window, we swizzle the // implementation of -[NSNextStepFrame mouseDown:], replacing it with our // own. // This is only necessary on MAS where we can't directly refer to // NSNextStepFrame or NSThemeFrame, as they are private APIs. // See components/remote_cocoa/app_shim/native_widget_mac_nswindow.mm for // the non-MAS-compatible way of doing this. if (styleMask & NSWindowStyleMaskTitled) { if (!g_nsthemeframe_mousedown) { NSView* theme_frame = [[self contentView] superview]; DCHECK(strcmp(class_getName([theme_frame class]), "NSThemeFrame") == 0) << "Expected NSThemeFrame but was " << class_getName([theme_frame class]); SwizzleMouseDown(theme_frame, @selector(swiz_nsthemeframe_mouseDown:), &g_nsthemeframe_mousedown); } } else { if (!g_nsnextstepframe_mousedown) { NSView* nextstep_frame = [[self contentView] superview]; DCHECK(strcmp(class_getName([nextstep_frame class]), "NSNextStepFrame") == 0) << "Expected NSNextStepFrame but was " << class_getName([nextstep_frame class]); SwizzleMouseDown(nextstep_frame, @selector(swiz_nsnextstepframe_mouseDown:), &g_nsnextstepframe_mousedown); } } #else NSView* view = [[self contentView] superview]; SwizzleSwipeWithEvent(view, @selector(swiz_nsview_swipeWithEvent:)); #endif // IS_MAS_BUILD shell_ = shell; } return self; } - (electron::NativeWindowMac*)shell { return shell_; } - (id)accessibilityFocusedUIElement { views::Widget* widget = shell_->widget(); id superFocus = [super accessibilityFocusedUIElement]; if (!widget || shell_->IsFocused()) return superFocus; return nil; } - (NSRect)originalContentRectForFrameRect:(NSRect)frameRect { return [super contentRectForFrameRect:frameRect]; } - (NSTouchBar*)makeTouchBar { if (shell_->touch_bar()) return [shell_->touch_bar() makeTouchBar]; else return nil; } // NSWindow overrides. - (void)rotateWithEvent:(NSEvent*)event { shell_->NotifyWindowRotateGesture(event.rotation); } - (NSRect)contentRectForFrameRect:(NSRect)frameRect { if (shell_->has_frame()) return [super contentRectForFrameRect:frameRect]; else return frameRect; } - (NSRect)constrainFrameRect:(NSRect)frameRect toScreen:(NSScreen*)screen { // Resizing is disabled. if (electron::ScopedDisableResize::IsResizeDisabled()) return [self frame]; NSRect result = [super constrainFrameRect:frameRect toScreen:screen]; // Enable the window to be larger than screen. if ([self enableLargerThanScreen]) { // If we have a frame, ensure that we only position the window // somewhere where the user can move or resize it (and not // behind the menu bar, for instance) // // If there's no frame, put the window wherever the developer // wanted it to go if (shell_->has_frame()) { result.size = frameRect.size; } else { result = frameRect; } } return result; } - (void)setFrame:(NSRect)windowFrame display:(BOOL)displayViews { // constrainFrameRect is not called on hidden windows so disable adjusting // the frame directly when resize is disabled if (!electron::ScopedDisableResize::IsResizeDisabled()) [super setFrame:windowFrame display:displayViews]; } - (id)accessibilityAttributeValue:(NSString*)attribute { if ([attribute isEqual:NSAccessibilityEnabledAttribute]) return [NSNumber numberWithBool:YES]; if (![attribute isEqualToString:@"AXChildren"]) return [super accessibilityAttributeValue:attribute]; // We want to remove the window title (also known as // NSAccessibilityReparentingCellProxy), which VoiceOver already sees. // * when VoiceOver is disabled, this causes Cmd+C to be used for TTS but // still leaves the buttons available in the accessibility tree. // * when VoiceOver is enabled, the full accessibility tree is used. // Without removing the title and with VO disabled, the TTS would always read // the window title instead of using Cmd+C to get the selected text. NSPredicate* predicate = [NSPredicate predicateWithFormat:@"(self.className != %@)", @"NSAccessibilityReparentingCellProxy"]; NSArray* children = [super accessibilityAttributeValue:attribute]; NSMutableArray* mutableChildren = [children mutableCopy]; [mutableChildren filterUsingPredicate:predicate]; return mutableChildren; } - (NSString*)accessibilityTitle { return base::SysUTF8ToNSString(shell_->GetTitle()); } - (BOOL)canBecomeMainWindow { return !self.disableKeyOrMainWindow; } - (BOOL)canBecomeKeyWindow { return !self.disableKeyOrMainWindow; } - (NSView*)frameView { return [[self contentView] superview]; } - (BOOL)validateUserInterfaceItem:(id<NSValidatedUserInterfaceItem>)item { // By default "Close Window" is always disabled when window has no title, to // support closing a window without title we need to manually do menu item // validation. This code path is used by the "roundedCorners" option. if ([item action] == @selector(performClose:)) return shell_->IsClosable(); return [super validateUserInterfaceItem:item]; } // By overriding this built-in method the corners of the vibrant view (if set) // will be smooth. - (NSImage*)_cornerMask { if (self.vibrantView != nil) { return [self cornerMask]; } else { return [super _cornerMask]; } } // Quicklook methods - (BOOL)acceptsPreviewPanelControl:(QLPreviewPanel*)panel { return YES; } - (void)beginPreviewPanelControl:(QLPreviewPanel*)panel { panel.dataSource = static_cast<id<QLPreviewPanelDataSource>>([self delegate]); } - (void)endPreviewPanelControl:(QLPreviewPanel*)panel { panel.dataSource = nil; } // Custom window button methods - (BOOL)windowShouldClose:(id)sender { return YES; } - (void)performClose:(id)sender { if (shell_->title_bar_style() == electron::NativeWindowMac::TitleBarStyle::kCustomButtonsOnHover) { [[self delegate] windowShouldClose:self]; } else if (!([self styleMask] & NSWindowStyleMaskTitled)) { // performClose does not work for windows without title, so we have to // emulate its behavior. This code path is used by "simpleFullscreen" and // "roundedCorners" options. if ([[self delegate] respondsToSelector:@selector(windowShouldClose:)]) { if (![[self delegate] windowShouldClose:self]) return; } else if ([self respondsToSelector:@selector(windowShouldClose:)]) { if (![self windowShouldClose:self]) return; } [self close]; } else if (shell_->is_modal() && shell_->parent() && shell_->IsVisible()) { // We don't want to actually call [window close] here since // we've already called endSheet on the modal sheet. return; } else { [super performClose:sender]; } } - (void)toggleFullScreenMode:(id)sender { bool is_simple_fs = shell_->IsSimpleFullScreen(); bool always_simple_fs = shell_->always_simple_fullscreen(); // If we're in simple fullscreen mode and trying to exit it // we need to ensure we exit it properly to prevent a crash // with NSWindowStyleMaskTitled mode. if (is_simple_fs || always_simple_fs) { shell_->SetSimpleFullScreen(!is_simple_fs); } else { if (shell_->IsVisible()) { // Until 10.13, AppKit would obey a call to -toggleFullScreen: made inside // windowDidEnterFullScreen & windowDidExitFullScreen. Starting in 10.13, // it behaves as though the transition is still in progress and just emits // "not in a fullscreen state" when trying to exit fullscreen in the same // runloop that entered it. To handle this, invoke -toggleFullScreen: // asynchronously. [super performSelector:@selector(toggleFullScreen:) withObject:nil afterDelay:0]; } else { [super toggleFullScreen:sender]; } // Exiting fullscreen causes Cocoa to redraw the NSWindow, which resets // the enabled state for NSWindowZoomButton. We need to persist it. bool maximizable = shell_->IsMaximizable(); shell_->SetMaximizable(maximizable); } } - (void)performMiniaturize:(id)sender { if (shell_->title_bar_style() == electron::NativeWindowMac::TitleBarStyle::kCustomButtonsOnHover) [self miniaturize:self]; else [super performMiniaturize:sender]; } @end
closed
electron/electron
https://github.com/electron/electron
35,403
[Bug]: macOS - Using frame, roundedCorners, and fullscreen settings together automatically causes a 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 20.0.3 ### What operating system are you using? macOS ### Operating System Version Catalina (confirmed on Big Sur too) ### What arch are you using? x64 ### Last Known Working Electron version Not working in version 17-21 ### Expected Behavior Code such as the following should not crash Electron: ``` win = new BrowserWindow({ title: "Media Window", frame: false, // These 3 options can't be roundedCorners: false, // used concurrently on macOS fullscreen: true // without causing a crash }); ``` ### Actual Behavior The following code crashes Electron on macOS: ``` win = new BrowserWindow({ title: "Media Window", frame: false, // These 3 options can't be roundedCorners: false, // used concurrently on macOS fullscreen: true // without causing a crash }); ``` Any of the following 3 variants does **not** cause the crash: ``` win = new BrowserWindow({ title: "Media Window", // frame: false, roundedCorners: false, fullscreen: true }); ``` ``` win = new BrowserWindow({ title: "Media Window", frame: false, // roundedCorners: false, fullscreen: true }); ``` ``` win = new BrowserWindow({ title: "Media Window", frame: false, roundedCorners: false, // fullscreen: true }); ``` ### Testcase Gist URL https://gist.github.com/sircharlo/c78e81a20c3eb4167037197b3803d76e ### Additional Information Error looks like this: Electron[785:12045] *** Assertion failure in -[ElectronNSWindow titlebarAccessoryViewControllers], /AppleInternal/BuildRoot/Library/Caches/com.apple.xbs/Sources/AppKit/AppKit-1894.60.100/AppKit.subproj/NSWindow.m:3337
https://github.com/electron/electron/issues/35403
https://github.com/electron/electron/pull/39747
2324c4d8fd6f7b2cd336d4e93591464544e12953
ab185c058f894ddc556f67b2853de4adad2bb10c
2022-08-22T15:16:24Z
c++
2023-09-11T07:38:10Z
shell/browser/native_window_mac.mm
// 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_mac.h" #include <AvailabilityMacros.h> #include <objc/objc-runtime.h> #include <algorithm> #include <memory> #include <string> #include <utility> #include <vector> #include "base/apple/scoped_cftyperef.h" #include "base/mac/mac_util.h" #include "base/strings/sys_string_conversions.h" #include "components/remote_cocoa/app_shim/native_widget_ns_window_bridge.h" #include "components/remote_cocoa/browser/scoped_cg_window_id.h" #include "content/public/browser/browser_accessibility_state.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/desktop_media_id.h" #include "shell/browser/browser.h" #include "shell/browser/javascript_environment.h" #include "shell/browser/native_browser_view_mac.h" #include "shell/browser/ui/cocoa/electron_native_widget_mac.h" #include "shell/browser/ui/cocoa/electron_ns_window.h" #include "shell/browser/ui/cocoa/electron_ns_window_delegate.h" #include "shell/browser/ui/cocoa/electron_preview_item.h" #include "shell/browser/ui/cocoa/electron_touch_bar.h" #include "shell/browser/ui/cocoa/root_view_mac.h" #include "shell/browser/ui/cocoa/window_buttons_proxy.h" #include "shell/browser/ui/drag_util.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/window_list.h" #include "shell/common/gin_converters/gfx_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/node_includes.h" #include "shell/common/options_switches.h" #include "shell/common/process_util.h" #include "skia/ext/skia_utils_mac.h" #include "third_party/skia/include/core/SkRegion.h" #include "third_party/webrtc/modules/desktop_capture/mac/window_list_utils.h" #include "ui/base/hit_test.h" #include "ui/display/screen.h" #include "ui/gfx/skia_util.h" #include "ui/gl/gpu_switching_manager.h" #include "ui/views/background.h" #include "ui/views/cocoa/native_widget_mac_ns_window_host.h" #include "ui/views/widget/widget.h" #include "ui/views/window/native_frame_view_mac.h" @interface ElectronProgressBar : NSProgressIndicator @end @implementation ElectronProgressBar - (void)drawRect:(NSRect)dirtyRect { if (self.style != NSProgressIndicatorStyleBar) return; // Draw edges of rounded rect. NSRect rect = NSInsetRect([self bounds], 1.0, 1.0); CGFloat radius = rect.size.height / 2; NSBezierPath* bezier_path = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [bezier_path setLineWidth:2.0]; [[NSColor grayColor] set]; [bezier_path stroke]; // Fill the rounded rect. rect = NSInsetRect(rect, 2.0, 2.0); radius = rect.size.height / 2; bezier_path = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [bezier_path setLineWidth:1.0]; [bezier_path addClip]; // Calculate the progress width. rect.size.width = floor(rect.size.width * ([self doubleValue] / [self maxValue])); // Fill the progress bar with color blue. [[NSColor colorWithSRGBRed:0.2 green:0.6 blue:1 alpha:1] set]; NSRectFill(rect); } @end namespace gin { template <> struct Converter<electron::NativeWindowMac::VisualEffectState> { static bool FromV8(v8::Isolate* isolate, v8::Handle<v8::Value> val, electron::NativeWindowMac::VisualEffectState* out) { using VisualEffectState = electron::NativeWindowMac::VisualEffectState; std::string visual_effect_state; if (!ConvertFromV8(isolate, val, &visual_effect_state)) return false; if (visual_effect_state == "followWindow") { *out = VisualEffectState::kFollowWindow; } else if (visual_effect_state == "active") { *out = VisualEffectState::kActive; } else if (visual_effect_state == "inactive") { *out = VisualEffectState::kInactive; } else { return false; } return true; } }; } // namespace gin namespace electron { namespace { bool IsFramelessWindow(NSView* view) { NSWindow* nswindow = [view window]; if (![nswindow respondsToSelector:@selector(shell)]) return false; NativeWindow* window = [static_cast<ElectronNSWindow*>(nswindow) shell]; return window && !window->has_frame(); } IMP original_set_frame_size = nullptr; IMP original_view_did_move_to_superview = nullptr; // This method is directly called by NSWindow during a window resize on OSX // 10.10.0, beta 2. We must override it to prevent the content view from // shrinking. void SetFrameSize(NSView* self, SEL _cmd, NSSize size) { if (!IsFramelessWindow(self)) { auto original = reinterpret_cast<decltype(&SetFrameSize)>(original_set_frame_size); return original(self, _cmd, size); } // For frameless window, resize the view to cover full window. if ([self superview]) size = [[self superview] bounds].size; auto super_impl = reinterpret_cast<decltype(&SetFrameSize)>( [[self superclass] instanceMethodForSelector:_cmd]); super_impl(self, _cmd, size); } // The contentView gets moved around during certain full-screen operations. // This is less than ideal, and should eventually be removed. void ViewDidMoveToSuperview(NSView* self, SEL _cmd) { if (!IsFramelessWindow(self)) { // [BridgedContentView viewDidMoveToSuperview]; auto original = reinterpret_cast<decltype(&ViewDidMoveToSuperview)>( original_view_did_move_to_superview); if (original) original(self, _cmd); return; } [self setFrame:[[self superview] bounds]]; } // -[NSWindow orderWindow] does not handle reordering for children // windows. Their order is fixed to the attachment order (the last attached // window is on the top). Therefore, work around it by re-parenting in our // desired order. void ReorderChildWindowAbove(NSWindow* child_window, NSWindow* other_window) { NSWindow* parent = [child_window parentWindow]; DCHECK(parent); // `ordered_children` sorts children windows back to front. NSArray<NSWindow*>* children = [[child_window parentWindow] childWindows]; std::vector<std::pair<NSInteger, NSWindow*>> ordered_children; for (NSWindow* child in children) ordered_children.push_back({[child orderedIndex], child}); std::sort(ordered_children.begin(), ordered_children.end(), std::greater<>()); // If `other_window` is nullptr, place `child_window` in front of // all other children windows. if (other_window == nullptr) other_window = ordered_children.back().second; if (child_window == other_window) return; for (NSWindow* child in children) [parent removeChildWindow:child]; const bool relative_to_parent = parent == other_window; if (relative_to_parent) [parent addChildWindow:child_window ordered:NSWindowAbove]; // Re-parent children windows in the desired order. for (auto [ordered_index, child] : ordered_children) { if (child != child_window && child != other_window) { [parent addChildWindow:child ordered:NSWindowAbove]; } else if (child == other_window && !relative_to_parent) { [parent addChildWindow:other_window ordered:NSWindowAbove]; [parent addChildWindow:child_window ordered:NSWindowAbove]; } } } } // namespace NativeWindowMac::NativeWindowMac(const gin_helper::Dictionary& options, NativeWindow* parent) : NativeWindow(options, parent), root_view_(new RootViewMac(this)) { ui::NativeTheme::GetInstanceForNativeUi()->AddObserver(this); display::Screen::GetScreen()->AddObserver(this); int width = 800, height = 600; options.Get(options::kWidth, &width); options.Get(options::kHeight, &height); NSRect main_screen_rect = [[[NSScreen screens] firstObject] frame]; gfx::Rect bounds(round((NSWidth(main_screen_rect) - width) / 2), round((NSHeight(main_screen_rect) - height) / 2), width, height); bool resizable = true; options.Get(options::kResizable, &resizable); options.Get(options::kZoomToPageWidth, &zoom_to_page_width_); options.Get(options::kSimpleFullScreen, &always_simple_fullscreen_); options.GetOptional(options::kTrafficLightPosition, &traffic_light_position_); options.Get(options::kVisualEffectState, &visual_effect_state_); if (options.Has(options::kFullscreenWindowTitle)) { EmitWarning( node::Environment::GetCurrent(JavascriptEnvironment::GetIsolate()), "\"fullscreenWindowTitle\" option has been deprecated and is " "no-op now.", "electron"); } bool minimizable = true; options.Get(options::kMinimizable, &minimizable); bool maximizable = true; options.Get(options::kMaximizable, &maximizable); bool closable = true; options.Get(options::kClosable, &closable); std::string tabbingIdentifier; options.Get(options::kTabbingIdentifier, &tabbingIdentifier); std::string windowType; options.Get(options::kType, &windowType); bool hiddenInMissionControl = false; options.Get(options::kHiddenInMissionControl, &hiddenInMissionControl); bool useStandardWindow = true; // eventually deprecate separate "standardWindow" option in favor of // standard / textured window types options.Get(options::kStandardWindow, &useStandardWindow); if (windowType == "textured") { useStandardWindow = false; } // The window without titlebar is treated the same with frameless window. if (title_bar_style_ != TitleBarStyle::kNormal) set_has_frame(false); NSUInteger styleMask = NSWindowStyleMaskTitled; // The NSWindowStyleMaskFullSizeContentView style removes rounded corners // for frameless window. bool rounded_corner = true; options.Get(options::kRoundedCorners, &rounded_corner); if (!rounded_corner && !has_frame()) styleMask = NSWindowStyleMaskBorderless; if (minimizable) styleMask |= NSWindowStyleMaskMiniaturizable; if (closable) styleMask |= NSWindowStyleMaskClosable; if (resizable) styleMask |= NSWindowStyleMaskResizable; if (!useStandardWindow || transparent() || !has_frame()) styleMask |= NSWindowStyleMaskTexturedBackground; // Create views::Widget and assign window_ with it. // TODO(zcbenz): Get rid of the window_ in future. 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.native_widget = new ElectronNativeWidgetMac(this, windowType, styleMask, widget()); widget()->Init(std::move(params)); SetCanResize(resizable); window_ = static_cast<ElectronNSWindow*>( widget()->GetNativeWindow().GetNativeNSWindow()); RegisterDeleteDelegateCallback(base::BindOnce( [](NativeWindowMac* window) { if (window->window_) window->window_ = nil; if (window->buttons_proxy_) window->buttons_proxy_ = nil; }, this)); [window_ setEnableLargerThanScreen:enable_larger_than_screen()]; window_delegate_ = [[ElectronNSWindowDelegate alloc] initWithShell:this]; [window_ setDelegate:window_delegate_]; // Only use native parent window for non-modal windows. if (parent && !is_modal()) { SetParentWindow(parent); } if (transparent()) { // Setting the background color to clear will also hide the shadow. [window_ setBackgroundColor:[NSColor clearColor]]; } if (windowType == "desktop") { [window_ setLevel:kCGDesktopWindowLevel - 1]; [window_ setDisableKeyOrMainWindow:YES]; [window_ setCollectionBehavior:(NSWindowCollectionBehaviorCanJoinAllSpaces | NSWindowCollectionBehaviorStationary | NSWindowCollectionBehaviorIgnoresCycle)]; } if (windowType == "panel") { [window_ setLevel:NSFloatingWindowLevel]; } bool focusable; if (options.Get(options::kFocusable, &focusable) && !focusable) [window_ setDisableKeyOrMainWindow:YES]; if (transparent() || !has_frame()) { // Don't show title bar. [window_ setTitlebarAppearsTransparent:YES]; [window_ setTitleVisibility:NSWindowTitleHidden]; // Remove non-transparent corners, see // https://github.com/electron/electron/issues/517. [window_ setOpaque:NO]; // Show window buttons if titleBarStyle is not "normal". if (title_bar_style_ == TitleBarStyle::kNormal) { InternalSetWindowButtonVisibility(false); } else { buttons_proxy_ = [[WindowButtonsProxy alloc] initWithWindow:window_]; [buttons_proxy_ setHeight:titlebar_overlay_height()]; if (traffic_light_position_) { [buttons_proxy_ setMargin:*traffic_light_position_]; } else if (title_bar_style_ == TitleBarStyle::kHiddenInset) { // For macOS >= 11, while this value does not match official macOS apps // like Safari or Notes, it matches titleBarStyle's old implementation // before Electron <= 12. [buttons_proxy_ setMargin:gfx::Point(12, 11)]; } if (title_bar_style_ == TitleBarStyle::kCustomButtonsOnHover) { [buttons_proxy_ setShowOnHover:YES]; } else { // customButtonsOnHover does not show buttons initially. InternalSetWindowButtonVisibility(true); } } } // Create a tab only if tabbing identifier is specified and window has // a native title bar. if (tabbingIdentifier.empty() || transparent() || !has_frame()) { [window_ setTabbingMode:NSWindowTabbingModeDisallowed]; } else { [window_ setTabbingIdentifier:base::SysUTF8ToNSString(tabbingIdentifier)]; } // Resize to content bounds. bool use_content_size = false; options.Get(options::kUseContentSize, &use_content_size); if (!has_frame() || use_content_size) SetContentSize(gfx::Size(width, height)); // Enable the NSView to accept first mouse event. bool acceptsFirstMouse = false; options.Get(options::kAcceptFirstMouse, &acceptsFirstMouse); [window_ setAcceptsFirstMouse:acceptsFirstMouse]; // Disable auto-hiding cursor. bool disableAutoHideCursor = false; options.Get(options::kDisableAutoHideCursor, &disableAutoHideCursor); [window_ setDisableAutoHideCursor:disableAutoHideCursor]; SetHiddenInMissionControl(hiddenInMissionControl); // Set maximizable state last to ensure zoom button does not get reset // by calls to other APIs. SetMaximizable(maximizable); // Default content view. SetContentView(new views::View()); AddContentViewLayers(); UpdateWindowOriginalFrame(); original_level_ = [window_ level]; } NativeWindowMac::~NativeWindowMac() = default; void NativeWindowMac::SetContentView(views::View* view) { views::View* root_view = GetContentsView(); if (content_view()) root_view->RemoveChildView(content_view()); set_content_view(view); root_view->AddChildView(content_view()); root_view->Layout(); } void NativeWindowMac::Close() { if (!IsClosable()) { WindowList::WindowCloseCancelled(this); return; } if (fullscreen_transition_state() != FullScreenTransitionState::kNone) { SetHasDeferredWindowClose(true); return; } // Ensure we're detached from the parent window before closing. RemoveChildFromParentWindow(); while (!child_windows_.empty()) { auto* child = child_windows_.back(); child->RemoveChildFromParentWindow(); } // If a sheet is attached to the window when we call // [window_ performClose:nil], the window won't close properly // even after the user has ended the sheet. // Ensure it's closed before calling [window_ performClose:nil]. if ([window_ attachedSheet]) [window_ endSheet:[window_ attachedSheet]]; [window_ performClose:nil]; // Closing a sheet doesn't trigger windowShouldClose, // so we need to manually call it ourselves here. if (is_modal() && parent() && IsVisible()) { NotifyWindowCloseButtonClicked(); } } void NativeWindowMac::CloseImmediately() { // Ensure we're detached from the parent window before closing. RemoveChildFromParentWindow(); while (!child_windows_.empty()) { auto* child = child_windows_.back(); child->RemoveChildFromParentWindow(); } [window_ close]; } void NativeWindowMac::Focus(bool focus) { if (!IsVisible()) return; if (focus) { [[NSApplication sharedApplication] activateIgnoringOtherApps:NO]; [window_ makeKeyAndOrderFront:nil]; } else { [window_ orderOut:nil]; [window_ orderBack:nil]; } } bool NativeWindowMac::IsFocused() { return [window_ isKeyWindow]; } void NativeWindowMac::Show() { if (is_modal() && parent()) { NSWindow* window = parent()->GetNativeWindow().GetNativeNSWindow(); if ([window_ sheetParent] == nil) [window beginSheet:window_ completionHandler:^(NSModalResponse){ }]; return; } // Reattach the window to the parent to actually show it. if (parent()) InternalSetParentWindow(parent(), true); // This method is supposed to put focus on window, however if the app does not // have focus then "makeKeyAndOrderFront" will only show the window. [NSApp activateIgnoringOtherApps:YES]; [window_ makeKeyAndOrderFront:nil]; } void NativeWindowMac::ShowInactive() { // Reattach the window to the parent to actually show it. if (parent()) InternalSetParentWindow(parent(), true); [window_ orderFrontRegardless]; } void NativeWindowMac::Hide() { // If a sheet is attached to the window when we call [window_ orderOut:nil], // the sheet won't be able to show again on the same window. // Ensure it's closed before calling [window_ orderOut:nil]. if ([window_ attachedSheet]) [window_ endSheet:[window_ attachedSheet]]; if (is_modal() && parent()) { [window_ orderOut:nil]; [parent()->GetNativeWindow().GetNativeNSWindow() endSheet:window_]; return; } DetachChildren(); // Detach the window from the parent before. if (parent()) InternalSetParentWindow(parent(), false); [window_ orderOut:nil]; } bool NativeWindowMac::IsVisible() { bool occluded = [window_ occlusionState] == NSWindowOcclusionStateVisible; return [window_ isVisible] && !occluded && !IsMinimized(); } bool NativeWindowMac::IsEnabled() { return [window_ attachedSheet] == nil; } void NativeWindowMac::SetEnabled(bool enable) { if (!enable) { NSRect frame = [window_ frame]; NSWindow* window = [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, frame.size.width, frame.size.height) styleMask:NSWindowStyleMaskTitled backing:NSBackingStoreBuffered defer:NO]; [window setAlphaValue:0.5]; [window_ beginSheet:window completionHandler:^(NSModalResponse returnCode) { NSLog(@"main window disabled"); return; }]; } else if ([window_ attachedSheet]) { [window_ endSheet:[window_ attachedSheet]]; } } void NativeWindowMac::Maximize() { const bool is_visible = [window_ isVisible]; if (IsMaximized()) { if (!is_visible) ShowInactive(); return; } // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); [window_ zoom:nil]; if (!is_visible) { ShowInactive(); NotifyWindowMaximize(); } } void NativeWindowMac::Unmaximize() { // Bail if the last user set bounds were the same size as the window // screen (e.g. the user set the window to maximized via setBounds) // // Per docs during zoom: // > If there’s no saved user state because there has been no previous // > zoom,the size and location of the window don’t change. // // However, in classic Apple fashion, this is not the case in practice, // and the frame inexplicably becomes very tiny. We should prevent // zoom from being called if the window is being unmaximized and its // unmaximized window bounds are themselves functionally maximized. if (!IsMaximized() || user_set_bounds_maximized_) return; [window_ zoom:nil]; } bool NativeWindowMac::IsMaximized() { // It's possible for [window_ isZoomed] to be true // when the window is minimized or fullscreened. if (IsMinimized() || IsFullscreen()) return false; if (HasStyleMask(NSWindowStyleMaskResizable) != 0) return [window_ isZoomed]; NSRect rectScreen = GetAspectRatio() > 0.0 ? default_frame_for_zoom() : [[NSScreen mainScreen] visibleFrame]; return NSEqualRects([window_ frame], rectScreen); } void NativeWindowMac::Minimize() { if (IsMinimized()) return; // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); [window_ miniaturize:nil]; } void NativeWindowMac::Restore() { [window_ deminiaturize:nil]; } bool NativeWindowMac::IsMinimized() { return [window_ isMiniaturized]; } bool NativeWindowMac::HandleDeferredClose() { if (has_deferred_window_close_) { SetHasDeferredWindowClose(false); Close(); return true; } return false; } void NativeWindowMac::RemoveChildWindow(NativeWindow* child) { child_windows_.remove_if([&child](NativeWindow* w) { return (w == child); }); [window_ removeChildWindow:child->GetNativeWindow().GetNativeNSWindow()]; } void NativeWindowMac::RemoveChildFromParentWindow() { if (parent() && !is_modal()) { parent()->RemoveChildWindow(this); NativeWindow::SetParentWindow(nullptr); } } void NativeWindowMac::AttachChildren() { for (auto* child : child_windows_) { auto* child_nswindow = child->GetNativeWindow().GetNativeNSWindow(); if ([child_nswindow parentWindow] == window_) continue; // Attaching a window as a child window resets its window level, so // save and restore it afterwards. NSInteger level = window_.level; [window_ addChildWindow:child_nswindow ordered:NSWindowAbove]; [window_ setLevel:level]; } } void NativeWindowMac::DetachChildren() { DCHECK(child_windows_.size() == [[window_ childWindows] count]); // Hide all children before hiding/minimizing the window. // NativeWidgetNSWindowBridge::NotifyVisibilityChangeDown() // will DCHECK otherwise. for (auto* child : child_windows_) { [child->GetNativeWindow().GetNativeNSWindow() orderOut:nil]; } } void NativeWindowMac::SetFullScreen(bool fullscreen) { if (!has_frame() && !HasStyleMask(NSWindowStyleMaskTitled)) return; // [NSWindow -toggleFullScreen] is an asynchronous operation, which means // that it's possible to call it while a fullscreen transition is currently // in process. This can create weird behavior (incl. phantom windows), // so we want to schedule a transition for when the current one has completed. if (fullscreen_transition_state() != FullScreenTransitionState::kNone) { if (!pending_transitions_.empty()) { bool last_pending = pending_transitions_.back(); // Only push new transitions if they're different than the last transition // in the queue. if (last_pending != fullscreen) pending_transitions_.push(fullscreen); } else { pending_transitions_.push(fullscreen); } return; } if (fullscreen == IsFullscreen() || !IsFullScreenable()) return; // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); // This needs to be set here because it can be the case that // SetFullScreen is called by a user before windowWillEnterFullScreen // or windowWillExitFullScreen are invoked, and so a potential transition // could be dropped. fullscreen_transition_state_ = fullscreen ? FullScreenTransitionState::kEntering : FullScreenTransitionState::kExiting; [window_ toggleFullScreenMode:nil]; } bool NativeWindowMac::IsFullscreen() const { return HasStyleMask(NSWindowStyleMaskFullScreen); } void NativeWindowMac::SetBounds(const gfx::Rect& bounds, bool animate) { // Do nothing if in fullscreen mode. if (IsFullscreen()) return; // Check size constraints since setFrame does not check it. gfx::Size size = bounds.size(); size.SetToMax(GetMinimumSize()); gfx::Size max_size = GetMaximumSize(); if (!max_size.IsEmpty()) size.SetToMin(max_size); NSRect cocoa_bounds = NSMakeRect(bounds.x(), 0, size.width(), size.height()); // Flip coordinates based on the primary screen. NSScreen* screen = [[NSScreen screens] firstObject]; cocoa_bounds.origin.y = NSHeight([screen frame]) - size.height() - bounds.y(); [window_ setFrame:cocoa_bounds display:YES animate:animate]; user_set_bounds_maximized_ = IsMaximized() ? true : false; UpdateWindowOriginalFrame(); } gfx::Rect NativeWindowMac::GetBounds() { NSRect frame = [window_ frame]; gfx::Rect bounds(frame.origin.x, 0, NSWidth(frame), NSHeight(frame)); NSScreen* screen = [[NSScreen screens] firstObject]; bounds.set_y(NSHeight([screen frame]) - NSMaxY(frame)); return bounds; } bool NativeWindowMac::IsNormal() { return NativeWindow::IsNormal() && !IsSimpleFullScreen(); } gfx::Rect NativeWindowMac::GetNormalBounds() { if (IsNormal()) { return GetBounds(); } NSRect frame = original_frame_; gfx::Rect bounds(frame.origin.x, 0, NSWidth(frame), NSHeight(frame)); NSScreen* screen = [[NSScreen screens] firstObject]; bounds.set_y(NSHeight([screen frame]) - NSMaxY(frame)); return bounds; // Works on OS_WIN ! // return widget()->GetRestoredBounds(); } void NativeWindowMac::SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints) { auto convertSize = [this](const gfx::Size& size) { // Our frameless window still has titlebar attached, so setting contentSize // will result in actual content size being larger. if (!has_frame()) { NSRect frame = NSMakeRect(0, 0, size.width(), size.height()); NSRect content = [window_ originalContentRectForFrameRect:frame]; return content.size; } else { return NSMakeSize(size.width(), size.height()); } }; NSView* content = [window_ contentView]; if (size_constraints.HasMinimumSize()) { NSSize min_size = convertSize(size_constraints.GetMinimumSize()); [window_ setContentMinSize:[content convertSize:min_size toView:nil]]; } if (size_constraints.HasMaximumSize()) { NSSize max_size = convertSize(size_constraints.GetMaximumSize()); [window_ setContentMaxSize:[content convertSize:max_size toView:nil]]; } NativeWindow::SetContentSizeConstraints(size_constraints); } bool NativeWindowMac::MoveAbove(const std::string& sourceId) { const content::DesktopMediaID id = content::DesktopMediaID::Parse(sourceId); if (id.type != content::DesktopMediaID::TYPE_WINDOW) return false; // Check if the window source is valid. const CGWindowID window_id = id.id; if (!webrtc::GetWindowOwnerPid(window_id)) return false; if (!parent() || is_modal()) { [window_ orderWindow:NSWindowAbove relativeTo:window_id]; } else { NSWindow* other_window = [NSApp windowWithWindowNumber:window_id]; ReorderChildWindowAbove(window_, other_window); } return true; } void NativeWindowMac::MoveTop() { if (!parent() || is_modal()) { [window_ orderWindow:NSWindowAbove relativeTo:0]; } else { ReorderChildWindowAbove(window_, nullptr); } } void NativeWindowMac::SetResizable(bool resizable) { ScopedDisableResize disable_resize; SetStyleMask(resizable, NSWindowStyleMaskResizable); bool was_fullscreenable = IsFullScreenable(); // Right now, resizable and fullscreenable are decoupled in // documentation and on Windows/Linux. Chromium disables // fullscreen collection behavior as well as the maximize traffic // light in SetCanResize if resizability is false on macOS unless // the window is both resizable and maximizable. We want consistent // cross-platform behavior, so if resizability is disabled we disable // the maximize button and ensure fullscreenability matches user setting. SetCanResize(resizable); SetFullScreenable(was_fullscreenable); [[window_ standardWindowButton:NSWindowZoomButton] setEnabled:resizable ? was_fullscreenable : false]; } bool NativeWindowMac::IsResizable() { bool in_fs_transition = fullscreen_transition_state() != FullScreenTransitionState::kNone; bool has_rs_mask = HasStyleMask(NSWindowStyleMaskResizable); return has_rs_mask && !IsFullscreen() && !in_fs_transition; } void NativeWindowMac::SetMovable(bool movable) { [window_ setMovable:movable]; } bool NativeWindowMac::IsMovable() { return [window_ isMovable]; } void NativeWindowMac::SetMinimizable(bool minimizable) { SetStyleMask(minimizable, NSWindowStyleMaskMiniaturizable); } bool NativeWindowMac::IsMinimizable() { return HasStyleMask(NSWindowStyleMaskMiniaturizable); } void NativeWindowMac::SetMaximizable(bool maximizable) { maximizable_ = maximizable; [[window_ standardWindowButton:NSWindowZoomButton] setEnabled:maximizable]; } bool NativeWindowMac::IsMaximizable() { return [[window_ standardWindowButton:NSWindowZoomButton] isEnabled]; } void NativeWindowMac::SetFullScreenable(bool fullscreenable) { SetCollectionBehavior(fullscreenable, NSWindowCollectionBehaviorFullScreenPrimary); // On EL Capitan this flag is required to hide fullscreen button. SetCollectionBehavior(!fullscreenable, NSWindowCollectionBehaviorFullScreenAuxiliary); } bool NativeWindowMac::IsFullScreenable() { NSUInteger collectionBehavior = [window_ collectionBehavior]; return collectionBehavior & NSWindowCollectionBehaviorFullScreenPrimary; } void NativeWindowMac::SetClosable(bool closable) { SetStyleMask(closable, NSWindowStyleMaskClosable); } bool NativeWindowMac::IsClosable() { return HasStyleMask(NSWindowStyleMaskClosable); } void NativeWindowMac::SetAlwaysOnTop(ui::ZOrderLevel z_order, const std::string& level_name, int relative_level) { if (z_order == ui::ZOrderLevel::kNormal) { SetWindowLevel(NSNormalWindowLevel); return; } int level = NSNormalWindowLevel; if (level_name == "floating") { level = NSFloatingWindowLevel; } else if (level_name == "torn-off-menu") { level = NSTornOffMenuWindowLevel; } else if (level_name == "modal-panel") { level = NSModalPanelWindowLevel; } else if (level_name == "main-menu") { level = NSMainMenuWindowLevel; } else if (level_name == "status") { level = NSStatusWindowLevel; } else if (level_name == "pop-up-menu") { level = NSPopUpMenuWindowLevel; } else if (level_name == "screen-saver") { level = NSScreenSaverWindowLevel; } SetWindowLevel(level + relative_level); } std::string NativeWindowMac::GetAlwaysOnTopLevel() { std::string level_name = "normal"; int level = [window_ level]; if (level == NSFloatingWindowLevel) { level_name = "floating"; } else if (level == NSTornOffMenuWindowLevel) { level_name = "torn-off-menu"; } else if (level == NSModalPanelWindowLevel) { level_name = "modal-panel"; } else if (level == NSMainMenuWindowLevel) { level_name = "main-menu"; } else if (level == NSStatusWindowLevel) { level_name = "status"; } else if (level == NSPopUpMenuWindowLevel) { level_name = "pop-up-menu"; } else if (level == NSScreenSaverWindowLevel) { level_name = "screen-saver"; } return level_name; } void NativeWindowMac::SetWindowLevel(int unbounded_level) { int level = std::min( std::max(unbounded_level, CGWindowLevelForKey(kCGMinimumWindowLevelKey)), CGWindowLevelForKey(kCGMaximumWindowLevelKey)); ui::ZOrderLevel z_order_level = level == NSNormalWindowLevel ? ui::ZOrderLevel::kNormal : ui::ZOrderLevel::kFloatingWindow; bool did_z_order_level_change = z_order_level != GetZOrderLevel(); was_maximizable_ = IsMaximizable(); // We need to explicitly keep the NativeWidget up to date, since it stores the // window level in a local variable, rather than reading it from the NSWindow. // Unfortunately, it results in a second setLevel call. It's not ideal, but we // don't expect this to cause any user-visible jank. widget()->SetZOrderLevel(z_order_level); [window_ setLevel:level]; // Set level will make the zoom button revert to default, probably // a bug of Cocoa or macOS. SetMaximizable(was_maximizable_); // This must be notified at the very end or IsAlwaysOnTop // will not yet have been updated to reflect the new status if (did_z_order_level_change) NativeWindow::NotifyWindowAlwaysOnTopChanged(); } ui::ZOrderLevel NativeWindowMac::GetZOrderLevel() { return widget()->GetZOrderLevel(); } void NativeWindowMac::Center() { [window_ center]; } void NativeWindowMac::Invalidate() { [[window_ contentView] setNeedsDisplay:YES]; } void NativeWindowMac::SetTitle(const std::string& title) { [window_ setTitle:base::SysUTF8ToNSString(title)]; if (buttons_proxy_) [buttons_proxy_ redraw]; } std::string NativeWindowMac::GetTitle() { return base::SysNSStringToUTF8([window_ title]); } void NativeWindowMac::FlashFrame(bool flash) { if (flash) { attention_request_id_ = [NSApp requestUserAttention:NSInformationalRequest]; } else { [NSApp cancelUserAttentionRequest:attention_request_id_]; attention_request_id_ = 0; } } void NativeWindowMac::SetSkipTaskbar(bool skip) {} bool NativeWindowMac::IsExcludedFromShownWindowsMenu() { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); return [window isExcludedFromWindowsMenu]; } void NativeWindowMac::SetExcludedFromShownWindowsMenu(bool excluded) { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); [window setExcludedFromWindowsMenu:excluded]; } void NativeWindowMac::OnDisplayMetricsChanged(const display::Display& display, uint32_t changed_metrics) { // We only want to force screen recalibration if we're in simpleFullscreen // mode. if (!is_simple_fullscreen_) return; content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&NativeWindow::UpdateFrame, GetWeakPtr())); } void NativeWindowMac::SetSimpleFullScreen(bool simple_fullscreen) { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); if (simple_fullscreen && !is_simple_fullscreen_) { is_simple_fullscreen_ = true; // Take note of the current window size and level if (IsNormal()) { UpdateWindowOriginalFrame(); original_level_ = [window_ level]; } simple_fullscreen_options_ = [NSApp currentSystemPresentationOptions]; simple_fullscreen_mask_ = [window styleMask]; // We can simulate the pre-Lion fullscreen by auto-hiding the dock and menu // bar NSApplicationPresentationOptions options = NSApplicationPresentationAutoHideDock | NSApplicationPresentationAutoHideMenuBar; [NSApp setPresentationOptions:options]; was_maximizable_ = IsMaximizable(); was_movable_ = IsMovable(); NSRect fullscreenFrame = [window.screen frame]; // If our app has dock hidden, set the window level higher so another app's // menu bar doesn't appear on top of our fullscreen app. if ([[NSRunningApplication currentApplication] activationPolicy] != NSApplicationActivationPolicyRegular) { window.level = NSPopUpMenuWindowLevel; } // Always hide the titlebar in simple fullscreen mode. // // Note that we must remove the NSWindowStyleMaskTitled style instead of // using the [window_ setTitleVisibility:], as the latter would leave the // window with rounded corners. SetStyleMask(false, NSWindowStyleMaskTitled); if (!window_button_visibility_.has_value()) { // Lets keep previous behaviour - hide window controls in titled // fullscreen mode when not specified otherwise. InternalSetWindowButtonVisibility(false); } [window setFrame:fullscreenFrame display:YES animate:YES]; // Fullscreen windows can't be resized, minimized, maximized, or moved SetMinimizable(false); SetResizable(false); SetMaximizable(false); SetMovable(false); } else if (!simple_fullscreen && is_simple_fullscreen_) { is_simple_fullscreen_ = false; [window setFrame:original_frame_ display:YES animate:YES]; window.level = original_level_; [NSApp setPresentationOptions:simple_fullscreen_options_]; // Restore original style mask ScopedDisableResize disable_resize; [window_ setStyleMask:simple_fullscreen_mask_]; // Restore window manipulation abilities SetMaximizable(was_maximizable_); SetMovable(was_movable_); // Restore default window controls visibility state. if (!window_button_visibility_.has_value()) { bool visibility; if (has_frame()) visibility = true; else visibility = title_bar_style_ != TitleBarStyle::kNormal; InternalSetWindowButtonVisibility(visibility); } if (buttons_proxy_) [buttons_proxy_ redraw]; } } bool NativeWindowMac::IsSimpleFullScreen() { return is_simple_fullscreen_; } void NativeWindowMac::SetKiosk(bool kiosk) { if (kiosk && !is_kiosk_) { kiosk_options_ = [NSApp currentSystemPresentationOptions]; NSApplicationPresentationOptions options = NSApplicationPresentationHideDock | NSApplicationPresentationHideMenuBar | NSApplicationPresentationDisableAppleMenu | NSApplicationPresentationDisableProcessSwitching | NSApplicationPresentationDisableForceQuit | NSApplicationPresentationDisableSessionTermination | NSApplicationPresentationDisableHideApplication; [NSApp setPresentationOptions:options]; is_kiosk_ = true; fullscreen_before_kiosk_ = IsFullscreen(); if (!fullscreen_before_kiosk_) SetFullScreen(true); } else if (!kiosk && is_kiosk_) { is_kiosk_ = false; if (!fullscreen_before_kiosk_) SetFullScreen(false); // Set presentation options *after* asynchronously exiting // fullscreen to ensure they take effect. [NSApp setPresentationOptions:kiosk_options_]; } } bool NativeWindowMac::IsKiosk() { return is_kiosk_; } void NativeWindowMac::SetBackgroundColor(SkColor color) { base::apple::ScopedCFTypeRef<CGColorRef> cgcolor( skia::CGColorCreateFromSkColor(color)); [[[window_ contentView] layer] setBackgroundColor:cgcolor]; } SkColor NativeWindowMac::GetBackgroundColor() { CGColorRef color = [[[window_ contentView] layer] backgroundColor]; if (!color) return SK_ColorTRANSPARENT; return skia::CGColorRefToSkColor(color); } void NativeWindowMac::SetHasShadow(bool has_shadow) { [window_ setHasShadow:has_shadow]; } bool NativeWindowMac::HasShadow() { return [window_ hasShadow]; } void NativeWindowMac::InvalidateShadow() { [window_ invalidateShadow]; } void NativeWindowMac::SetOpacity(const double opacity) { const double boundedOpacity = std::clamp(opacity, 0.0, 1.0); [window_ setAlphaValue:boundedOpacity]; } double NativeWindowMac::GetOpacity() { return [window_ alphaValue]; } void NativeWindowMac::SetRepresentedFilename(const std::string& filename) { [window_ setRepresentedFilename:base::SysUTF8ToNSString(filename)]; if (buttons_proxy_) [buttons_proxy_ redraw]; } std::string NativeWindowMac::GetRepresentedFilename() { return base::SysNSStringToUTF8([window_ representedFilename]); } void NativeWindowMac::SetDocumentEdited(bool edited) { [window_ setDocumentEdited:edited]; if (buttons_proxy_) [buttons_proxy_ redraw]; } bool NativeWindowMac::IsDocumentEdited() { return [window_ isDocumentEdited]; } bool NativeWindowMac::IsHiddenInMissionControl() { NSUInteger collectionBehavior = [window_ collectionBehavior]; return collectionBehavior & NSWindowCollectionBehaviorTransient; } void NativeWindowMac::SetHiddenInMissionControl(bool hidden) { SetCollectionBehavior(hidden, NSWindowCollectionBehaviorTransient); } void NativeWindowMac::SetIgnoreMouseEvents(bool ignore, bool forward) { [window_ setIgnoresMouseEvents:ignore]; if (!ignore) { SetForwardMouseMessages(NO); } else { SetForwardMouseMessages(forward); } } void NativeWindowMac::SetContentProtection(bool enable) { [window_ setSharingType:enable ? NSWindowSharingNone : NSWindowSharingReadOnly]; } void NativeWindowMac::SetFocusable(bool focusable) { // No known way to unfocus the window if it had the focus. Here we do not // want to call Focus(false) because it moves the window to the back, i.e. // at the bottom in term of z-order. [window_ setDisableKeyOrMainWindow:!focusable]; } bool NativeWindowMac::IsFocusable() { return ![window_ disableKeyOrMainWindow]; } void NativeWindowMac::AddBrowserView(NativeBrowserView* view) { [CATransaction begin]; [CATransaction setDisableActions:YES]; if (!view) { [CATransaction commit]; return; } add_browser_view(view); if (view->GetInspectableWebContentsView()) { auto* native_view = view->GetInspectableWebContentsView() ->GetNativeView() .GetNativeNSView(); [[window_ contentView] addSubview:native_view positioned:NSWindowAbove relativeTo:nil]; native_view.hidden = NO; } [CATransaction commit]; } void NativeWindowMac::RemoveBrowserView(NativeBrowserView* view) { [CATransaction begin]; [CATransaction setDisableActions:YES]; if (!view) { [CATransaction commit]; return; } if (view->GetInspectableWebContentsView()) [view->GetInspectableWebContentsView()->GetNativeView().GetNativeNSView() removeFromSuperview]; remove_browser_view(view); [CATransaction commit]; } void NativeWindowMac::SetTopBrowserView(NativeBrowserView* view) { [CATransaction begin]; [CATransaction setDisableActions:YES]; if (!view) { [CATransaction commit]; return; } remove_browser_view(view); add_browser_view(view); if (view->GetInspectableWebContentsView()) { auto* native_view = view->GetInspectableWebContentsView() ->GetNativeView() .GetNativeNSView(); [[window_ contentView] addSubview:native_view positioned:NSWindowAbove relativeTo:nil]; native_view.hidden = NO; } [CATransaction commit]; } void NativeWindowMac::SetParentWindow(NativeWindow* parent) { InternalSetParentWindow(parent, IsVisible()); } gfx::NativeView NativeWindowMac::GetNativeView() const { return [window_ contentView]; } gfx::NativeWindow NativeWindowMac::GetNativeWindow() const { return window_; } gfx::AcceleratedWidget NativeWindowMac::GetAcceleratedWidget() const { return [window_ windowNumber]; } content::DesktopMediaID NativeWindowMac::GetDesktopMediaID() const { auto desktop_media_id = content::DesktopMediaID( content::DesktopMediaID::TYPE_WINDOW, GetAcceleratedWidget()); // c.f. // https://source.chromium.org/chromium/chromium/src/+/main:chrome/browser/media/webrtc/native_desktop_media_list.cc;l=775-780;drc=79502ab47f61bff351426f57f576daef02b1a8dc // Refs https://github.com/electron/electron/pull/30507 // TODO(deepak1556): Match upstream for `kWindowCaptureMacV2` #if 0 if (remote_cocoa::ScopedCGWindowID::Get(desktop_media_id.id)) { desktop_media_id.window_id = desktop_media_id.id; } #endif return desktop_media_id; } NativeWindowHandle NativeWindowMac::GetNativeWindowHandle() const { return [window_ contentView]; } void NativeWindowMac::SetProgressBar(double progress, const NativeWindow::ProgressState state) { NSDockTile* dock_tile = [NSApp dockTile]; // Sometimes macOS would install a default contentView for dock, we must // verify whether NSProgressIndicator has been installed. bool first_time = !dock_tile.contentView || [[dock_tile.contentView subviews] count] == 0 || ![[[dock_tile.contentView subviews] lastObject] isKindOfClass:[NSProgressIndicator class]]; // For the first time API invoked, we need to create a ContentView in // DockTile. if (first_time) { NSImageView* image_view = [[NSImageView alloc] init]; [image_view setImage:[NSApp applicationIconImage]]; [dock_tile setContentView:image_view]; NSRect frame = NSMakeRect(0.0f, 0.0f, dock_tile.size.width, 15.0); NSProgressIndicator* progress_indicator = [[ElectronProgressBar alloc] initWithFrame:frame]; [progress_indicator setStyle:NSProgressIndicatorStyleBar]; [progress_indicator setIndeterminate:NO]; [progress_indicator setBezeled:YES]; [progress_indicator setMinValue:0]; [progress_indicator setMaxValue:1]; [progress_indicator setHidden:NO]; [dock_tile.contentView addSubview:progress_indicator]; } NSProgressIndicator* progress_indicator = static_cast<NSProgressIndicator*>( [[[dock_tile contentView] subviews] lastObject]); if (progress < 0) { [progress_indicator setHidden:YES]; } else if (progress > 1) { [progress_indicator setHidden:NO]; [progress_indicator setIndeterminate:YES]; [progress_indicator setDoubleValue:1]; } else { [progress_indicator setHidden:NO]; [progress_indicator setDoubleValue:progress]; } [dock_tile display]; } void NativeWindowMac::SetOverlayIcon(const gfx::Image& overlay, const std::string& description) {} void NativeWindowMac::SetVisibleOnAllWorkspaces(bool visible, bool visibleOnFullScreen, bool skipTransformProcessType) { // In order for NSWindows to be visible on fullscreen we need to invoke // app.dock.hide() since Apple changed the underlying functionality of // NSWindows starting with 10.14 to disallow NSWindows from floating on top of // fullscreen apps. if (!skipTransformProcessType) { if (visibleOnFullScreen) { Browser::Get()->DockHide(); } else { Browser::Get()->DockShow(JavascriptEnvironment::GetIsolate()); } } SetCollectionBehavior(visible, NSWindowCollectionBehaviorCanJoinAllSpaces); SetCollectionBehavior(visibleOnFullScreen, NSWindowCollectionBehaviorFullScreenAuxiliary); } bool NativeWindowMac::IsVisibleOnAllWorkspaces() { NSUInteger collectionBehavior = [window_ collectionBehavior]; return collectionBehavior & NSWindowCollectionBehaviorCanJoinAllSpaces; } void NativeWindowMac::SetAutoHideCursor(bool auto_hide) { [window_ setDisableAutoHideCursor:!auto_hide]; } void NativeWindowMac::UpdateVibrancyRadii(bool fullscreen) { NSVisualEffectView* vibrantView = [window_ vibrantView]; if (vibrantView != nil && !vibrancy_type_.empty()) { const bool no_rounded_corner = !HasStyleMask(NSWindowStyleMaskTitled); if (!has_frame() && !is_modal() && !no_rounded_corner) { CGFloat radius; if (fullscreen) { radius = 0.0f; } else if (@available(macOS 11.0, *)) { radius = 9.0f; } else { // Smaller corner radius on versions prior to Big Sur. radius = 5.0f; } CGFloat dimension = 2 * radius + 1; NSSize size = NSMakeSize(dimension, dimension); NSImage* maskImage = [NSImage imageWithSize:size flipped:NO drawingHandler:^BOOL(NSRect rect) { NSBezierPath* bezierPath = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [[NSColor blackColor] set]; [bezierPath fill]; return YES; }]; [maskImage setCapInsets:NSEdgeInsetsMake(radius, radius, radius, radius)]; [maskImage setResizingMode:NSImageResizingModeStretch]; [vibrantView setMaskImage:maskImage]; [window_ setCornerMask:maskImage]; } } } void NativeWindowMac::UpdateWindowOriginalFrame() { original_frame_ = [window_ frame]; } void NativeWindowMac::SetVibrancy(const std::string& type) { NSVisualEffectView* vibrantView = [window_ vibrantView]; if (type.empty()) { if (vibrantView == nil) return; [vibrantView removeFromSuperview]; [window_ setVibrantView:nil]; return; } NSVisualEffectMaterial vibrancyType{}; if (type == "titlebar") { vibrancyType = NSVisualEffectMaterialTitlebar; } else if (type == "selection") { vibrancyType = NSVisualEffectMaterialSelection; } else if (type == "menu") { vibrancyType = NSVisualEffectMaterialMenu; } else if (type == "popover") { vibrancyType = NSVisualEffectMaterialPopover; } else if (type == "sidebar") { vibrancyType = NSVisualEffectMaterialSidebar; } else if (type == "header") { vibrancyType = NSVisualEffectMaterialHeaderView; } else if (type == "sheet") { vibrancyType = NSVisualEffectMaterialSheet; } else if (type == "window") { vibrancyType = NSVisualEffectMaterialWindowBackground; } else if (type == "hud") { vibrancyType = NSVisualEffectMaterialHUDWindow; } else if (type == "fullscreen-ui") { vibrancyType = NSVisualEffectMaterialFullScreenUI; } else if (type == "tooltip") { vibrancyType = NSVisualEffectMaterialToolTip; } else if (type == "content") { vibrancyType = NSVisualEffectMaterialContentBackground; } else if (type == "under-window") { vibrancyType = NSVisualEffectMaterialUnderWindowBackground; } else if (type == "under-page") { vibrancyType = NSVisualEffectMaterialUnderPageBackground; } if (vibrancyType) { vibrancy_type_ = type; if (vibrantView == nil) { vibrantView = [[NSVisualEffectView alloc] initWithFrame:[[window_ contentView] bounds]]; [window_ setVibrantView:vibrantView]; [vibrantView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable]; [vibrantView setBlendingMode:NSVisualEffectBlendingModeBehindWindow]; if (visual_effect_state_ == VisualEffectState::kActive) { [vibrantView setState:NSVisualEffectStateActive]; } else if (visual_effect_state_ == VisualEffectState::kInactive) { [vibrantView setState:NSVisualEffectStateInactive]; } else { [vibrantView setState:NSVisualEffectStateFollowsWindowActiveState]; } [[window_ contentView] addSubview:vibrantView positioned:NSWindowBelow relativeTo:nil]; UpdateVibrancyRadii(IsFullscreen()); } [vibrantView setMaterial:vibrancyType]; } } void NativeWindowMac::SetWindowButtonVisibility(bool visible) { window_button_visibility_ = visible; if (buttons_proxy_) { if (visible) [buttons_proxy_ redraw]; [buttons_proxy_ setVisible:visible]; } if (title_bar_style_ != TitleBarStyle::kCustomButtonsOnHover) InternalSetWindowButtonVisibility(visible); NotifyLayoutWindowControlsOverlay(); } bool NativeWindowMac::GetWindowButtonVisibility() const { return ![window_ standardWindowButton:NSWindowZoomButton].hidden || ![window_ standardWindowButton:NSWindowMiniaturizeButton].hidden || ![window_ standardWindowButton:NSWindowCloseButton].hidden; } void NativeWindowMac::SetWindowButtonPosition( absl::optional<gfx::Point> position) { traffic_light_position_ = std::move(position); if (buttons_proxy_) { [buttons_proxy_ setMargin:traffic_light_position_]; NotifyLayoutWindowControlsOverlay(); } } absl::optional<gfx::Point> NativeWindowMac::GetWindowButtonPosition() const { return traffic_light_position_; } void NativeWindowMac::RedrawTrafficLights() { if (buttons_proxy_ && !IsFullscreen()) [buttons_proxy_ redraw]; } // In simpleFullScreen mode, update the frame for new bounds. void NativeWindowMac::UpdateFrame() { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); NSRect fullscreenFrame = [window.screen frame]; [window setFrame:fullscreenFrame display:YES animate:YES]; } void NativeWindowMac::SetTouchBar( std::vector<gin_helper::PersistentDictionary> items) { touch_bar_ = [[ElectronTouchBar alloc] initWithDelegate:window_delegate_ window:this settings:std::move(items)]; [window_ setTouchBar:nil]; } void NativeWindowMac::RefreshTouchBarItem(const std::string& item_id) { if (touch_bar_ && [window_ touchBar]) [touch_bar_ refreshTouchBarItem:[window_ touchBar] id:item_id]; } void NativeWindowMac::SetEscapeTouchBarItem( gin_helper::PersistentDictionary item) { if (touch_bar_ && [window_ touchBar]) [touch_bar_ setEscapeTouchBarItem:std::move(item) forTouchBar:[window_ touchBar]]; } void NativeWindowMac::SelectPreviousTab() { [window_ selectPreviousTab:nil]; } void NativeWindowMac::SelectNextTab() { [window_ selectNextTab:nil]; } void NativeWindowMac::ShowAllTabs() { [window_ toggleTabOverview:nil]; } void NativeWindowMac::MergeAllWindows() { [window_ mergeAllWindows:nil]; } void NativeWindowMac::MoveTabToNewWindow() { [window_ moveTabToNewWindow:nil]; } void NativeWindowMac::ToggleTabBar() { [window_ toggleTabBar:nil]; } bool NativeWindowMac::AddTabbedWindow(NativeWindow* window) { if (window_ == window->GetNativeWindow().GetNativeNSWindow()) { return false; } else { [window_ addTabbedWindow:window->GetNativeWindow().GetNativeNSWindow() ordered:NSWindowAbove]; } return true; } void NativeWindowMac::SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) { NativeWindow::SetAspectRatio(aspect_ratio, extra_size); // Reset the behaviour to default if aspect_ratio is set to 0 or less. if (aspect_ratio > 0.0) { NSSize aspect_ratio_size = NSMakeSize(aspect_ratio, 1.0); if (has_frame()) [window_ setContentAspectRatio:aspect_ratio_size]; else [window_ setAspectRatio:aspect_ratio_size]; } else { [window_ setResizeIncrements:NSMakeSize(1.0, 1.0)]; } } void NativeWindowMac::PreviewFile(const std::string& path, const std::string& display_name) { preview_item_ = [[ElectronPreviewItem alloc] initWithURL:[NSURL fileURLWithPath:base::SysUTF8ToNSString(path)] title:base::SysUTF8ToNSString(display_name)]; [[QLPreviewPanel sharedPreviewPanel] makeKeyAndOrderFront:nil]; } void NativeWindowMac::CloseFilePreview() { if ([QLPreviewPanel sharedPreviewPanelExists]) { [[QLPreviewPanel sharedPreviewPanel] close]; } } gfx::Rect NativeWindowMac::ContentBoundsToWindowBounds( const gfx::Rect& bounds) const { if (has_frame()) { gfx::Rect window_bounds( [window_ frameRectForContentRect:bounds.ToCGRect()]); int frame_height = window_bounds.height() - bounds.height(); window_bounds.set_y(window_bounds.y() - frame_height); return window_bounds; } else { return bounds; } } gfx::Rect NativeWindowMac::WindowBoundsToContentBounds( const gfx::Rect& bounds) const { if (has_frame()) { gfx::Rect content_bounds( [window_ contentRectForFrameRect:bounds.ToCGRect()]); int frame_height = bounds.height() - content_bounds.height(); content_bounds.set_y(content_bounds.y() + frame_height); return content_bounds; } else { return bounds; } } void NativeWindowMac::NotifyWindowEnterFullScreen() { NativeWindow::NotifyWindowEnterFullScreen(); // Restore the window title under fullscreen mode. if (buttons_proxy_) [window_ setTitleVisibility:NSWindowTitleVisible]; if (transparent() || !has_frame()) [window_ setTitlebarAppearsTransparent:NO]; } void NativeWindowMac::NotifyWindowLeaveFullScreen() { NativeWindow::NotifyWindowLeaveFullScreen(); // Restore window buttons. if (buttons_proxy_ && window_button_visibility_.value_or(true)) { [buttons_proxy_ redraw]; [buttons_proxy_ setVisible:YES]; } if (transparent() || !has_frame()) [window_ setTitlebarAppearsTransparent:YES]; } void NativeWindowMac::NotifyWindowWillEnterFullScreen() { UpdateVibrancyRadii(true); } void NativeWindowMac::NotifyWindowWillLeaveFullScreen() { if (buttons_proxy_) { // Hide window title when leaving fullscreen. [window_ setTitleVisibility:NSWindowTitleHidden]; // Hide the container otherwise traffic light buttons jump. [buttons_proxy_ setVisible:NO]; } UpdateVibrancyRadii(false); } void NativeWindowMac::SetActive(bool is_key) { is_active_ = is_key; } bool NativeWindowMac::IsActive() const { return is_active_; } void NativeWindowMac::Cleanup() { DCHECK(!IsClosed()); ui::NativeTheme::GetInstanceForNativeUi()->RemoveObserver(this); display::Screen::GetScreen()->RemoveObserver(this); } class NativeAppWindowFrameViewMac : public views::NativeFrameViewMac { public: NativeAppWindowFrameViewMac(views::Widget* frame, NativeWindowMac* window) : views::NativeFrameViewMac(frame), native_window_(window) {} NativeAppWindowFrameViewMac(const NativeAppWindowFrameViewMac&) = delete; NativeAppWindowFrameViewMac& operator=(const NativeAppWindowFrameViewMac&) = delete; ~NativeAppWindowFrameViewMac() override = default; // NonClientFrameView: int NonClientHitTest(const gfx::Point& point) override { if (!bounds().Contains(point)) return HTNOWHERE; if (GetWidget()->IsFullscreen()) return HTCLIENT; // Check for possible draggable region in the client area for the frameless // window. int contents_hit_test = native_window_->NonClientHitTest(point); if (contents_hit_test != HTNOWHERE) return contents_hit_test; return HTCLIENT; } private: // Weak. raw_ptr<NativeWindowMac> const native_window_; }; std::unique_ptr<views::NonClientFrameView> NativeWindowMac::CreateNonClientFrameView(views::Widget* widget) { return std::make_unique<NativeAppWindowFrameViewMac>(widget, this); } bool NativeWindowMac::HasStyleMask(NSUInteger flag) const { return [window_ styleMask] & flag; } void NativeWindowMac::SetStyleMask(bool on, NSUInteger flag) { // Changing the styleMask of a frameless windows causes it to change size so // we explicitly disable resizing while setting it. ScopedDisableResize disable_resize; if (on) [window_ setStyleMask:[window_ styleMask] | flag]; else [window_ setStyleMask:[window_ styleMask] & (~flag)]; // Change style mask will make the zoom button revert to default, probably // a bug of Cocoa or macOS. SetMaximizable(maximizable_); } void NativeWindowMac::SetCollectionBehavior(bool on, NSUInteger flag) { if (on) [window_ setCollectionBehavior:[window_ collectionBehavior] | flag]; else [window_ setCollectionBehavior:[window_ collectionBehavior] & (~flag)]; // Change collectionBehavior will make the zoom button revert to default, // probably a bug of Cocoa or macOS. SetMaximizable(maximizable_); } views::View* NativeWindowMac::GetContentsView() { return root_view_.get(); } bool NativeWindowMac::CanMaximize() const { return maximizable_; } void NativeWindowMac::OnNativeThemeUpdated(ui::NativeTheme* observed_theme) { content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&NativeWindow::RedrawTrafficLights, GetWeakPtr())); } void NativeWindowMac::AddContentViewLayers() { // Make sure the bottom corner is rounded for non-modal windows: // http://crbug.com/396264. if (!is_modal()) { // For normal window, we need to explicitly set layer for contentView to // make setBackgroundColor work correctly. // There is no need to do so for frameless window, and doing so would make // titleBarStyle stop working. if (has_frame()) { CALayer* background_layer = [[CALayer alloc] init]; [background_layer setAutoresizingMask:kCALayerWidthSizable | kCALayerHeightSizable]; [[window_ contentView] setLayer:background_layer]; } [[window_ contentView] setWantsLayer:YES]; } } void NativeWindowMac::InternalSetWindowButtonVisibility(bool visible) { [[window_ standardWindowButton:NSWindowCloseButton] setHidden:!visible]; [[window_ standardWindowButton:NSWindowMiniaturizeButton] setHidden:!visible]; [[window_ standardWindowButton:NSWindowZoomButton] setHidden:!visible]; } void NativeWindowMac::InternalSetParentWindow(NativeWindow* new_parent, bool attach) { if (is_modal()) return; // Do not remove/add if we are already properly attached. if (attach && new_parent && [window_ parentWindow] == new_parent->GetNativeWindow().GetNativeNSWindow()) return; // Remove current parent window. RemoveChildFromParentWindow(); // Set new parent window. if (new_parent) { new_parent->add_child_window(this); if (attach) new_parent->AttachChildren(); } NativeWindow::SetParentWindow(new_parent); } void NativeWindowMac::SetForwardMouseMessages(bool forward) { [window_ setAcceptsMouseMovedEvents:forward]; } gfx::Rect NativeWindowMac::GetWindowControlsOverlayRect() { if (titlebar_overlay_ && buttons_proxy_ && window_button_visibility_.value_or(true)) { NSRect buttons = [buttons_proxy_ getButtonsContainerBounds]; gfx::Rect overlay; overlay.set_width(GetContentSize().width() - NSWidth(buttons)); if ([buttons_proxy_ useCustomHeight]) { overlay.set_height(titlebar_overlay_height()); } else { overlay.set_height(NSHeight(buttons)); } if (!base::i18n::IsRTL()) overlay.set_x(NSMaxX(buttons)); return overlay; } return gfx::Rect(); } // static NativeWindow* NativeWindow::Create(const gin_helper::Dictionary& options, NativeWindow* parent) { return new NativeWindowMac(options, parent); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
35,403
[Bug]: macOS - Using frame, roundedCorners, and fullscreen settings together automatically causes a 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 20.0.3 ### What operating system are you using? macOS ### Operating System Version Catalina (confirmed on Big Sur too) ### What arch are you using? x64 ### Last Known Working Electron version Not working in version 17-21 ### Expected Behavior Code such as the following should not crash Electron: ``` win = new BrowserWindow({ title: "Media Window", frame: false, // These 3 options can't be roundedCorners: false, // used concurrently on macOS fullscreen: true // without causing a crash }); ``` ### Actual Behavior The following code crashes Electron on macOS: ``` win = new BrowserWindow({ title: "Media Window", frame: false, // These 3 options can't be roundedCorners: false, // used concurrently on macOS fullscreen: true // without causing a crash }); ``` Any of the following 3 variants does **not** cause the crash: ``` win = new BrowserWindow({ title: "Media Window", // frame: false, roundedCorners: false, fullscreen: true }); ``` ``` win = new BrowserWindow({ title: "Media Window", frame: false, // roundedCorners: false, fullscreen: true }); ``` ``` win = new BrowserWindow({ title: "Media Window", frame: false, roundedCorners: false, // fullscreen: true }); ``` ### Testcase Gist URL https://gist.github.com/sircharlo/c78e81a20c3eb4167037197b3803d76e ### Additional Information Error looks like this: Electron[785:12045] *** Assertion failure in -[ElectronNSWindow titlebarAccessoryViewControllers], /AppleInternal/BuildRoot/Library/Caches/com.apple.xbs/Sources/AppKit/AppKit-1894.60.100/AppKit.subproj/NSWindow.m:3337
https://github.com/electron/electron/issues/35403
https://github.com/electron/electron/pull/39747
2324c4d8fd6f7b2cd336d4e93591464544e12953
ab185c058f894ddc556f67b2853de4adad2bb10c
2022-08-22T15:16:24Z
c++
2023-09-11T07:38:10Z
shell/browser/ui/cocoa/electron_ns_window.h
// Copyright (c) 2018 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_COCOA_ELECTRON_NS_WINDOW_H_ #define ELECTRON_SHELL_BROWSER_UI_COCOA_ELECTRON_NS_WINDOW_H_ #include "base/memory/raw_ptr.h" #include "components/remote_cocoa/app_shim/native_widget_mac_nswindow.h" #include "shell/browser/ui/cocoa/event_dispatching_window.h" #include "ui/views/widget/native_widget_mac.h" namespace electron { class NativeWindowMac; // Prevents window from resizing during the scope. class ScopedDisableResize { public: ScopedDisableResize() { disable_resize_++; } ~ScopedDisableResize() { disable_resize_--; } // True if there are 1+ nested ScopedDisableResize objects in the scope static bool IsResizeDisabled() { return disable_resize_ > 0; } private: static int disable_resize_; }; } // namespace electron @interface ElectronNSWindow : NativeWidgetMacNSWindow { @private raw_ptr<electron::NativeWindowMac> shell_; } @property BOOL acceptsFirstMouse; @property BOOL enableLargerThanScreen; @property BOOL disableAutoHideCursor; @property BOOL disableKeyOrMainWindow; @property(nonatomic, retain) NSVisualEffectView* vibrantView; @property(nonatomic, retain) NSImage* cornerMask; - (id)initWithShell:(electron::NativeWindowMac*)shell styleMask:(NSUInteger)styleMask; - (electron::NativeWindowMac*)shell; - (id)accessibilityFocusedUIElement; - (NSRect)originalContentRectForFrameRect:(NSRect)frameRect; - (void)toggleFullScreenMode:(id)sender; - (NSImage*)_cornerMask; @end #endif // ELECTRON_SHELL_BROWSER_UI_COCOA_ELECTRON_NS_WINDOW_H_
closed
electron/electron
https://github.com/electron/electron
35,403
[Bug]: macOS - Using frame, roundedCorners, and fullscreen settings together automatically causes a 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 20.0.3 ### What operating system are you using? macOS ### Operating System Version Catalina (confirmed on Big Sur too) ### What arch are you using? x64 ### Last Known Working Electron version Not working in version 17-21 ### Expected Behavior Code such as the following should not crash Electron: ``` win = new BrowserWindow({ title: "Media Window", frame: false, // These 3 options can't be roundedCorners: false, // used concurrently on macOS fullscreen: true // without causing a crash }); ``` ### Actual Behavior The following code crashes Electron on macOS: ``` win = new BrowserWindow({ title: "Media Window", frame: false, // These 3 options can't be roundedCorners: false, // used concurrently on macOS fullscreen: true // without causing a crash }); ``` Any of the following 3 variants does **not** cause the crash: ``` win = new BrowserWindow({ title: "Media Window", // frame: false, roundedCorners: false, fullscreen: true }); ``` ``` win = new BrowserWindow({ title: "Media Window", frame: false, // roundedCorners: false, fullscreen: true }); ``` ``` win = new BrowserWindow({ title: "Media Window", frame: false, roundedCorners: false, // fullscreen: true }); ``` ### Testcase Gist URL https://gist.github.com/sircharlo/c78e81a20c3eb4167037197b3803d76e ### Additional Information Error looks like this: Electron[785:12045] *** Assertion failure in -[ElectronNSWindow titlebarAccessoryViewControllers], /AppleInternal/BuildRoot/Library/Caches/com.apple.xbs/Sources/AppKit/AppKit-1894.60.100/AppKit.subproj/NSWindow.m:3337
https://github.com/electron/electron/issues/35403
https://github.com/electron/electron/pull/39747
2324c4d8fd6f7b2cd336d4e93591464544e12953
ab185c058f894ddc556f67b2853de4adad2bb10c
2022-08-22T15:16:24Z
c++
2023-09-11T07:38:10Z
shell/browser/ui/cocoa/electron_ns_window.mm
// Copyright (c) 2018 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/cocoa/electron_ns_window.h" #include "base/strings/sys_string_conversions.h" #include "shell/browser/native_window_mac.h" #include "shell/browser/ui/cocoa/electron_preview_item.h" #include "shell/browser/ui/cocoa/electron_touch_bar.h" #include "shell/browser/ui/cocoa/root_view_mac.h" #include "ui/base/cocoa/window_size_constants.h" #import <objc/message.h> #import <objc/runtime.h> namespace electron { int ScopedDisableResize::disable_resize_ = 0; } // namespace electron @interface NSWindow (PrivateAPI) - (NSImage*)_cornerMask; - (int64_t)_resizeDirectionForMouseLocation:(CGPoint)location; @end // See components/remote_cocoa/app_shim/native_widget_mac_nswindow.mm @interface NSView (CRFrameViewAdditions) - (void)cr_mouseDownOnFrameView:(NSEvent*)event; @end typedef void (*MouseDownImpl)(id, SEL, NSEvent*); namespace { MouseDownImpl g_nsthemeframe_mousedown; MouseDownImpl g_nsnextstepframe_mousedown; } // namespace // This class is never instantiated, it's just a container for our swizzled // mouseDown method. @interface SwizzledMethodsClass : NSView @end @implementation SwizzledMethodsClass - (void)swiz_nsthemeframe_mouseDown:(NSEvent*)event { if ([self.window respondsToSelector:@selector(shell)]) { electron::NativeWindowMac* shell = (electron::NativeWindowMac*)[(id)self.window shell]; if (shell && !shell->has_frame()) [self cr_mouseDownOnFrameView:event]; g_nsthemeframe_mousedown(self, @selector(mouseDown:), event); } } - (void)swiz_nsnextstepframe_mouseDown:(NSEvent*)event { if ([self.window respondsToSelector:@selector(shell)]) { electron::NativeWindowMac* shell = (electron::NativeWindowMac*)[(id)self.window shell]; if (shell && !shell->has_frame()) { [self cr_mouseDownOnFrameView:event]; } g_nsnextstepframe_mousedown(self, @selector(mouseDown:), event); } } - (void)swiz_nsview_swipeWithEvent:(NSEvent*)event { if ([self.window respondsToSelector:@selector(shell)]) { electron::NativeWindowMac* shell = (electron::NativeWindowMac*)[(id)self.window shell]; if (shell) { if (event.deltaY == 1.0) { shell->NotifyWindowSwipe("up"); } else if (event.deltaX == -1.0) { shell->NotifyWindowSwipe("right"); } else if (event.deltaY == -1.0) { shell->NotifyWindowSwipe("down"); } else if (event.deltaX == 1.0) { shell->NotifyWindowSwipe("left"); } } } } @end namespace { #if IS_MAS_BUILD() void SwizzleMouseDown(NSView* frame_view, SEL swiz_selector, MouseDownImpl* orig_impl) { Method original_mousedown = class_getInstanceMethod([frame_view class], @selector(mouseDown:)); *orig_impl = (MouseDownImpl)method_getImplementation(original_mousedown); Method new_mousedown = class_getInstanceMethod([SwizzledMethodsClass class], swiz_selector); method_setImplementation(original_mousedown, method_getImplementation(new_mousedown)); } #else // components/remote_cocoa/app_shim/bridged_content_view.h overrides // swipeWithEvent, so we can't just override the implementation // in ElectronNSWindow like we do with for ex. rotateWithEvent. void SwizzleSwipeWithEvent(NSView* view, SEL swiz_selector) { Method original_swipe_with_event = class_getInstanceMethod([view class], @selector(swipeWithEvent:)); Method new_swipe_with_event = class_getInstanceMethod([SwizzledMethodsClass class], swiz_selector); method_setImplementation(original_swipe_with_event, method_getImplementation(new_swipe_with_event)); } #endif } // namespace @implementation ElectronNSWindow @synthesize acceptsFirstMouse; @synthesize enableLargerThanScreen; @synthesize disableAutoHideCursor; @synthesize disableKeyOrMainWindow; @synthesize vibrantView; @synthesize cornerMask; - (id)initWithShell:(electron::NativeWindowMac*)shell styleMask:(NSUInteger)styleMask { if ((self = [super initWithContentRect:ui::kWindowSizeDeterminedLater styleMask:styleMask backing:NSBackingStoreBuffered defer:NO])) { #if IS_MAS_BUILD() // The first time we create a frameless window, we swizzle the // implementation of -[NSNextStepFrame mouseDown:], replacing it with our // own. // This is only necessary on MAS where we can't directly refer to // NSNextStepFrame or NSThemeFrame, as they are private APIs. // See components/remote_cocoa/app_shim/native_widget_mac_nswindow.mm for // the non-MAS-compatible way of doing this. if (styleMask & NSWindowStyleMaskTitled) { if (!g_nsthemeframe_mousedown) { NSView* theme_frame = [[self contentView] superview]; DCHECK(strcmp(class_getName([theme_frame class]), "NSThemeFrame") == 0) << "Expected NSThemeFrame but was " << class_getName([theme_frame class]); SwizzleMouseDown(theme_frame, @selector(swiz_nsthemeframe_mouseDown:), &g_nsthemeframe_mousedown); } } else { if (!g_nsnextstepframe_mousedown) { NSView* nextstep_frame = [[self contentView] superview]; DCHECK(strcmp(class_getName([nextstep_frame class]), "NSNextStepFrame") == 0) << "Expected NSNextStepFrame but was " << class_getName([nextstep_frame class]); SwizzleMouseDown(nextstep_frame, @selector(swiz_nsnextstepframe_mouseDown:), &g_nsnextstepframe_mousedown); } } #else NSView* view = [[self contentView] superview]; SwizzleSwipeWithEvent(view, @selector(swiz_nsview_swipeWithEvent:)); #endif // IS_MAS_BUILD shell_ = shell; } return self; } - (electron::NativeWindowMac*)shell { return shell_; } - (id)accessibilityFocusedUIElement { views::Widget* widget = shell_->widget(); id superFocus = [super accessibilityFocusedUIElement]; if (!widget || shell_->IsFocused()) return superFocus; return nil; } - (NSRect)originalContentRectForFrameRect:(NSRect)frameRect { return [super contentRectForFrameRect:frameRect]; } - (NSTouchBar*)makeTouchBar { if (shell_->touch_bar()) return [shell_->touch_bar() makeTouchBar]; else return nil; } // NSWindow overrides. - (void)rotateWithEvent:(NSEvent*)event { shell_->NotifyWindowRotateGesture(event.rotation); } - (NSRect)contentRectForFrameRect:(NSRect)frameRect { if (shell_->has_frame()) return [super contentRectForFrameRect:frameRect]; else return frameRect; } - (NSRect)constrainFrameRect:(NSRect)frameRect toScreen:(NSScreen*)screen { // Resizing is disabled. if (electron::ScopedDisableResize::IsResizeDisabled()) return [self frame]; NSRect result = [super constrainFrameRect:frameRect toScreen:screen]; // Enable the window to be larger than screen. if ([self enableLargerThanScreen]) { // If we have a frame, ensure that we only position the window // somewhere where the user can move or resize it (and not // behind the menu bar, for instance) // // If there's no frame, put the window wherever the developer // wanted it to go if (shell_->has_frame()) { result.size = frameRect.size; } else { result = frameRect; } } return result; } - (void)setFrame:(NSRect)windowFrame display:(BOOL)displayViews { // constrainFrameRect is not called on hidden windows so disable adjusting // the frame directly when resize is disabled if (!electron::ScopedDisableResize::IsResizeDisabled()) [super setFrame:windowFrame display:displayViews]; } - (id)accessibilityAttributeValue:(NSString*)attribute { if ([attribute isEqual:NSAccessibilityEnabledAttribute]) return [NSNumber numberWithBool:YES]; if (![attribute isEqualToString:@"AXChildren"]) return [super accessibilityAttributeValue:attribute]; // We want to remove the window title (also known as // NSAccessibilityReparentingCellProxy), which VoiceOver already sees. // * when VoiceOver is disabled, this causes Cmd+C to be used for TTS but // still leaves the buttons available in the accessibility tree. // * when VoiceOver is enabled, the full accessibility tree is used. // Without removing the title and with VO disabled, the TTS would always read // the window title instead of using Cmd+C to get the selected text. NSPredicate* predicate = [NSPredicate predicateWithFormat:@"(self.className != %@)", @"NSAccessibilityReparentingCellProxy"]; NSArray* children = [super accessibilityAttributeValue:attribute]; NSMutableArray* mutableChildren = [children mutableCopy]; [mutableChildren filterUsingPredicate:predicate]; return mutableChildren; } - (NSString*)accessibilityTitle { return base::SysUTF8ToNSString(shell_->GetTitle()); } - (BOOL)canBecomeMainWindow { return !self.disableKeyOrMainWindow; } - (BOOL)canBecomeKeyWindow { return !self.disableKeyOrMainWindow; } - (NSView*)frameView { return [[self contentView] superview]; } - (BOOL)validateUserInterfaceItem:(id<NSValidatedUserInterfaceItem>)item { // By default "Close Window" is always disabled when window has no title, to // support closing a window without title we need to manually do menu item // validation. This code path is used by the "roundedCorners" option. if ([item action] == @selector(performClose:)) return shell_->IsClosable(); return [super validateUserInterfaceItem:item]; } // By overriding this built-in method the corners of the vibrant view (if set) // will be smooth. - (NSImage*)_cornerMask { if (self.vibrantView != nil) { return [self cornerMask]; } else { return [super _cornerMask]; } } // Quicklook methods - (BOOL)acceptsPreviewPanelControl:(QLPreviewPanel*)panel { return YES; } - (void)beginPreviewPanelControl:(QLPreviewPanel*)panel { panel.dataSource = static_cast<id<QLPreviewPanelDataSource>>([self delegate]); } - (void)endPreviewPanelControl:(QLPreviewPanel*)panel { panel.dataSource = nil; } // Custom window button methods - (BOOL)windowShouldClose:(id)sender { return YES; } - (void)performClose:(id)sender { if (shell_->title_bar_style() == electron::NativeWindowMac::TitleBarStyle::kCustomButtonsOnHover) { [[self delegate] windowShouldClose:self]; } else if (!([self styleMask] & NSWindowStyleMaskTitled)) { // performClose does not work for windows without title, so we have to // emulate its behavior. This code path is used by "simpleFullscreen" and // "roundedCorners" options. if ([[self delegate] respondsToSelector:@selector(windowShouldClose:)]) { if (![[self delegate] windowShouldClose:self]) return; } else if ([self respondsToSelector:@selector(windowShouldClose:)]) { if (![self windowShouldClose:self]) return; } [self close]; } else if (shell_->is_modal() && shell_->parent() && shell_->IsVisible()) { // We don't want to actually call [window close] here since // we've already called endSheet on the modal sheet. return; } else { [super performClose:sender]; } } - (void)toggleFullScreenMode:(id)sender { bool is_simple_fs = shell_->IsSimpleFullScreen(); bool always_simple_fs = shell_->always_simple_fullscreen(); // If we're in simple fullscreen mode and trying to exit it // we need to ensure we exit it properly to prevent a crash // with NSWindowStyleMaskTitled mode. if (is_simple_fs || always_simple_fs) { shell_->SetSimpleFullScreen(!is_simple_fs); } else { if (shell_->IsVisible()) { // Until 10.13, AppKit would obey a call to -toggleFullScreen: made inside // windowDidEnterFullScreen & windowDidExitFullScreen. Starting in 10.13, // it behaves as though the transition is still in progress and just emits // "not in a fullscreen state" when trying to exit fullscreen in the same // runloop that entered it. To handle this, invoke -toggleFullScreen: // asynchronously. [super performSelector:@selector(toggleFullScreen:) withObject:nil afterDelay:0]; } else { [super toggleFullScreen:sender]; } // Exiting fullscreen causes Cocoa to redraw the NSWindow, which resets // the enabled state for NSWindowZoomButton. We need to persist it. bool maximizable = shell_->IsMaximizable(); shell_->SetMaximizable(maximizable); } } - (void)performMiniaturize:(id)sender { if (shell_->title_bar_style() == electron::NativeWindowMac::TitleBarStyle::kCustomButtonsOnHover) [self miniaturize:self]; else [super performMiniaturize:sender]; } @end
closed
electron/electron
https://github.com/electron/electron
38,532
[Feature Request]: Support full frame transparency with Mica background material
### 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. ### Problem Description The [Mica `backgroundMaterial`](https://github.com/electron/electron/pull/38163) effect does not appear below the WebContents. ### Proposed Solution The `backgroundMaterial` option should behave the same as when setting the `vibrancy` option. | macOS: `vibrancy: 'medium-light'` | Windows: `backgroundMaterial: 'acrylic'` | Windows: `backgroundMaterial: 'acrylic'` + `transparent: true` | | --- | --- | --- | | ![Screenshot 2023-05-31 at 4 30 04 PM](https://github.com/electron/electron/assets/1656324/3f2a47e7-ed33-4f88-ae0d-2f67b1cb9b1d) | ![image (5)](https://github.com/electron/electron/assets/1656324/cb4c3a2e-284f-4a54-a968-7870af8be549) | ![image (6)](https://github.com/electron/electron/assets/1656324/318797e0-63ea-49d6-9feb-50cd66db0664) | When `vibrancy` is set, the WebContents is transparent by default. The same should apply to `backgroundMaterial`. Setting `transparent: true` doesn't seem to be a valid workaround, but ideally should still work. The code below needs to be updated: https://github.com/electron/electron/blob/9ffffdb6ef202bd93be496b53fdd4156dd3504ce/shell/browser/api/electron_api_browser_window.cc#L58-L64 ### Alternatives Considered None. ### Additional Information Tested on: ``` Edition Windows 11 Pro Version 22H2 OS build 22621.1778 ``` Fiddle gist: https://gist.github.com/34cf667b21a5075d1f6fbe093d7ad7f9
https://github.com/electron/electron/issues/38532
https://github.com/electron/electron/pull/39708
ab185c058f894ddc556f67b2853de4adad2bb10c
d1827941790f23b241ef3f234a9782750ac97e8d
2023-05-31T20:43:55Z
c++
2023-09-11T12:51:54Z
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 enable_reset_aspect_ratio.patch boringssl_build_gn.patch pepper_plugin_support.patch gtk_visibility.patch resource_file_conflict.patch scroll_bounce_flag.patch mas_blink_no_private_api.patch mas_no_private_api.patch mas-cgdisplayusesforcetogray.patch mas_disable_remote_layer.patch mas_disable_remote_accessibility.patch mas_disable_custom_window_frame.patch mas_avoid_usage_of_private_macos_apis.patch mas_use_public_apis_to_determine_if_a_font_is_a_system_font.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 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 allow_in-process_windows_to_have_different_web_prefs.patch refactor_expose_cursor_changes_to_the_webcontentsobserver.patch crash_allow_setting_more_options.patch upload_list_add_loadsync_method.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 export_gin_v8platform_pageallocator_for_usage_outside_of_the_gin.patch fix_export_zlib_symbols.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 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 process_singleton.patch add_ui_scopedcliboardwriter_writeunsaferawdata.patch feat_add_data_parameter_to_processsingleton.patch load_v8_snapshot_in_browser_process.patch fix_adapt_exclusive_access_for_electron_needs.patch fix_aspect_ratio_with_max_size.patch fix_crash_when_saving_edited_pdf_files.patch port_autofill_colors_to_the_color_pipeline.patch build_disable_partition_alloc_on_mac.patch fix_non-client_mouse_tracking_and_message_bubbling_on_windows.patch build_make_libcxx_abi_unstable_false_for_electron.patch introduce_ozoneplatform_electron_can_call_x11_property.patch make_gtk_getlibgtk_public.patch build_disable_print_content_analysis.patch custom_protocols_plzserviceworker.patch feat_filter_out_non-shareable_windows_in_the_current_application_in.patch disable_freezing_flags_after_init_in_node.patch short-circuit_permissions_checks_in_mediastreamdevicescontroller.patch chore_add_electron_deps_to_gitignores.patch chore_allow_chromium_to_handle_synthetic_mouse_events_for_touch.patch add_maximized_parameter_to_linuxui_getwindowframeprovider.patch add_electron_deps_to_license_credits_file.patch fix_crash_loading_non-standard_schemes_in_iframes.patch create_browser_v8_snapshot_file_name_fuse.patch feat_configure_launch_options_for_service_process.patch feat_ensure_mas_builds_of_the_same_application_can_use_safestorage.patch fix_on-screen-keyboard_hides_on_input_blur_in_webview.patch preconnect_manager.patch fix_remove_caption-removing_style_call.patch build_allow_electron_to_use_exec_script.patch build_only_use_the_mas_build_config_in_the_required_components.patch chore_introduce_blocking_api_for_electron.patch chore_patch_out_partition_attribute_dcheck_for_webviews.patch expose_v8initializer_codegenerationcheckcallbackinmainthread.patch chore_patch_out_profile_methods_in_profile_selections_cc.patch add_gin_converter_support_for_arraybufferview.patch chore_defer_usb_service_getdevices_request_until_usb_service_is.patch refactor_expose_hostimportmoduledynamically_and.patch feat_expose_documentloader_setdefersloading_on_webdocumentloader.patch fix_remove_profiles_from_spellcheck_service.patch chore_patch_out_profile_methods_in_chrome_browser_pdf.patch chore_patch_out_profile_methods_in_titlebar_config.patch fix_select_the_first_menu_item_when_opened_via_keyboard.patch fix_return_v8_value_from_localframe_requestexecutescript.patch fix_harden_blink_scriptstate_maybefrom.patch chore_add_buildflag_guard_around_new_include.patch fix_use_delegated_generic_capturer_when_available.patch build_remove_ent_content_analysis_assert.patch fix_move_autopipsettingshelper_behind_branding_buildflag.patch revert_remove_the_allowaggressivethrottlingwithwebsocket_feature.patch
closed
electron/electron
https://github.com/electron/electron
38,532
[Feature Request]: Support full frame transparency with Mica background material
### 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. ### Problem Description The [Mica `backgroundMaterial`](https://github.com/electron/electron/pull/38163) effect does not appear below the WebContents. ### Proposed Solution The `backgroundMaterial` option should behave the same as when setting the `vibrancy` option. | macOS: `vibrancy: 'medium-light'` | Windows: `backgroundMaterial: 'acrylic'` | Windows: `backgroundMaterial: 'acrylic'` + `transparent: true` | | --- | --- | --- | | ![Screenshot 2023-05-31 at 4 30 04 PM](https://github.com/electron/electron/assets/1656324/3f2a47e7-ed33-4f88-ae0d-2f67b1cb9b1d) | ![image (5)](https://github.com/electron/electron/assets/1656324/cb4c3a2e-284f-4a54-a968-7870af8be549) | ![image (6)](https://github.com/electron/electron/assets/1656324/318797e0-63ea-49d6-9feb-50cd66db0664) | When `vibrancy` is set, the WebContents is transparent by default. The same should apply to `backgroundMaterial`. Setting `transparent: true` doesn't seem to be a valid workaround, but ideally should still work. The code below needs to be updated: https://github.com/electron/electron/blob/9ffffdb6ef202bd93be496b53fdd4156dd3504ce/shell/browser/api/electron_api_browser_window.cc#L58-L64 ### Alternatives Considered None. ### Additional Information Tested on: ``` Edition Windows 11 Pro Version 22H2 OS build 22621.1778 ``` Fiddle gist: https://gist.github.com/34cf667b21a5075d1f6fbe093d7ad7f9
https://github.com/electron/electron/issues/38532
https://github.com/electron/electron/pull/39708
ab185c058f894ddc556f67b2853de4adad2bb10c
d1827941790f23b241ef3f234a9782750ac97e8d
2023-05-31T20:43:55Z
c++
2023-09-11T12:51:54Z
patches/chromium/fix_activate_background_material_on_windows.patch
closed
electron/electron
https://github.com/electron/electron
38,532
[Feature Request]: Support full frame transparency with Mica background material
### 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. ### Problem Description The [Mica `backgroundMaterial`](https://github.com/electron/electron/pull/38163) effect does not appear below the WebContents. ### Proposed Solution The `backgroundMaterial` option should behave the same as when setting the `vibrancy` option. | macOS: `vibrancy: 'medium-light'` | Windows: `backgroundMaterial: 'acrylic'` | Windows: `backgroundMaterial: 'acrylic'` + `transparent: true` | | --- | --- | --- | | ![Screenshot 2023-05-31 at 4 30 04 PM](https://github.com/electron/electron/assets/1656324/3f2a47e7-ed33-4f88-ae0d-2f67b1cb9b1d) | ![image (5)](https://github.com/electron/electron/assets/1656324/cb4c3a2e-284f-4a54-a968-7870af8be549) | ![image (6)](https://github.com/electron/electron/assets/1656324/318797e0-63ea-49d6-9feb-50cd66db0664) | When `vibrancy` is set, the WebContents is transparent by default. The same should apply to `backgroundMaterial`. Setting `transparent: true` doesn't seem to be a valid workaround, but ideally should still work. The code below needs to be updated: https://github.com/electron/electron/blob/9ffffdb6ef202bd93be496b53fdd4156dd3504ce/shell/browser/api/electron_api_browser_window.cc#L58-L64 ### Alternatives Considered None. ### Additional Information Tested on: ``` Edition Windows 11 Pro Version 22H2 OS build 22621.1778 ``` Fiddle gist: https://gist.github.com/34cf667b21a5075d1f6fbe093d7ad7f9
https://github.com/electron/electron/issues/38532
https://github.com/electron/electron/pull/39708
ab185c058f894ddc556f67b2853de4adad2bb10c
d1827941790f23b241ef3f234a9782750ac97e8d
2023-05-31T20:43:55Z
c++
2023-09-11T12:51:54Z
shell/browser/api/electron_api_browser_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/api/electron_api_browser_window.h" #include "base/task/single_thread_task_runner.h" #include "content/browser/renderer_host/render_widget_host_impl.h" // nogncheck #include "content/browser/renderer_host/render_widget_host_owner_delegate.h" // nogncheck #include "content/browser/web_contents/web_contents_impl.h" // nogncheck #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/common/color_parser.h" #include "shell/browser/api/electron_api_web_contents_view.h" #include "shell/browser/browser.h" #include "shell/browser/native_browser_view.h" #include "shell/browser/web_contents_preferences.h" #include "shell/browser/window_list.h" #include "shell/common/color_util.h" #include "shell/common/gin_helper/constructor.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/gin_helper/object_template_builder.h" #include "shell/common/node_includes.h" #include "shell/common/options_switches.h" #include "ui/gl/gpu_switching_manager.h" #if defined(TOOLKIT_VIEWS) #include "shell/browser/native_window_views.h" #endif #if BUILDFLAG(IS_WIN) #include "shell/browser/ui/views/win_frame_view.h" #endif namespace electron::api { BrowserWindow::BrowserWindow(gin::Arguments* args, const gin_helper::Dictionary& options) : BaseWindow(args->isolate(), options) { // Use options.webPreferences in WebContents. v8::Isolate* isolate = args->isolate(); auto web_preferences = gin_helper::Dictionary::CreateEmpty(isolate); options.Get(options::kWebPreferences, &web_preferences); bool transparent = false; options.Get(options::kTransparent, &transparent); std::string vibrancy_type; #if BUILDFLAG(IS_MAC) options.Get(options::kVibrancyType, &vibrancy_type); #endif // Copy the backgroundColor to webContents. std::string color; if (options.Get(options::kBackgroundColor, &color)) { web_preferences.SetHidden(options::kBackgroundColor, color); } else if (!vibrancy_type.empty() || transparent) { // If the BrowserWindow is transparent or a vibrancy type has been set, // also propagate transparency to the WebContents unless a separate // backgroundColor has been set. web_preferences.SetHidden(options::kBackgroundColor, ToRGBAHex(SK_ColorTRANSPARENT)); } // Copy the show setting to webContents, but only if we don't want to paint // when initially hidden bool paint_when_initially_hidden = true; options.Get("paintWhenInitiallyHidden", &paint_when_initially_hidden); if (!paint_when_initially_hidden) { bool show = true; options.Get(options::kShow, &show); web_preferences.Set(options::kShow, show); } // Copy the webContents option to webPreferences. v8::Local<v8::Value> value; if (options.Get("webContents", &value)) { web_preferences.SetHidden("webContents", value); } // Creates the WebContentsView. gin::Handle<WebContentsView> web_contents_view = WebContentsView::Create(isolate, web_preferences); DCHECK(web_contents_view.get()); window_->AddDraggableRegionProvider(web_contents_view.get()); // Save a reference of the WebContents. gin::Handle<WebContents> web_contents = web_contents_view->GetWebContents(isolate); web_contents_.Reset(isolate, web_contents.ToV8()); api_web_contents_ = web_contents->GetWeakPtr(); api_web_contents_->AddObserver(this); Observe(api_web_contents_->web_contents()); // Associate with BrowserWindow. web_contents->SetOwnerWindow(window()); InitWithArgs(args); // Install the content view after BaseWindow's JS code is initialized. SetContentView(gin::CreateHandle<View>(isolate, web_contents_view.get())); // Init window after everything has been setup. window()->InitFromOptions(options); } BrowserWindow::~BrowserWindow() { if (api_web_contents_) { // Cleanup the observers if user destroyed this instance directly instead of // gracefully closing content::WebContents. api_web_contents_->RemoveObserver(this); // Destroy the WebContents. OnCloseContents(); api_web_contents_->Destroy(); } } void BrowserWindow::BeforeUnloadDialogCancelled() { WindowList::WindowCloseCancelled(window()); // Cancel unresponsive event when window close is cancelled. window_unresponsive_closure_.Cancel(); } void BrowserWindow::OnRendererUnresponsive(content::RenderProcessHost*) { // Schedule the unresponsive shortly later, since we may receive the // responsive event soon. This could happen after the whole application had // blocked for a while. // Also notice that when closing this event would be ignored because we have // explicitly started a close timeout counter. This is on purpose because we // don't want the unresponsive event to be sent too early when user is closing // the window. ScheduleUnresponsiveEvent(50); } void BrowserWindow::WebContentsDestroyed() { api_web_contents_ = nullptr; CloseImmediately(); } void BrowserWindow::OnCloseContents() { BaseWindow::ResetBrowserViews(); } void BrowserWindow::OnRendererResponsive(content::RenderProcessHost*) { window_unresponsive_closure_.Cancel(); Emit("responsive"); } void BrowserWindow::OnSetContentBounds(const gfx::Rect& rect) { // window.resizeTo(...) // window.moveTo(...) window()->SetBounds(rect, false); } void BrowserWindow::OnActivateContents() { // Hide the auto-hide menu when webContents is focused. #if !BUILDFLAG(IS_MAC) if (IsMenuBarAutoHide() && IsMenuBarVisible()) window()->SetMenuBarVisibility(false); #endif } void BrowserWindow::OnPageTitleUpdated(const std::u16string& title, bool explicit_set) { // Change window title to page title. auto self = GetWeakPtr(); if (!Emit("page-title-updated", title, explicit_set)) { // |this| might be deleted, or marked as destroyed by close(). if (self && !IsDestroyed()) SetTitle(base::UTF16ToUTF8(title)); } } void BrowserWindow::RequestPreferredWidth(int* width) { *width = web_contents()->GetPreferredSize().width(); } void BrowserWindow::OnCloseButtonClicked(bool* prevent_default) { // When user tries to close the window by clicking the close button, we do // not close the window immediately, instead we try to close the web page // first, and when the web page is closed the window will also be closed. *prevent_default = true; // Assume the window is not responding if it doesn't cancel the close and is // not closed in 5s, in this way we can quickly show the unresponsive // dialog when the window is busy executing some script without waiting for // the unresponsive timeout. if (window_unresponsive_closure_.IsCancelled()) ScheduleUnresponsiveEvent(5000); // Already closed by renderer. if (!web_contents() || !api_web_contents_) return; // Required to make beforeunload handler work. api_web_contents_->NotifyUserActivation(); // Trigger beforeunload events for associated BrowserViews. for (NativeBrowserView* view : window_->browser_views()) { auto* iwc = view->GetInspectableWebContents(); if (!iwc) continue; auto* vwc = iwc->GetWebContents(); auto* api_web_contents = api::WebContents::From(vwc); // Required to make beforeunload handler work. if (api_web_contents) api_web_contents->NotifyUserActivation(); if (vwc) { if (vwc->NeedToFireBeforeUnloadOrUnloadEvents()) { vwc->DispatchBeforeUnload(false /* auto_cancel */); } } } if (web_contents()->NeedToFireBeforeUnloadOrUnloadEvents()) { web_contents()->DispatchBeforeUnload(false /* auto_cancel */); } else { web_contents()->Close(); } } void BrowserWindow::OnWindowBlur() { if (api_web_contents_) web_contents()->StoreFocus(); BaseWindow::OnWindowBlur(); } void BrowserWindow::OnWindowFocus() { // focus/blur events might be emitted while closing window. if (api_web_contents_) { web_contents()->RestoreFocus(); #if !BUILDFLAG(IS_MAC) if (!api_web_contents_->IsDevToolsOpened()) web_contents()->Focus(); #endif } BaseWindow::OnWindowFocus(); } void BrowserWindow::OnWindowIsKeyChanged(bool is_key) { #if BUILDFLAG(IS_MAC) auto* rwhv = web_contents()->GetRenderWidgetHostView(); if (rwhv) rwhv->SetActive(is_key); window()->SetActive(is_key); #endif } void BrowserWindow::OnWindowLeaveFullScreen() { #if BUILDFLAG(IS_MAC) if (web_contents()->IsFullscreen()) web_contents()->ExitFullscreen(true); #endif BaseWindow::OnWindowLeaveFullScreen(); } void BrowserWindow::UpdateWindowControlsOverlay( const gfx::Rect& bounding_rect) { web_contents()->UpdateWindowControlsOverlay(bounding_rect); } void BrowserWindow::CloseImmediately() { // Close all child windows before closing current window. v8::HandleScope handle_scope(isolate()); for (v8::Local<v8::Value> value : child_windows_.Values(isolate())) { gin::Handle<BrowserWindow> child; if (gin::ConvertFromV8(isolate(), value, &child) && !child.IsEmpty()) child->window()->CloseImmediately(); } BaseWindow::CloseImmediately(); // Do not sent "unresponsive" event after window is closed. window_unresponsive_closure_.Cancel(); } void BrowserWindow::Focus() { if (api_web_contents_->IsOffScreen()) FocusOnWebView(); else BaseWindow::Focus(); } void BrowserWindow::Blur() { if (api_web_contents_->IsOffScreen()) BlurWebView(); else BaseWindow::Blur(); } void BrowserWindow::SetBackgroundColor(const std::string& color_name) { BaseWindow::SetBackgroundColor(color_name); SkColor color = ParseCSSColor(color_name); web_contents()->SetPageBaseBackgroundColor(color); auto* rwhv = web_contents()->GetRenderWidgetHostView(); if (rwhv) { rwhv->SetBackgroundColor(color); static_cast<content::RenderWidgetHostViewBase*>(rwhv) ->SetContentBackgroundColor(color); } // Also update the web preferences object otherwise the view will be reset on // the next load URL call if (api_web_contents_) { auto* web_preferences = WebContentsPreferences::From(api_web_contents_->web_contents()); if (web_preferences) { web_preferences->SetBackgroundColor(ParseCSSColor(color_name)); } } } void BrowserWindow::SetBrowserView( absl::optional<gin::Handle<BrowserView>> browser_view) { BaseWindow::ResetBrowserViews(); if (browser_view) BaseWindow::AddBrowserView(*browser_view); } void BrowserWindow::FocusOnWebView() { web_contents()->GetRenderViewHost()->GetWidget()->Focus(); } void BrowserWindow::BlurWebView() { web_contents()->GetRenderViewHost()->GetWidget()->Blur(); } bool BrowserWindow::IsWebViewFocused() { auto* host_view = web_contents()->GetRenderViewHost()->GetWidget()->GetView(); return host_view && host_view->HasFocus(); } v8::Local<v8::Value> BrowserWindow::GetWebContents(v8::Isolate* isolate) { if (web_contents_.IsEmpty()) return v8::Null(isolate); return v8::Local<v8::Value>::New(isolate, web_contents_); } #if BUILDFLAG(IS_WIN) void BrowserWindow::SetTitleBarOverlay(const gin_helper::Dictionary& options, gin_helper::Arguments* args) { // Ensure WCO is already enabled on this window if (!window_->titlebar_overlay_enabled()) { args->ThrowError("Titlebar overlay is not enabled"); return; } auto* window = static_cast<NativeWindowViews*>(window_.get()); bool updated = false; // Check and update the button color std::string btn_color; if (options.Get(options::kOverlayButtonColor, &btn_color)) { // Parse the string as a CSS color SkColor color; if (!content::ParseCssColorString(btn_color, &color)) { args->ThrowError("Could not parse color as CSS color"); return; } // Update the view window->set_overlay_button_color(color); updated = true; } // Check and update the symbol color std::string symbol_color; if (options.Get(options::kOverlaySymbolColor, &symbol_color)) { // Parse the string as a CSS color SkColor color; if (!content::ParseCssColorString(symbol_color, &color)) { args->ThrowError("Could not parse symbol color as CSS color"); return; } // Update the view window->set_overlay_symbol_color(color); updated = true; } // Check and update the height int height = 0; if (options.Get(options::kOverlayHeight, &height)) { window->set_titlebar_overlay_height(height); updated = true; } // If anything was updated, invalidate the layout and schedule a paint of the // window's frame view if (updated) { auto* frame_view = static_cast<WinFrameView*>( window->widget()->non_client_view()->frame_view()); frame_view->InvalidateCaptionButtons(); } } #endif void BrowserWindow::ScheduleUnresponsiveEvent(int ms) { if (!window_unresponsive_closure_.IsCancelled()) return; window_unresponsive_closure_.Reset(base::BindRepeating( &BrowserWindow::NotifyWindowUnresponsive, GetWeakPtr())); base::SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask( FROM_HERE, window_unresponsive_closure_.callback(), base::Milliseconds(ms)); } void BrowserWindow::NotifyWindowUnresponsive() { window_unresponsive_closure_.Cancel(); if (!window_->IsClosed() && window_->IsEnabled()) { Emit("unresponsive"); } } void BrowserWindow::OnWindowShow() { web_contents()->WasShown(); BaseWindow::OnWindowShow(); } void BrowserWindow::OnWindowHide() { web_contents()->WasOccluded(); BaseWindow::OnWindowHide(); } // static gin_helper::WrappableBase* BrowserWindow::New(gin_helper::ErrorThrower thrower, gin::Arguments* args) { if (!Browser::Get()->is_ready()) { thrower.ThrowError("Cannot create BrowserWindow before app is ready"); return nullptr; } if (args->Length() > 1) { args->ThrowError(); return nullptr; } gin_helper::Dictionary options; if (!(args->Length() == 1 && args->GetNext(&options))) { options = gin::Dictionary::CreateEmpty(args->isolate()); } return new BrowserWindow(args, options); } // static void BrowserWindow::BuildPrototype(v8::Isolate* isolate, v8::Local<v8::FunctionTemplate> prototype) { prototype->SetClassName(gin::StringToV8(isolate, "BrowserWindow")); gin_helper::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate()) .SetMethod("focusOnWebView", &BrowserWindow::FocusOnWebView) .SetMethod("blurWebView", &BrowserWindow::BlurWebView) .SetMethod("isWebViewFocused", &BrowserWindow::IsWebViewFocused) #if BUILDFLAG(IS_WIN) .SetMethod("setTitleBarOverlay", &BrowserWindow::SetTitleBarOverlay) #endif .SetProperty("webContents", &BrowserWindow::GetWebContents); } // static v8::Local<v8::Value> BrowserWindow::From(v8::Isolate* isolate, NativeWindow* native_window) { auto* existing = TrackableObject::FromWrappedClass(isolate, native_window); if (existing) return existing->GetWrapper(); else return v8::Null(isolate); } } // namespace electron::api namespace { using electron::api::BrowserWindow; 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("BrowserWindow", gin_helper::CreateConstructor<BrowserWindow>( isolate, base::BindRepeating(&BrowserWindow::New))); } } // namespace NODE_LINKED_BINDING_CONTEXT_AWARE(electron_browser_window, Initialize)
closed
electron/electron
https://github.com/electron/electron
38,532
[Feature Request]: Support full frame transparency with Mica background material
### 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. ### Problem Description The [Mica `backgroundMaterial`](https://github.com/electron/electron/pull/38163) effect does not appear below the WebContents. ### Proposed Solution The `backgroundMaterial` option should behave the same as when setting the `vibrancy` option. | macOS: `vibrancy: 'medium-light'` | Windows: `backgroundMaterial: 'acrylic'` | Windows: `backgroundMaterial: 'acrylic'` + `transparent: true` | | --- | --- | --- | | ![Screenshot 2023-05-31 at 4 30 04 PM](https://github.com/electron/electron/assets/1656324/3f2a47e7-ed33-4f88-ae0d-2f67b1cb9b1d) | ![image (5)](https://github.com/electron/electron/assets/1656324/cb4c3a2e-284f-4a54-a968-7870af8be549) | ![image (6)](https://github.com/electron/electron/assets/1656324/318797e0-63ea-49d6-9feb-50cd66db0664) | When `vibrancy` is set, the WebContents is transparent by default. The same should apply to `backgroundMaterial`. Setting `transparent: true` doesn't seem to be a valid workaround, but ideally should still work. The code below needs to be updated: https://github.com/electron/electron/blob/9ffffdb6ef202bd93be496b53fdd4156dd3504ce/shell/browser/api/electron_api_browser_window.cc#L58-L64 ### Alternatives Considered None. ### Additional Information Tested on: ``` Edition Windows 11 Pro Version 22H2 OS build 22621.1778 ``` Fiddle gist: https://gist.github.com/34cf667b21a5075d1f6fbe093d7ad7f9
https://github.com/electron/electron/issues/38532
https://github.com/electron/electron/pull/39708
ab185c058f894ddc556f67b2853de4adad2bb10c
d1827941790f23b241ef3f234a9782750ac97e8d
2023-05-31T20:43:55Z
c++
2023-09-11T12:51:54Z
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/containers/contains.h" #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/ui/drag_util.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 "third_party/skia/include/core/SkRegion.h" #include "ui/base/hit_test.h" #include "ui/views/widget/widget.h" #if !BUILDFLAG(IS_MAC) #include "shell/browser/ui/views/frameless_view.h" #endif #if BUILDFLAG(IS_WIN) #include "ui/base/win/shell.h" #include "ui/display/win/screen_win.h" #endif #if defined(USE_OZONE) #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()) 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_dict = gin::Dictionary::CreateEmpty(options.isolate()); options.Get(options::ktitleBarOverlay, &titlebar_overlay_dict); int height; if (titlebar_overlay_dict.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)); gfx::Size max_size = size_constraints.GetMaximumSize(); int max_width = max_size.width() > 0 ? max_size.width() : INT_MAX; int max_height = max_size.height() > 0 ? max_size.height() : INT_MAX; bool have_max_width = options.Get(options::kMaxWidth, &max_width); if (have_max_width && max_width <= 0) max_width = INT_MAX; bool have_max_height = options.Get(options::kMaxHeight, &max_height); if (have_max_height && max_height <= 0) max_height = INT_MAX; // By default the window has a default maximum size that prevents it // from being resized larger than the screen, so we should only set this // if the user has passed in values. if (have_max_height || have_max_width || !max_size.IsEmpty()) 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 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 } options.Get(options::kFullScreenable, &fullscreenable); SetFullScreenable(fullscreenable); if (fullscreen) SetFullScreen(true); bool resizable; if (options.Get(options::kResizable, &resizable)) { SetResizable(resizable); } 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); } #elif BUILDFLAG(IS_WIN) std::string material; if (options.Get(options::kBackgroundMaterial, &material)) { SetBackgroundMaterial(material); } #endif std::string color; if (options.Get(options::kBackgroundColor, &color)) { SetBackgroundColor(ParseCSSColor(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) { size_constraints_ = window_constraints; content_size_constraints_.reset(); } extensions::SizeConstraints NativeWindow::GetSizeConstraints() const { if (size_constraints_) return *size_constraints_; if (!content_size_constraints_) return extensions::SizeConstraints(); // Convert content size constraints to window size constraints. extensions::SizeConstraints constraints; if (content_size_constraints_->HasMaximumSize()) { gfx::Rect max_bounds = ContentBoundsToWindowBounds( gfx::Rect(content_size_constraints_->GetMaximumSize())); constraints.set_maximum_size(max_bounds.size()); } if (content_size_constraints_->HasMinimumSize()) { gfx::Rect min_bounds = ContentBoundsToWindowBounds( gfx::Rect(content_size_constraints_->GetMinimumSize())); constraints.set_minimum_size(min_bounds.size()); } return constraints; } void NativeWindow::SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints) { content_size_constraints_ = size_constraints; size_constraints_.reset(); } // The return value of GetContentSizeConstraints will be passed to Chromium // to set min/max sizes of window. Note that we are returning content size // instead of window size because that is what Chromium expects, see the // comment of |WidgetSizeIsClientSize| in Chromium's codebase to learn more. extensions::SizeConstraints NativeWindow::GetContentSizeConstraints() const { if (content_size_constraints_) return *content_size_constraints_; if (!size_constraints_) return extensions::SizeConstraints(); // Convert window size constraints to content size constraints. // Note that we are not caching the results, because Chromium reccalculates // window frame size everytime when min/max sizes are passed, and we must // do the same otherwise the resulting size with frame included will be wrong. extensions::SizeConstraints constraints; if (size_constraints_->HasMaximumSize()) { gfx::Rect max_bounds = WindowBoundsToContentBounds( gfx::Rect(size_constraints_->GetMaximumSize())); constraints.set_maximum_size(max_bounds.size()); } if (size_constraints_->HasMinimumSize()) { gfx::Rect min_bounds = WindowBoundsToContentBounds( gfx::Rect(size_constraints_->GetMinimumSize())); constraints.set_minimum_size(min_bounds.size()); } return constraints; } void NativeWindow::SetMinimumSize(const gfx::Size& size) { extensions::SizeConstraints size_constraints = GetSizeConstraints(); 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 = GetSizeConstraints(); 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::InvalidateShadow() {} void NativeWindow::SetAutoHideCursor(bool auto_hide) {} void NativeWindow::SelectPreviousTab() {} void NativeWindow::SelectNextTab() {} void NativeWindow::ShowAllTabs() {} 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::SetBackgroundMaterial(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::NotifyWindowRequestPreferredWidth(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::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, base::Value::Dict 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 int NativeWindow::NonClientHitTest(const gfx::Point& point) { #if !BUILDFLAG(IS_MAC) // We need to ensure we account for resizing borders on Windows and Linux. if ((!has_frame() || has_client_frame()) && IsResizable()) { auto* frame = static_cast<FramelessView*>(widget()->non_client_view()->frame_view()); int border_hit = frame->ResizingBorderHitTest(point); if (border_hit != HTNOWHERE) return border_hit; } #endif for (auto* provider : draggable_region_providers_) { int hit = provider->NonClientHitTest(point); if (hit != HTNOWHERE) return hit; } return HTNOWHERE; } void NativeWindow::AddDraggableRegionProvider( DraggableRegionProvider* provider) { if (!base::Contains(draggable_region_providers_, provider)) { draggable_region_providers_.push_back(provider); } } void NativeWindow::RemoveDraggableRegionProvider( DraggableRegionProvider* provider) { draggable_region_providers_.remove_if( [&provider](DraggableRegionProvider* p) { return p == provider; }); } 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_); } void NativeWindow::HandlePendingFullscreenTransitions() { if (pending_transitions_.empty()) { set_fullscreen_transition_type(FullScreenTransitionType::kNone); return; } bool next_transition = pending_transitions_.front(); pending_transitions_.pop(); SetFullScreen(next_transition); } // 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
38,532
[Feature Request]: Support full frame transparency with Mica background material
### 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. ### Problem Description The [Mica `backgroundMaterial`](https://github.com/electron/electron/pull/38163) effect does not appear below the WebContents. ### Proposed Solution The `backgroundMaterial` option should behave the same as when setting the `vibrancy` option. | macOS: `vibrancy: 'medium-light'` | Windows: `backgroundMaterial: 'acrylic'` | Windows: `backgroundMaterial: 'acrylic'` + `transparent: true` | | --- | --- | --- | | ![Screenshot 2023-05-31 at 4 30 04 PM](https://github.com/electron/electron/assets/1656324/3f2a47e7-ed33-4f88-ae0d-2f67b1cb9b1d) | ![image (5)](https://github.com/electron/electron/assets/1656324/cb4c3a2e-284f-4a54-a968-7870af8be549) | ![image (6)](https://github.com/electron/electron/assets/1656324/318797e0-63ea-49d6-9feb-50cd66db0664) | When `vibrancy` is set, the WebContents is transparent by default. The same should apply to `backgroundMaterial`. Setting `transparent: true` doesn't seem to be a valid workaround, but ideally should still work. The code below needs to be updated: https://github.com/electron/electron/blob/9ffffdb6ef202bd93be496b53fdd4156dd3504ce/shell/browser/api/electron_api_browser_window.cc#L58-L64 ### Alternatives Considered None. ### Additional Information Tested on: ``` Edition Windows 11 Pro Version 22H2 OS build 22621.1778 ``` Fiddle gist: https://gist.github.com/34cf667b21a5075d1f6fbe093d7ad7f9
https://github.com/electron/electron/issues/38532
https://github.com/electron/electron/pull/39708
ab185c058f894ddc556f67b2853de4adad2bb10c
d1827941790f23b241ef3f234a9782750ac97e8d
2023-05-31T20:43:55Z
c++
2023-09-11T12:51:54Z
shell/browser/native_window.h
// Copyright (c) 2013 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_NATIVE_WINDOW_H_ #define ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_H_ #include <list> #include <memory> #include <queue> #include <string> #include <vector> #include "base/memory/raw_ptr.h" #include "base/memory/weak_ptr.h" #include "base/observer_list.h" #include "base/supports_user_data.h" #include "content/public/browser/desktop_media_id.h" #include "content/public/browser/web_contents_user_data.h" #include "electron/shell/common/api/api.mojom.h" #include "extensions/browser/app_window/size_constraints.h" #include "shell/browser/draggable_region_provider.h" #include "shell/browser/native_window_observer.h" #include "shell/browser/ui/inspectable_web_contents_view.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/views/widget/widget_delegate.h" class SkRegion; namespace content { struct NativeWebKeyboardEvent; } namespace gfx { class Image; class Point; class Rect; enum class ResizeEdge; class Size; } // namespace gfx namespace gin_helper { class Dictionary; class PersistentDictionary; } // namespace gin_helper namespace electron { class ElectronMenuModel; class NativeBrowserView; namespace api { class BrowserView; } #if BUILDFLAG(IS_MAC) typedef NSView* NativeWindowHandle; #else typedef gfx::AcceleratedWidget NativeWindowHandle; #endif class NativeWindow : public base::SupportsUserData, public views::WidgetDelegate { public: ~NativeWindow() override; // disable copy NativeWindow(const NativeWindow&) = delete; NativeWindow& operator=(const NativeWindow&) = delete; // Create window with existing WebContents, the caller is responsible for // managing the window's live. static NativeWindow* Create(const gin_helper::Dictionary& options, NativeWindow* parent = nullptr); void InitFromOptions(const gin_helper::Dictionary& options); virtual void SetContentView(views::View* view) = 0; virtual void Close() = 0; virtual void CloseImmediately() = 0; virtual bool IsClosed() const; virtual void Focus(bool focus) = 0; virtual bool IsFocused() = 0; virtual void Show() = 0; virtual void ShowInactive() = 0; virtual void Hide() = 0; virtual bool IsVisible() = 0; virtual bool IsEnabled() = 0; virtual void SetEnabled(bool enable) = 0; virtual void Maximize() = 0; virtual void Unmaximize() = 0; virtual bool IsMaximized() = 0; virtual void Minimize() = 0; virtual void Restore() = 0; virtual bool IsMinimized() = 0; virtual void SetFullScreen(bool fullscreen) = 0; virtual bool IsFullscreen() const = 0; virtual void SetBounds(const gfx::Rect& bounds, bool animate = false) = 0; virtual gfx::Rect GetBounds() = 0; virtual void SetSize(const gfx::Size& size, bool animate = false); virtual gfx::Size GetSize(); virtual void SetPosition(const gfx::Point& position, bool animate = false); virtual gfx::Point GetPosition(); virtual void SetContentSize(const gfx::Size& size, bool animate = false); virtual gfx::Size GetContentSize(); virtual void SetContentBounds(const gfx::Rect& bounds, bool animate = false); virtual gfx::Rect GetContentBounds(); virtual bool IsNormal(); virtual gfx::Rect GetNormalBounds() = 0; virtual void SetSizeConstraints( const extensions::SizeConstraints& window_constraints); virtual extensions::SizeConstraints GetSizeConstraints() const; virtual void SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints); virtual extensions::SizeConstraints GetContentSizeConstraints() const; virtual void SetMinimumSize(const gfx::Size& size); virtual gfx::Size GetMinimumSize() const; virtual void SetMaximumSize(const gfx::Size& size); virtual gfx::Size GetMaximumSize() const; virtual gfx::Size GetContentMinimumSize() const; virtual gfx::Size GetContentMaximumSize() const; virtual void SetSheetOffset(const double offsetX, const double offsetY); virtual double GetSheetOffsetX(); virtual double GetSheetOffsetY(); virtual void SetResizable(bool resizable) = 0; virtual bool MoveAbove(const std::string& sourceId) = 0; virtual void MoveTop() = 0; virtual bool IsResizable() = 0; virtual void SetMovable(bool movable) = 0; virtual bool IsMovable() = 0; virtual void SetMinimizable(bool minimizable) = 0; virtual bool IsMinimizable() = 0; virtual void SetMaximizable(bool maximizable) = 0; virtual bool IsMaximizable() = 0; virtual void SetFullScreenable(bool fullscreenable) = 0; virtual bool IsFullScreenable() = 0; virtual void SetClosable(bool closable) = 0; virtual bool IsClosable() = 0; virtual void SetAlwaysOnTop(ui::ZOrderLevel z_order, const std::string& level = "floating", int relativeLevel = 0) = 0; virtual ui::ZOrderLevel GetZOrderLevel() = 0; virtual void Center() = 0; virtual void Invalidate() = 0; virtual void SetTitle(const std::string& title) = 0; virtual std::string GetTitle() = 0; #if BUILDFLAG(IS_MAC) virtual std::string GetAlwaysOnTopLevel() = 0; virtual void SetActive(bool is_key) = 0; virtual bool IsActive() const = 0; virtual void RemoveChildFromParentWindow() = 0; virtual void RemoveChildWindow(NativeWindow* child) = 0; virtual void AttachChildren() = 0; virtual void DetachChildren() = 0; #endif // Ability to augment the window title for the screen readers. void SetAccessibleTitle(const std::string& title); std::string GetAccessibleTitle(); virtual void FlashFrame(bool flash) = 0; virtual void SetSkipTaskbar(bool skip) = 0; virtual void SetExcludedFromShownWindowsMenu(bool excluded) = 0; virtual bool IsExcludedFromShownWindowsMenu() = 0; virtual void SetSimpleFullScreen(bool simple_fullscreen) = 0; virtual bool IsSimpleFullScreen() = 0; virtual void SetKiosk(bool kiosk) = 0; virtual bool IsKiosk() = 0; virtual bool IsTabletMode() const; virtual void SetBackgroundColor(SkColor color) = 0; virtual SkColor GetBackgroundColor() = 0; virtual void InvalidateShadow(); virtual void SetHasShadow(bool has_shadow) = 0; virtual bool HasShadow() = 0; virtual void SetOpacity(const double opacity) = 0; virtual double GetOpacity() = 0; virtual void SetRepresentedFilename(const std::string& filename); virtual std::string GetRepresentedFilename(); virtual void SetDocumentEdited(bool edited); virtual bool IsDocumentEdited(); virtual void SetIgnoreMouseEvents(bool ignore, bool forward) = 0; virtual void SetContentProtection(bool enable) = 0; virtual void SetFocusable(bool focusable); virtual bool IsFocusable(); virtual void SetMenu(ElectronMenuModel* menu); virtual void SetParentWindow(NativeWindow* parent); virtual void AddBrowserView(NativeBrowserView* browser_view) = 0; virtual void RemoveBrowserView(NativeBrowserView* browser_view) = 0; virtual void SetTopBrowserView(NativeBrowserView* browser_view) = 0; virtual content::DesktopMediaID GetDesktopMediaID() const = 0; virtual gfx::NativeView GetNativeView() const = 0; virtual gfx::NativeWindow GetNativeWindow() const = 0; virtual gfx::AcceleratedWidget GetAcceleratedWidget() const = 0; virtual NativeWindowHandle GetNativeWindowHandle() const = 0; // Taskbar/Dock APIs. enum class ProgressState { kNone, // no progress, no marking kIndeterminate, // progress, indeterminate kError, // progress, errored (red) kPaused, // progress, paused (yellow) kNormal, // progress, not marked (green) }; virtual void SetProgressBar(double progress, const ProgressState state) = 0; virtual void SetOverlayIcon(const gfx::Image& overlay, const std::string& description) = 0; // Workspace APIs. virtual void SetVisibleOnAllWorkspaces( bool visible, bool visibleOnFullScreen = false, bool skipTransformProcessType = false) = 0; virtual bool IsVisibleOnAllWorkspaces() = 0; virtual void SetAutoHideCursor(bool auto_hide); // Vibrancy API virtual void SetVibrancy(const std::string& type); virtual void SetBackgroundMaterial(const std::string& type); // Traffic Light API #if BUILDFLAG(IS_MAC) virtual void SetWindowButtonVisibility(bool visible) = 0; virtual bool GetWindowButtonVisibility() const = 0; virtual void SetWindowButtonPosition(absl::optional<gfx::Point> position) = 0; virtual absl::optional<gfx::Point> GetWindowButtonPosition() const = 0; virtual void RedrawTrafficLights() = 0; virtual void UpdateFrame() = 0; #endif // whether windows should be ignored by mission control #if BUILDFLAG(IS_MAC) virtual bool IsHiddenInMissionControl() = 0; virtual void SetHiddenInMissionControl(bool hidden) = 0; #endif // Touchbar API virtual void SetTouchBar(std::vector<gin_helper::PersistentDictionary> items); virtual void RefreshTouchBarItem(const std::string& item_id); virtual void SetEscapeTouchBarItem(gin_helper::PersistentDictionary item); // Native Tab API virtual void SelectPreviousTab(); virtual void SelectNextTab(); virtual void ShowAllTabs(); virtual void MergeAllWindows(); virtual void MoveTabToNewWindow(); virtual void ToggleTabBar(); virtual bool AddTabbedWindow(NativeWindow* window); // Toggle the menu bar. virtual void SetAutoHideMenuBar(bool auto_hide); virtual bool IsMenuBarAutoHide(); virtual void SetMenuBarVisibility(bool visible); virtual bool IsMenuBarVisible(); // Set the aspect ratio when resizing window. double GetAspectRatio(); gfx::Size GetAspectRatioExtraSize(); virtual void SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size); // File preview APIs. virtual void PreviewFile(const std::string& path, const std::string& display_name); virtual void CloseFilePreview(); virtual void SetGTKDarkThemeEnabled(bool use_dark_theme) {} // Converts between content bounds and window bounds. virtual gfx::Rect ContentBoundsToWindowBounds( const gfx::Rect& bounds) const = 0; virtual gfx::Rect WindowBoundsToContentBounds( const gfx::Rect& bounds) const = 0; base::WeakPtr<NativeWindow> GetWeakPtr() { return weak_factory_.GetWeakPtr(); } virtual gfx::Rect GetWindowControlsOverlayRect(); virtual void SetWindowControlsOverlayRect(const gfx::Rect& overlay_rect); // Methods called by the WebContents. virtual void HandleKeyboardEvent( content::WebContents*, const content::NativeWebKeyboardEvent& event) {} // Public API used by platform-dependent delegates and observers to send UI // related notifications. void NotifyWindowRequestPreferredWidth(int* width); void NotifyWindowCloseButtonClicked(); void NotifyWindowClosed(); void NotifyWindowEndSession(); void NotifyWindowBlur(); void NotifyWindowFocus(); void NotifyWindowShow(); void NotifyWindowIsKeyChanged(bool is_key); void NotifyWindowHide(); void NotifyWindowMaximize(); void NotifyWindowUnmaximize(); void NotifyWindowMinimize(); void NotifyWindowRestore(); void NotifyWindowMove(); void NotifyWindowWillResize(const gfx::Rect& new_bounds, const gfx::ResizeEdge& edge, bool* prevent_default); void NotifyWindowResize(); void NotifyWindowResized(); void NotifyWindowWillMove(const gfx::Rect& new_bounds, bool* prevent_default); void NotifyWindowMoved(); void NotifyWindowSwipe(const std::string& direction); void NotifyWindowRotateGesture(float rotation); void NotifyWindowSheetBegin(); void NotifyWindowSheetEnd(); virtual void NotifyWindowEnterFullScreen(); virtual void NotifyWindowLeaveFullScreen(); void NotifyWindowEnterHtmlFullScreen(); void NotifyWindowLeaveHtmlFullScreen(); void NotifyWindowAlwaysOnTopChanged(); void NotifyWindowExecuteAppCommand(const std::string& command); void NotifyTouchBarItemInteraction(const std::string& item_id, base::Value::Dict details); void NotifyNewWindowForTab(); void NotifyWindowSystemContextMenu(int x, int y, bool* prevent_default); void NotifyLayoutWindowControlsOverlay(); #if BUILDFLAG(IS_WIN) void NotifyWindowMessage(UINT message, WPARAM w_param, LPARAM l_param); #endif void AddObserver(NativeWindowObserver* obs) { observers_.AddObserver(obs); } void RemoveObserver(NativeWindowObserver* obs) { observers_.RemoveObserver(obs); } // Handle fullscreen transitions. void HandlePendingFullscreenTransitions(); enum class FullScreenTransitionState { kEntering, kExiting, kNone }; void set_fullscreen_transition_state(FullScreenTransitionState state) { fullscreen_transition_state_ = state; } FullScreenTransitionState fullscreen_transition_state() const { return fullscreen_transition_state_; } enum class FullScreenTransitionType { kHTML, kNative, kNone }; void set_fullscreen_transition_type(FullScreenTransitionType type) { fullscreen_transition_type_ = type; } FullScreenTransitionType fullscreen_transition_type() const { return fullscreen_transition_type_; } views::Widget* widget() const { return widget_.get(); } views::View* content_view() const { return content_view_; } enum class TitleBarStyle { kNormal, kHidden, kHiddenInset, kCustomButtonsOnHover, }; TitleBarStyle title_bar_style() const { return title_bar_style_; } int titlebar_overlay_height() const { return titlebar_overlay_height_; } void set_titlebar_overlay_height(int height) { titlebar_overlay_height_ = height; } bool titlebar_overlay_enabled() const { return titlebar_overlay_; } bool has_frame() const { return has_frame_; } void set_has_frame(bool has_frame) { has_frame_ = has_frame; } bool has_client_frame() const { return has_client_frame_; } bool transparent() const { return transparent_; } bool enable_larger_than_screen() const { return enable_larger_than_screen_; } NativeWindow* parent() const { return parent_; } bool is_modal() const { return is_modal_; } std::list<NativeBrowserView*> browser_views() const { return browser_views_; } int32_t window_id() const { return next_id_; } void add_child_window(NativeWindow* child) { child_windows_.push_back(child); } int NonClientHitTest(const gfx::Point& point); void AddDraggableRegionProvider(DraggableRegionProvider* provider); void RemoveDraggableRegionProvider(DraggableRegionProvider* provider); protected: friend class api::BrowserView; NativeWindow(const gin_helper::Dictionary& options, NativeWindow* parent); // views::WidgetDelegate: views::Widget* GetWidget() override; const views::Widget* GetWidget() const override; std::u16string GetAccessibleWindowTitle() const override; void set_content_view(views::View* view) { content_view_ = view; } void add_browser_view(NativeBrowserView* browser_view) { browser_views_.push_back(browser_view); } void remove_browser_view(NativeBrowserView* browser_view) { browser_views_.remove_if( [&browser_view](NativeBrowserView* n) { return (n == browser_view); }); } // The boolean parsing of the "titleBarOverlay" option bool titlebar_overlay_ = false; // The custom height parsed from the "height" option in a Object // "titleBarOverlay" int titlebar_overlay_height_ = 0; // The "titleBarStyle" option. TitleBarStyle title_bar_style_ = TitleBarStyle::kNormal; // Minimum and maximum size. absl::optional<extensions::SizeConstraints> size_constraints_; // Same as above but stored as content size, we are storing 2 types of size // constraints beacause converting between them will cause rounding errors // on HiDPI displays on some environments. absl::optional<extensions::SizeConstraints> content_size_constraints_; std::queue<bool> pending_transitions_; FullScreenTransitionState fullscreen_transition_state_ = FullScreenTransitionState::kNone; FullScreenTransitionType fullscreen_transition_type_ = FullScreenTransitionType::kNone; std::list<NativeWindow*> child_windows_; private: std::unique_ptr<views::Widget> widget_; static int32_t next_id_; // The content view, weak ref. raw_ptr<views::View> content_view_ = nullptr; // Whether window has standard frame. bool has_frame_ = true; // Whether window has standard frame, but it's drawn by Electron (the client // application) instead of the OS. Currently only has meaning on Linux for // Wayland hosts. bool has_client_frame_ = false; // Whether window is transparent. bool transparent_ = false; // Whether window can be resized larger than screen. bool enable_larger_than_screen_ = false; // The windows has been closed. bool is_closed_ = false; // Used to display sheets at the appropriate horizontal and vertical offsets // on macOS. double sheet_offset_x_ = 0.0; double sheet_offset_y_ = 0.0; // Used to maintain the aspect ratio of a view which is inside of the // content view. double aspect_ratio_ = 0.0; gfx::Size aspect_ratio_extraSize_; // The parent window, it is guaranteed to be valid during this window's life. raw_ptr<NativeWindow> parent_ = nullptr; // Is this a modal window. bool is_modal_ = false; // The browser view layer. std::list<NativeBrowserView*> browser_views_; std::list<DraggableRegionProvider*> draggable_region_providers_; // Observers of this window. base::ObserverList<NativeWindowObserver> observers_; // Accessible title. std::u16string accessible_title_; gfx::Rect overlay_rect_; base::WeakPtrFactory<NativeWindow> weak_factory_{this}; }; // This class provides a hook to get a NativeWindow from a WebContents. class NativeWindowRelay : public content::WebContentsUserData<NativeWindowRelay> { public: static void CreateForWebContents(content::WebContents*, base::WeakPtr<NativeWindow>); ~NativeWindowRelay() override; NativeWindow* GetNativeWindow() const { return native_window_.get(); } WEB_CONTENTS_USER_DATA_KEY_DECL(); private: friend class content::WebContentsUserData<NativeWindow>; explicit NativeWindowRelay(content::WebContents* web_contents, base::WeakPtr<NativeWindow> window); base::WeakPtr<NativeWindow> native_window_; }; } // namespace electron #endif // ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_H_
closed
electron/electron
https://github.com/electron/electron
38,532
[Feature Request]: Support full frame transparency with Mica background material
### 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. ### Problem Description The [Mica `backgroundMaterial`](https://github.com/electron/electron/pull/38163) effect does not appear below the WebContents. ### Proposed Solution The `backgroundMaterial` option should behave the same as when setting the `vibrancy` option. | macOS: `vibrancy: 'medium-light'` | Windows: `backgroundMaterial: 'acrylic'` | Windows: `backgroundMaterial: 'acrylic'` + `transparent: true` | | --- | --- | --- | | ![Screenshot 2023-05-31 at 4 30 04 PM](https://github.com/electron/electron/assets/1656324/3f2a47e7-ed33-4f88-ae0d-2f67b1cb9b1d) | ![image (5)](https://github.com/electron/electron/assets/1656324/cb4c3a2e-284f-4a54-a968-7870af8be549) | ![image (6)](https://github.com/electron/electron/assets/1656324/318797e0-63ea-49d6-9feb-50cd66db0664) | When `vibrancy` is set, the WebContents is transparent by default. The same should apply to `backgroundMaterial`. Setting `transparent: true` doesn't seem to be a valid workaround, but ideally should still work. The code below needs to be updated: https://github.com/electron/electron/blob/9ffffdb6ef202bd93be496b53fdd4156dd3504ce/shell/browser/api/electron_api_browser_window.cc#L58-L64 ### Alternatives Considered None. ### Additional Information Tested on: ``` Edition Windows 11 Pro Version 22H2 OS build 22621.1778 ``` Fiddle gist: https://gist.github.com/34cf667b21a5075d1f6fbe093d7ad7f9
https://github.com/electron/electron/issues/38532
https://github.com/electron/electron/pull/39708
ab185c058f894ddc556f67b2853de4adad2bb10c
d1827941790f23b241ef3f234a9782750ac97e8d
2023-05-31T20:43:55Z
c++
2023-09-11T12:51:54Z
shell/browser/native_window_mac.mm
// 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_mac.h" #include <AvailabilityMacros.h> #include <objc/objc-runtime.h> #include <algorithm> #include <memory> #include <string> #include <utility> #include <vector> #include "base/apple/scoped_cftyperef.h" #include "base/mac/mac_util.h" #include "base/strings/sys_string_conversions.h" #include "components/remote_cocoa/app_shim/native_widget_ns_window_bridge.h" #include "components/remote_cocoa/browser/scoped_cg_window_id.h" #include "content/public/browser/browser_accessibility_state.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/desktop_media_id.h" #include "shell/browser/browser.h" #include "shell/browser/javascript_environment.h" #include "shell/browser/native_browser_view_mac.h" #include "shell/browser/ui/cocoa/electron_native_widget_mac.h" #include "shell/browser/ui/cocoa/electron_ns_window.h" #include "shell/browser/ui/cocoa/electron_ns_window_delegate.h" #include "shell/browser/ui/cocoa/electron_preview_item.h" #include "shell/browser/ui/cocoa/electron_touch_bar.h" #include "shell/browser/ui/cocoa/root_view_mac.h" #include "shell/browser/ui/cocoa/window_buttons_proxy.h" #include "shell/browser/ui/drag_util.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/window_list.h" #include "shell/common/gin_converters/gfx_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/node_includes.h" #include "shell/common/options_switches.h" #include "shell/common/process_util.h" #include "skia/ext/skia_utils_mac.h" #include "third_party/skia/include/core/SkRegion.h" #include "third_party/webrtc/modules/desktop_capture/mac/window_list_utils.h" #include "ui/base/hit_test.h" #include "ui/display/screen.h" #include "ui/gfx/skia_util.h" #include "ui/gl/gpu_switching_manager.h" #include "ui/views/background.h" #include "ui/views/cocoa/native_widget_mac_ns_window_host.h" #include "ui/views/widget/widget.h" #include "ui/views/window/native_frame_view_mac.h" @interface ElectronProgressBar : NSProgressIndicator @end @implementation ElectronProgressBar - (void)drawRect:(NSRect)dirtyRect { if (self.style != NSProgressIndicatorStyleBar) return; // Draw edges of rounded rect. NSRect rect = NSInsetRect([self bounds], 1.0, 1.0); CGFloat radius = rect.size.height / 2; NSBezierPath* bezier_path = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [bezier_path setLineWidth:2.0]; [[NSColor grayColor] set]; [bezier_path stroke]; // Fill the rounded rect. rect = NSInsetRect(rect, 2.0, 2.0); radius = rect.size.height / 2; bezier_path = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [bezier_path setLineWidth:1.0]; [bezier_path addClip]; // Calculate the progress width. rect.size.width = floor(rect.size.width * ([self doubleValue] / [self maxValue])); // Fill the progress bar with color blue. [[NSColor colorWithSRGBRed:0.2 green:0.6 blue:1 alpha:1] set]; NSRectFill(rect); } @end namespace gin { template <> struct Converter<electron::NativeWindowMac::VisualEffectState> { static bool FromV8(v8::Isolate* isolate, v8::Handle<v8::Value> val, electron::NativeWindowMac::VisualEffectState* out) { using VisualEffectState = electron::NativeWindowMac::VisualEffectState; std::string visual_effect_state; if (!ConvertFromV8(isolate, val, &visual_effect_state)) return false; if (visual_effect_state == "followWindow") { *out = VisualEffectState::kFollowWindow; } else if (visual_effect_state == "active") { *out = VisualEffectState::kActive; } else if (visual_effect_state == "inactive") { *out = VisualEffectState::kInactive; } else { return false; } return true; } }; } // namespace gin namespace electron { namespace { bool IsFramelessWindow(NSView* view) { NSWindow* nswindow = [view window]; if (![nswindow respondsToSelector:@selector(shell)]) return false; NativeWindow* window = [static_cast<ElectronNSWindow*>(nswindow) shell]; return window && !window->has_frame(); } IMP original_set_frame_size = nullptr; IMP original_view_did_move_to_superview = nullptr; // This method is directly called by NSWindow during a window resize on OSX // 10.10.0, beta 2. We must override it to prevent the content view from // shrinking. void SetFrameSize(NSView* self, SEL _cmd, NSSize size) { if (!IsFramelessWindow(self)) { auto original = reinterpret_cast<decltype(&SetFrameSize)>(original_set_frame_size); return original(self, _cmd, size); } // For frameless window, resize the view to cover full window. if ([self superview]) size = [[self superview] bounds].size; auto super_impl = reinterpret_cast<decltype(&SetFrameSize)>( [[self superclass] instanceMethodForSelector:_cmd]); super_impl(self, _cmd, size); } // The contentView gets moved around during certain full-screen operations. // This is less than ideal, and should eventually be removed. void ViewDidMoveToSuperview(NSView* self, SEL _cmd) { if (!IsFramelessWindow(self)) { // [BridgedContentView viewDidMoveToSuperview]; auto original = reinterpret_cast<decltype(&ViewDidMoveToSuperview)>( original_view_did_move_to_superview); if (original) original(self, _cmd); return; } [self setFrame:[[self superview] bounds]]; } // -[NSWindow orderWindow] does not handle reordering for children // windows. Their order is fixed to the attachment order (the last attached // window is on the top). Therefore, work around it by re-parenting in our // desired order. void ReorderChildWindowAbove(NSWindow* child_window, NSWindow* other_window) { NSWindow* parent = [child_window parentWindow]; DCHECK(parent); // `ordered_children` sorts children windows back to front. NSArray<NSWindow*>* children = [[child_window parentWindow] childWindows]; std::vector<std::pair<NSInteger, NSWindow*>> ordered_children; for (NSWindow* child in children) ordered_children.push_back({[child orderedIndex], child}); std::sort(ordered_children.begin(), ordered_children.end(), std::greater<>()); // If `other_window` is nullptr, place `child_window` in front of // all other children windows. if (other_window == nullptr) other_window = ordered_children.back().second; if (child_window == other_window) return; for (NSWindow* child in children) [parent removeChildWindow:child]; const bool relative_to_parent = parent == other_window; if (relative_to_parent) [parent addChildWindow:child_window ordered:NSWindowAbove]; // Re-parent children windows in the desired order. for (auto [ordered_index, child] : ordered_children) { if (child != child_window && child != other_window) { [parent addChildWindow:child ordered:NSWindowAbove]; } else if (child == other_window && !relative_to_parent) { [parent addChildWindow:other_window ordered:NSWindowAbove]; [parent addChildWindow:child_window ordered:NSWindowAbove]; } } } } // namespace NativeWindowMac::NativeWindowMac(const gin_helper::Dictionary& options, NativeWindow* parent) : NativeWindow(options, parent), root_view_(new RootViewMac(this)) { ui::NativeTheme::GetInstanceForNativeUi()->AddObserver(this); display::Screen::GetScreen()->AddObserver(this); int width = 800, height = 600; options.Get(options::kWidth, &width); options.Get(options::kHeight, &height); NSRect main_screen_rect = [[[NSScreen screens] firstObject] frame]; gfx::Rect bounds(round((NSWidth(main_screen_rect) - width) / 2), round((NSHeight(main_screen_rect) - height) / 2), width, height); bool resizable = true; options.Get(options::kResizable, &resizable); options.Get(options::kZoomToPageWidth, &zoom_to_page_width_); options.Get(options::kSimpleFullScreen, &always_simple_fullscreen_); options.GetOptional(options::kTrafficLightPosition, &traffic_light_position_); options.Get(options::kVisualEffectState, &visual_effect_state_); if (options.Has(options::kFullscreenWindowTitle)) { EmitWarning( node::Environment::GetCurrent(JavascriptEnvironment::GetIsolate()), "\"fullscreenWindowTitle\" option has been deprecated and is " "no-op now.", "electron"); } bool minimizable = true; options.Get(options::kMinimizable, &minimizable); bool maximizable = true; options.Get(options::kMaximizable, &maximizable); bool closable = true; options.Get(options::kClosable, &closable); std::string tabbingIdentifier; options.Get(options::kTabbingIdentifier, &tabbingIdentifier); std::string windowType; options.Get(options::kType, &windowType); bool hiddenInMissionControl = false; options.Get(options::kHiddenInMissionControl, &hiddenInMissionControl); bool useStandardWindow = true; // eventually deprecate separate "standardWindow" option in favor of // standard / textured window types options.Get(options::kStandardWindow, &useStandardWindow); if (windowType == "textured") { useStandardWindow = false; } // The window without titlebar is treated the same with frameless window. if (title_bar_style_ != TitleBarStyle::kNormal) set_has_frame(false); NSUInteger styleMask = NSWindowStyleMaskTitled; // The NSWindowStyleMaskFullSizeContentView style removes rounded corners // for frameless window. bool rounded_corner = true; options.Get(options::kRoundedCorners, &rounded_corner); if (!rounded_corner && !has_frame()) styleMask = NSWindowStyleMaskBorderless; if (minimizable) styleMask |= NSWindowStyleMaskMiniaturizable; if (closable) styleMask |= NSWindowStyleMaskClosable; if (resizable) styleMask |= NSWindowStyleMaskResizable; if (!useStandardWindow || transparent() || !has_frame()) styleMask |= NSWindowStyleMaskTexturedBackground; // Create views::Widget and assign window_ with it. // TODO(zcbenz): Get rid of the window_ in future. 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.native_widget = new ElectronNativeWidgetMac(this, windowType, styleMask, widget()); widget()->Init(std::move(params)); SetCanResize(resizable); window_ = static_cast<ElectronNSWindow*>( widget()->GetNativeWindow().GetNativeNSWindow()); RegisterDeleteDelegateCallback(base::BindOnce( [](NativeWindowMac* window) { if (window->window_) window->window_ = nil; if (window->buttons_proxy_) window->buttons_proxy_ = nil; }, this)); [window_ setEnableLargerThanScreen:enable_larger_than_screen()]; window_delegate_ = [[ElectronNSWindowDelegate alloc] initWithShell:this]; [window_ setDelegate:window_delegate_]; // Only use native parent window for non-modal windows. if (parent && !is_modal()) { SetParentWindow(parent); } if (transparent()) { // Setting the background color to clear will also hide the shadow. [window_ setBackgroundColor:[NSColor clearColor]]; } if (windowType == "desktop") { [window_ setLevel:kCGDesktopWindowLevel - 1]; [window_ setDisableKeyOrMainWindow:YES]; [window_ setCollectionBehavior:(NSWindowCollectionBehaviorCanJoinAllSpaces | NSWindowCollectionBehaviorStationary | NSWindowCollectionBehaviorIgnoresCycle)]; } if (windowType == "panel") { [window_ setLevel:NSFloatingWindowLevel]; } bool focusable; if (options.Get(options::kFocusable, &focusable) && !focusable) [window_ setDisableKeyOrMainWindow:YES]; if (transparent() || !has_frame()) { // Don't show title bar. [window_ setTitlebarAppearsTransparent:YES]; [window_ setTitleVisibility:NSWindowTitleHidden]; // Remove non-transparent corners, see // https://github.com/electron/electron/issues/517. [window_ setOpaque:NO]; // Show window buttons if titleBarStyle is not "normal". if (title_bar_style_ == TitleBarStyle::kNormal) { InternalSetWindowButtonVisibility(false); } else { buttons_proxy_ = [[WindowButtonsProxy alloc] initWithWindow:window_]; [buttons_proxy_ setHeight:titlebar_overlay_height()]; if (traffic_light_position_) { [buttons_proxy_ setMargin:*traffic_light_position_]; } else if (title_bar_style_ == TitleBarStyle::kHiddenInset) { // For macOS >= 11, while this value does not match official macOS apps // like Safari or Notes, it matches titleBarStyle's old implementation // before Electron <= 12. [buttons_proxy_ setMargin:gfx::Point(12, 11)]; } if (title_bar_style_ == TitleBarStyle::kCustomButtonsOnHover) { [buttons_proxy_ setShowOnHover:YES]; } else { // customButtonsOnHover does not show buttons initially. InternalSetWindowButtonVisibility(true); } } } // Create a tab only if tabbing identifier is specified and window has // a native title bar. if (tabbingIdentifier.empty() || transparent() || !has_frame()) { [window_ setTabbingMode:NSWindowTabbingModeDisallowed]; } else { [window_ setTabbingIdentifier:base::SysUTF8ToNSString(tabbingIdentifier)]; } // Resize to content bounds. bool use_content_size = false; options.Get(options::kUseContentSize, &use_content_size); if (!has_frame() || use_content_size) SetContentSize(gfx::Size(width, height)); // Enable the NSView to accept first mouse event. bool acceptsFirstMouse = false; options.Get(options::kAcceptFirstMouse, &acceptsFirstMouse); [window_ setAcceptsFirstMouse:acceptsFirstMouse]; // Disable auto-hiding cursor. bool disableAutoHideCursor = false; options.Get(options::kDisableAutoHideCursor, &disableAutoHideCursor); [window_ setDisableAutoHideCursor:disableAutoHideCursor]; SetHiddenInMissionControl(hiddenInMissionControl); // Set maximizable state last to ensure zoom button does not get reset // by calls to other APIs. SetMaximizable(maximizable); // Default content view. SetContentView(new views::View()); AddContentViewLayers(); UpdateWindowOriginalFrame(); original_level_ = [window_ level]; } NativeWindowMac::~NativeWindowMac() = default; void NativeWindowMac::SetContentView(views::View* view) { views::View* root_view = GetContentsView(); if (content_view()) root_view->RemoveChildView(content_view()); set_content_view(view); root_view->AddChildView(content_view()); root_view->Layout(); } void NativeWindowMac::Close() { if (!IsClosable()) { WindowList::WindowCloseCancelled(this); return; } if (fullscreen_transition_state() != FullScreenTransitionState::kNone) { SetHasDeferredWindowClose(true); return; } // Ensure we're detached from the parent window before closing. RemoveChildFromParentWindow(); while (!child_windows_.empty()) { auto* child = child_windows_.back(); child->RemoveChildFromParentWindow(); } // If a sheet is attached to the window when we call // [window_ performClose:nil], the window won't close properly // even after the user has ended the sheet. // Ensure it's closed before calling [window_ performClose:nil]. if ([window_ attachedSheet]) [window_ endSheet:[window_ attachedSheet]]; [window_ performClose:nil]; // Closing a sheet doesn't trigger windowShouldClose, // so we need to manually call it ourselves here. if (is_modal() && parent() && IsVisible()) { NotifyWindowCloseButtonClicked(); } } void NativeWindowMac::CloseImmediately() { // Ensure we're detached from the parent window before closing. RemoveChildFromParentWindow(); while (!child_windows_.empty()) { auto* child = child_windows_.back(); child->RemoveChildFromParentWindow(); } [window_ close]; } void NativeWindowMac::Focus(bool focus) { if (!IsVisible()) return; if (focus) { [[NSApplication sharedApplication] activateIgnoringOtherApps:NO]; [window_ makeKeyAndOrderFront:nil]; } else { [window_ orderOut:nil]; [window_ orderBack:nil]; } } bool NativeWindowMac::IsFocused() { return [window_ isKeyWindow]; } void NativeWindowMac::Show() { if (is_modal() && parent()) { NSWindow* window = parent()->GetNativeWindow().GetNativeNSWindow(); if ([window_ sheetParent] == nil) [window beginSheet:window_ completionHandler:^(NSModalResponse){ }]; return; } // Reattach the window to the parent to actually show it. if (parent()) InternalSetParentWindow(parent(), true); // This method is supposed to put focus on window, however if the app does not // have focus then "makeKeyAndOrderFront" will only show the window. [NSApp activateIgnoringOtherApps:YES]; [window_ makeKeyAndOrderFront:nil]; } void NativeWindowMac::ShowInactive() { // Reattach the window to the parent to actually show it. if (parent()) InternalSetParentWindow(parent(), true); [window_ orderFrontRegardless]; } void NativeWindowMac::Hide() { // If a sheet is attached to the window when we call [window_ orderOut:nil], // the sheet won't be able to show again on the same window. // Ensure it's closed before calling [window_ orderOut:nil]. if ([window_ attachedSheet]) [window_ endSheet:[window_ attachedSheet]]; if (is_modal() && parent()) { [window_ orderOut:nil]; [parent()->GetNativeWindow().GetNativeNSWindow() endSheet:window_]; return; } DetachChildren(); // Detach the window from the parent before. if (parent()) InternalSetParentWindow(parent(), false); [window_ orderOut:nil]; } bool NativeWindowMac::IsVisible() { bool occluded = [window_ occlusionState] == NSWindowOcclusionStateVisible; return [window_ isVisible] && !occluded && !IsMinimized(); } bool NativeWindowMac::IsEnabled() { return [window_ attachedSheet] == nil; } void NativeWindowMac::SetEnabled(bool enable) { if (!enable) { NSRect frame = [window_ frame]; NSWindow* window = [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, frame.size.width, frame.size.height) styleMask:NSWindowStyleMaskTitled backing:NSBackingStoreBuffered defer:NO]; [window setAlphaValue:0.5]; [window_ beginSheet:window completionHandler:^(NSModalResponse returnCode) { NSLog(@"main window disabled"); return; }]; } else if ([window_ attachedSheet]) { [window_ endSheet:[window_ attachedSheet]]; } } void NativeWindowMac::Maximize() { const bool is_visible = [window_ isVisible]; if (IsMaximized()) { if (!is_visible) ShowInactive(); return; } // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); [window_ zoom:nil]; if (!is_visible) { ShowInactive(); NotifyWindowMaximize(); } } void NativeWindowMac::Unmaximize() { // Bail if the last user set bounds were the same size as the window // screen (e.g. the user set the window to maximized via setBounds) // // Per docs during zoom: // > If there’s no saved user state because there has been no previous // > zoom,the size and location of the window don’t change. // // However, in classic Apple fashion, this is not the case in practice, // and the frame inexplicably becomes very tiny. We should prevent // zoom from being called if the window is being unmaximized and its // unmaximized window bounds are themselves functionally maximized. if (!IsMaximized() || user_set_bounds_maximized_) return; [window_ zoom:nil]; } bool NativeWindowMac::IsMaximized() { // It's possible for [window_ isZoomed] to be true // when the window is minimized or fullscreened. if (IsMinimized() || IsFullscreen()) return false; if (HasStyleMask(NSWindowStyleMaskResizable) != 0) return [window_ isZoomed]; NSRect rectScreen = GetAspectRatio() > 0.0 ? default_frame_for_zoom() : [[NSScreen mainScreen] visibleFrame]; return NSEqualRects([window_ frame], rectScreen); } void NativeWindowMac::Minimize() { if (IsMinimized()) return; // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); [window_ miniaturize:nil]; } void NativeWindowMac::Restore() { [window_ deminiaturize:nil]; } bool NativeWindowMac::IsMinimized() { return [window_ isMiniaturized]; } bool NativeWindowMac::HandleDeferredClose() { if (has_deferred_window_close_) { SetHasDeferredWindowClose(false); Close(); return true; } return false; } void NativeWindowMac::RemoveChildWindow(NativeWindow* child) { child_windows_.remove_if([&child](NativeWindow* w) { return (w == child); }); [window_ removeChildWindow:child->GetNativeWindow().GetNativeNSWindow()]; } void NativeWindowMac::RemoveChildFromParentWindow() { if (parent() && !is_modal()) { parent()->RemoveChildWindow(this); NativeWindow::SetParentWindow(nullptr); } } void NativeWindowMac::AttachChildren() { for (auto* child : child_windows_) { auto* child_nswindow = child->GetNativeWindow().GetNativeNSWindow(); if ([child_nswindow parentWindow] == window_) continue; // Attaching a window as a child window resets its window level, so // save and restore it afterwards. NSInteger level = window_.level; [window_ addChildWindow:child_nswindow ordered:NSWindowAbove]; [window_ setLevel:level]; } } void NativeWindowMac::DetachChildren() { DCHECK(child_windows_.size() == [[window_ childWindows] count]); // Hide all children before hiding/minimizing the window. // NativeWidgetNSWindowBridge::NotifyVisibilityChangeDown() // will DCHECK otherwise. for (auto* child : child_windows_) { [child->GetNativeWindow().GetNativeNSWindow() orderOut:nil]; } } void NativeWindowMac::SetFullScreen(bool fullscreen) { // [NSWindow -toggleFullScreen] is an asynchronous operation, which means // that it's possible to call it while a fullscreen transition is currently // in process. This can create weird behavior (incl. phantom windows), // so we want to schedule a transition for when the current one has completed. if (fullscreen_transition_state() != FullScreenTransitionState::kNone) { if (!pending_transitions_.empty()) { bool last_pending = pending_transitions_.back(); // Only push new transitions if they're different than the last transition // in the queue. if (last_pending != fullscreen) pending_transitions_.push(fullscreen); } else { pending_transitions_.push(fullscreen); } return; } if (fullscreen == IsFullscreen() || !IsFullScreenable()) return; // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); // This needs to be set here because it can be the case that // SetFullScreen is called by a user before windowWillEnterFullScreen // or windowWillExitFullScreen are invoked, and so a potential transition // could be dropped. fullscreen_transition_state_ = fullscreen ? FullScreenTransitionState::kEntering : FullScreenTransitionState::kExiting; if (![window_ toggleFullScreenMode:nil]) fullscreen_transition_state_ = FullScreenTransitionState::kNone; } bool NativeWindowMac::IsFullscreen() const { return HasStyleMask(NSWindowStyleMaskFullScreen); } void NativeWindowMac::SetBounds(const gfx::Rect& bounds, bool animate) { // Do nothing if in fullscreen mode. if (IsFullscreen()) return; // Check size constraints since setFrame does not check it. gfx::Size size = bounds.size(); size.SetToMax(GetMinimumSize()); gfx::Size max_size = GetMaximumSize(); if (!max_size.IsEmpty()) size.SetToMin(max_size); NSRect cocoa_bounds = NSMakeRect(bounds.x(), 0, size.width(), size.height()); // Flip coordinates based on the primary screen. NSScreen* screen = [[NSScreen screens] firstObject]; cocoa_bounds.origin.y = NSHeight([screen frame]) - size.height() - bounds.y(); [window_ setFrame:cocoa_bounds display:YES animate:animate]; user_set_bounds_maximized_ = IsMaximized() ? true : false; UpdateWindowOriginalFrame(); } gfx::Rect NativeWindowMac::GetBounds() { NSRect frame = [window_ frame]; gfx::Rect bounds(frame.origin.x, 0, NSWidth(frame), NSHeight(frame)); NSScreen* screen = [[NSScreen screens] firstObject]; bounds.set_y(NSHeight([screen frame]) - NSMaxY(frame)); return bounds; } bool NativeWindowMac::IsNormal() { return NativeWindow::IsNormal() && !IsSimpleFullScreen(); } gfx::Rect NativeWindowMac::GetNormalBounds() { if (IsNormal()) { return GetBounds(); } NSRect frame = original_frame_; gfx::Rect bounds(frame.origin.x, 0, NSWidth(frame), NSHeight(frame)); NSScreen* screen = [[NSScreen screens] firstObject]; bounds.set_y(NSHeight([screen frame]) - NSMaxY(frame)); return bounds; // Works on OS_WIN ! // return widget()->GetRestoredBounds(); } void NativeWindowMac::SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints) { auto convertSize = [this](const gfx::Size& size) { // Our frameless window still has titlebar attached, so setting contentSize // will result in actual content size being larger. if (!has_frame()) { NSRect frame = NSMakeRect(0, 0, size.width(), size.height()); NSRect content = [window_ originalContentRectForFrameRect:frame]; return content.size; } else { return NSMakeSize(size.width(), size.height()); } }; NSView* content = [window_ contentView]; if (size_constraints.HasMinimumSize()) { NSSize min_size = convertSize(size_constraints.GetMinimumSize()); [window_ setContentMinSize:[content convertSize:min_size toView:nil]]; } if (size_constraints.HasMaximumSize()) { NSSize max_size = convertSize(size_constraints.GetMaximumSize()); [window_ setContentMaxSize:[content convertSize:max_size toView:nil]]; } NativeWindow::SetContentSizeConstraints(size_constraints); } bool NativeWindowMac::MoveAbove(const std::string& sourceId) { const content::DesktopMediaID id = content::DesktopMediaID::Parse(sourceId); if (id.type != content::DesktopMediaID::TYPE_WINDOW) return false; // Check if the window source is valid. const CGWindowID window_id = id.id; if (!webrtc::GetWindowOwnerPid(window_id)) return false; if (!parent() || is_modal()) { [window_ orderWindow:NSWindowAbove relativeTo:window_id]; } else { NSWindow* other_window = [NSApp windowWithWindowNumber:window_id]; ReorderChildWindowAbove(window_, other_window); } return true; } void NativeWindowMac::MoveTop() { if (!parent() || is_modal()) { [window_ orderWindow:NSWindowAbove relativeTo:0]; } else { ReorderChildWindowAbove(window_, nullptr); } } void NativeWindowMac::SetResizable(bool resizable) { ScopedDisableResize disable_resize; SetStyleMask(resizable, NSWindowStyleMaskResizable); bool was_fullscreenable = IsFullScreenable(); // Right now, resizable and fullscreenable are decoupled in // documentation and on Windows/Linux. Chromium disables // fullscreen collection behavior as well as the maximize traffic // light in SetCanResize if resizability is false on macOS unless // the window is both resizable and maximizable. We want consistent // cross-platform behavior, so if resizability is disabled we disable // the maximize button and ensure fullscreenability matches user setting. SetCanResize(resizable); SetFullScreenable(was_fullscreenable); [[window_ standardWindowButton:NSWindowZoomButton] setEnabled:resizable ? was_fullscreenable : false]; } bool NativeWindowMac::IsResizable() { bool in_fs_transition = fullscreen_transition_state() != FullScreenTransitionState::kNone; bool has_rs_mask = HasStyleMask(NSWindowStyleMaskResizable); return has_rs_mask && !IsFullscreen() && !in_fs_transition; } void NativeWindowMac::SetMovable(bool movable) { [window_ setMovable:movable]; } bool NativeWindowMac::IsMovable() { return [window_ isMovable]; } void NativeWindowMac::SetMinimizable(bool minimizable) { SetStyleMask(minimizable, NSWindowStyleMaskMiniaturizable); } bool NativeWindowMac::IsMinimizable() { return HasStyleMask(NSWindowStyleMaskMiniaturizable); } void NativeWindowMac::SetMaximizable(bool maximizable) { maximizable_ = maximizable; [[window_ standardWindowButton:NSWindowZoomButton] setEnabled:maximizable]; } bool NativeWindowMac::IsMaximizable() { return [[window_ standardWindowButton:NSWindowZoomButton] isEnabled]; } void NativeWindowMac::SetFullScreenable(bool fullscreenable) { SetCollectionBehavior(fullscreenable, NSWindowCollectionBehaviorFullScreenPrimary); // On EL Capitan this flag is required to hide fullscreen button. SetCollectionBehavior(!fullscreenable, NSWindowCollectionBehaviorFullScreenAuxiliary); } bool NativeWindowMac::IsFullScreenable() { NSUInteger collectionBehavior = [window_ collectionBehavior]; return collectionBehavior & NSWindowCollectionBehaviorFullScreenPrimary; } void NativeWindowMac::SetClosable(bool closable) { SetStyleMask(closable, NSWindowStyleMaskClosable); } bool NativeWindowMac::IsClosable() { return HasStyleMask(NSWindowStyleMaskClosable); } void NativeWindowMac::SetAlwaysOnTop(ui::ZOrderLevel z_order, const std::string& level_name, int relative_level) { if (z_order == ui::ZOrderLevel::kNormal) { SetWindowLevel(NSNormalWindowLevel); return; } int level = NSNormalWindowLevel; if (level_name == "floating") { level = NSFloatingWindowLevel; } else if (level_name == "torn-off-menu") { level = NSTornOffMenuWindowLevel; } else if (level_name == "modal-panel") { level = NSModalPanelWindowLevel; } else if (level_name == "main-menu") { level = NSMainMenuWindowLevel; } else if (level_name == "status") { level = NSStatusWindowLevel; } else if (level_name == "pop-up-menu") { level = NSPopUpMenuWindowLevel; } else if (level_name == "screen-saver") { level = NSScreenSaverWindowLevel; } SetWindowLevel(level + relative_level); } std::string NativeWindowMac::GetAlwaysOnTopLevel() { std::string level_name = "normal"; int level = [window_ level]; if (level == NSFloatingWindowLevel) { level_name = "floating"; } else if (level == NSTornOffMenuWindowLevel) { level_name = "torn-off-menu"; } else if (level == NSModalPanelWindowLevel) { level_name = "modal-panel"; } else if (level == NSMainMenuWindowLevel) { level_name = "main-menu"; } else if (level == NSStatusWindowLevel) { level_name = "status"; } else if (level == NSPopUpMenuWindowLevel) { level_name = "pop-up-menu"; } else if (level == NSScreenSaverWindowLevel) { level_name = "screen-saver"; } return level_name; } void NativeWindowMac::SetWindowLevel(int unbounded_level) { int level = std::min( std::max(unbounded_level, CGWindowLevelForKey(kCGMinimumWindowLevelKey)), CGWindowLevelForKey(kCGMaximumWindowLevelKey)); ui::ZOrderLevel z_order_level = level == NSNormalWindowLevel ? ui::ZOrderLevel::kNormal : ui::ZOrderLevel::kFloatingWindow; bool did_z_order_level_change = z_order_level != GetZOrderLevel(); was_maximizable_ = IsMaximizable(); // We need to explicitly keep the NativeWidget up to date, since it stores the // window level in a local variable, rather than reading it from the NSWindow. // Unfortunately, it results in a second setLevel call. It's not ideal, but we // don't expect this to cause any user-visible jank. widget()->SetZOrderLevel(z_order_level); [window_ setLevel:level]; // Set level will make the zoom button revert to default, probably // a bug of Cocoa or macOS. SetMaximizable(was_maximizable_); // This must be notified at the very end or IsAlwaysOnTop // will not yet have been updated to reflect the new status if (did_z_order_level_change) NativeWindow::NotifyWindowAlwaysOnTopChanged(); } ui::ZOrderLevel NativeWindowMac::GetZOrderLevel() { return widget()->GetZOrderLevel(); } void NativeWindowMac::Center() { [window_ center]; } void NativeWindowMac::Invalidate() { [[window_ contentView] setNeedsDisplay:YES]; } void NativeWindowMac::SetTitle(const std::string& title) { [window_ setTitle:base::SysUTF8ToNSString(title)]; if (buttons_proxy_) [buttons_proxy_ redraw]; } std::string NativeWindowMac::GetTitle() { return base::SysNSStringToUTF8([window_ title]); } void NativeWindowMac::FlashFrame(bool flash) { if (flash) { attention_request_id_ = [NSApp requestUserAttention:NSInformationalRequest]; } else { [NSApp cancelUserAttentionRequest:attention_request_id_]; attention_request_id_ = 0; } } void NativeWindowMac::SetSkipTaskbar(bool skip) {} bool NativeWindowMac::IsExcludedFromShownWindowsMenu() { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); return [window isExcludedFromWindowsMenu]; } void NativeWindowMac::SetExcludedFromShownWindowsMenu(bool excluded) { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); [window setExcludedFromWindowsMenu:excluded]; } void NativeWindowMac::OnDisplayMetricsChanged(const display::Display& display, uint32_t changed_metrics) { // We only want to force screen recalibration if we're in simpleFullscreen // mode. if (!is_simple_fullscreen_) return; content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&NativeWindow::UpdateFrame, GetWeakPtr())); } void NativeWindowMac::SetSimpleFullScreen(bool simple_fullscreen) { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); if (simple_fullscreen && !is_simple_fullscreen_) { is_simple_fullscreen_ = true; // Take note of the current window size and level if (IsNormal()) { UpdateWindowOriginalFrame(); original_level_ = [window_ level]; } simple_fullscreen_options_ = [NSApp currentSystemPresentationOptions]; simple_fullscreen_mask_ = [window styleMask]; // We can simulate the pre-Lion fullscreen by auto-hiding the dock and menu // bar NSApplicationPresentationOptions options = NSApplicationPresentationAutoHideDock | NSApplicationPresentationAutoHideMenuBar; [NSApp setPresentationOptions:options]; was_maximizable_ = IsMaximizable(); was_movable_ = IsMovable(); NSRect fullscreenFrame = [window.screen frame]; // If our app has dock hidden, set the window level higher so another app's // menu bar doesn't appear on top of our fullscreen app. if ([[NSRunningApplication currentApplication] activationPolicy] != NSApplicationActivationPolicyRegular) { window.level = NSPopUpMenuWindowLevel; } // Always hide the titlebar in simple fullscreen mode. // // Note that we must remove the NSWindowStyleMaskTitled style instead of // using the [window_ setTitleVisibility:], as the latter would leave the // window with rounded corners. SetStyleMask(false, NSWindowStyleMaskTitled); if (!window_button_visibility_.has_value()) { // Lets keep previous behaviour - hide window controls in titled // fullscreen mode when not specified otherwise. InternalSetWindowButtonVisibility(false); } [window setFrame:fullscreenFrame display:YES animate:YES]; // Fullscreen windows can't be resized, minimized, maximized, or moved SetMinimizable(false); SetResizable(false); SetMaximizable(false); SetMovable(false); } else if (!simple_fullscreen && is_simple_fullscreen_) { is_simple_fullscreen_ = false; [window setFrame:original_frame_ display:YES animate:YES]; window.level = original_level_; [NSApp setPresentationOptions:simple_fullscreen_options_]; // Restore original style mask ScopedDisableResize disable_resize; [window_ setStyleMask:simple_fullscreen_mask_]; // Restore window manipulation abilities SetMaximizable(was_maximizable_); SetMovable(was_movable_); // Restore default window controls visibility state. if (!window_button_visibility_.has_value()) { bool visibility; if (has_frame()) visibility = true; else visibility = title_bar_style_ != TitleBarStyle::kNormal; InternalSetWindowButtonVisibility(visibility); } if (buttons_proxy_) [buttons_proxy_ redraw]; } } bool NativeWindowMac::IsSimpleFullScreen() { return is_simple_fullscreen_; } void NativeWindowMac::SetKiosk(bool kiosk) { if (kiosk && !is_kiosk_) { kiosk_options_ = [NSApp currentSystemPresentationOptions]; NSApplicationPresentationOptions options = NSApplicationPresentationHideDock | NSApplicationPresentationHideMenuBar | NSApplicationPresentationDisableAppleMenu | NSApplicationPresentationDisableProcessSwitching | NSApplicationPresentationDisableForceQuit | NSApplicationPresentationDisableSessionTermination | NSApplicationPresentationDisableHideApplication; [NSApp setPresentationOptions:options]; is_kiosk_ = true; fullscreen_before_kiosk_ = IsFullscreen(); if (!fullscreen_before_kiosk_) SetFullScreen(true); } else if (!kiosk && is_kiosk_) { is_kiosk_ = false; if (!fullscreen_before_kiosk_) SetFullScreen(false); // Set presentation options *after* asynchronously exiting // fullscreen to ensure they take effect. [NSApp setPresentationOptions:kiosk_options_]; } } bool NativeWindowMac::IsKiosk() { return is_kiosk_; } void NativeWindowMac::SetBackgroundColor(SkColor color) { base::apple::ScopedCFTypeRef<CGColorRef> cgcolor( skia::CGColorCreateFromSkColor(color)); [[[window_ contentView] layer] setBackgroundColor:cgcolor]; } SkColor NativeWindowMac::GetBackgroundColor() { CGColorRef color = [[[window_ contentView] layer] backgroundColor]; if (!color) return SK_ColorTRANSPARENT; return skia::CGColorRefToSkColor(color); } void NativeWindowMac::SetHasShadow(bool has_shadow) { [window_ setHasShadow:has_shadow]; } bool NativeWindowMac::HasShadow() { return [window_ hasShadow]; } void NativeWindowMac::InvalidateShadow() { [window_ invalidateShadow]; } void NativeWindowMac::SetOpacity(const double opacity) { const double boundedOpacity = std::clamp(opacity, 0.0, 1.0); [window_ setAlphaValue:boundedOpacity]; } double NativeWindowMac::GetOpacity() { return [window_ alphaValue]; } void NativeWindowMac::SetRepresentedFilename(const std::string& filename) { [window_ setRepresentedFilename:base::SysUTF8ToNSString(filename)]; if (buttons_proxy_) [buttons_proxy_ redraw]; } std::string NativeWindowMac::GetRepresentedFilename() { return base::SysNSStringToUTF8([window_ representedFilename]); } void NativeWindowMac::SetDocumentEdited(bool edited) { [window_ setDocumentEdited:edited]; if (buttons_proxy_) [buttons_proxy_ redraw]; } bool NativeWindowMac::IsDocumentEdited() { return [window_ isDocumentEdited]; } bool NativeWindowMac::IsHiddenInMissionControl() { NSUInteger collectionBehavior = [window_ collectionBehavior]; return collectionBehavior & NSWindowCollectionBehaviorTransient; } void NativeWindowMac::SetHiddenInMissionControl(bool hidden) { SetCollectionBehavior(hidden, NSWindowCollectionBehaviorTransient); } void NativeWindowMac::SetIgnoreMouseEvents(bool ignore, bool forward) { [window_ setIgnoresMouseEvents:ignore]; if (!ignore) { SetForwardMouseMessages(NO); } else { SetForwardMouseMessages(forward); } } void NativeWindowMac::SetContentProtection(bool enable) { [window_ setSharingType:enable ? NSWindowSharingNone : NSWindowSharingReadOnly]; } void NativeWindowMac::SetFocusable(bool focusable) { // No known way to unfocus the window if it had the focus. Here we do not // want to call Focus(false) because it moves the window to the back, i.e. // at the bottom in term of z-order. [window_ setDisableKeyOrMainWindow:!focusable]; } bool NativeWindowMac::IsFocusable() { return ![window_ disableKeyOrMainWindow]; } void NativeWindowMac::AddBrowserView(NativeBrowserView* view) { [CATransaction begin]; [CATransaction setDisableActions:YES]; if (!view) { [CATransaction commit]; return; } add_browser_view(view); if (view->GetInspectableWebContentsView()) { auto* native_view = view->GetInspectableWebContentsView() ->GetNativeView() .GetNativeNSView(); [[window_ contentView] addSubview:native_view positioned:NSWindowAbove relativeTo:nil]; native_view.hidden = NO; } [CATransaction commit]; } void NativeWindowMac::RemoveBrowserView(NativeBrowserView* view) { [CATransaction begin]; [CATransaction setDisableActions:YES]; if (!view) { [CATransaction commit]; return; } if (view->GetInspectableWebContentsView()) [view->GetInspectableWebContentsView()->GetNativeView().GetNativeNSView() removeFromSuperview]; remove_browser_view(view); [CATransaction commit]; } void NativeWindowMac::SetTopBrowserView(NativeBrowserView* view) { [CATransaction begin]; [CATransaction setDisableActions:YES]; if (!view) { [CATransaction commit]; return; } remove_browser_view(view); add_browser_view(view); if (view->GetInspectableWebContentsView()) { auto* native_view = view->GetInspectableWebContentsView() ->GetNativeView() .GetNativeNSView(); [[window_ contentView] addSubview:native_view positioned:NSWindowAbove relativeTo:nil]; native_view.hidden = NO; } [CATransaction commit]; } void NativeWindowMac::SetParentWindow(NativeWindow* parent) { InternalSetParentWindow(parent, IsVisible()); } gfx::NativeView NativeWindowMac::GetNativeView() const { return [window_ contentView]; } gfx::NativeWindow NativeWindowMac::GetNativeWindow() const { return window_; } gfx::AcceleratedWidget NativeWindowMac::GetAcceleratedWidget() const { return [window_ windowNumber]; } content::DesktopMediaID NativeWindowMac::GetDesktopMediaID() const { auto desktop_media_id = content::DesktopMediaID( content::DesktopMediaID::TYPE_WINDOW, GetAcceleratedWidget()); // c.f. // https://source.chromium.org/chromium/chromium/src/+/main:chrome/browser/media/webrtc/native_desktop_media_list.cc;l=775-780;drc=79502ab47f61bff351426f57f576daef02b1a8dc // Refs https://github.com/electron/electron/pull/30507 // TODO(deepak1556): Match upstream for `kWindowCaptureMacV2` #if 0 if (remote_cocoa::ScopedCGWindowID::Get(desktop_media_id.id)) { desktop_media_id.window_id = desktop_media_id.id; } #endif return desktop_media_id; } NativeWindowHandle NativeWindowMac::GetNativeWindowHandle() const { return [window_ contentView]; } void NativeWindowMac::SetProgressBar(double progress, const NativeWindow::ProgressState state) { NSDockTile* dock_tile = [NSApp dockTile]; // Sometimes macOS would install a default contentView for dock, we must // verify whether NSProgressIndicator has been installed. bool first_time = !dock_tile.contentView || [[dock_tile.contentView subviews] count] == 0 || ![[[dock_tile.contentView subviews] lastObject] isKindOfClass:[NSProgressIndicator class]]; // For the first time API invoked, we need to create a ContentView in // DockTile. if (first_time) { NSImageView* image_view = [[NSImageView alloc] init]; [image_view setImage:[NSApp applicationIconImage]]; [dock_tile setContentView:image_view]; NSRect frame = NSMakeRect(0.0f, 0.0f, dock_tile.size.width, 15.0); NSProgressIndicator* progress_indicator = [[ElectronProgressBar alloc] initWithFrame:frame]; [progress_indicator setStyle:NSProgressIndicatorStyleBar]; [progress_indicator setIndeterminate:NO]; [progress_indicator setBezeled:YES]; [progress_indicator setMinValue:0]; [progress_indicator setMaxValue:1]; [progress_indicator setHidden:NO]; [dock_tile.contentView addSubview:progress_indicator]; } NSProgressIndicator* progress_indicator = static_cast<NSProgressIndicator*>( [[[dock_tile contentView] subviews] lastObject]); if (progress < 0) { [progress_indicator setHidden:YES]; } else if (progress > 1) { [progress_indicator setHidden:NO]; [progress_indicator setIndeterminate:YES]; [progress_indicator setDoubleValue:1]; } else { [progress_indicator setHidden:NO]; [progress_indicator setDoubleValue:progress]; } [dock_tile display]; } void NativeWindowMac::SetOverlayIcon(const gfx::Image& overlay, const std::string& description) {} void NativeWindowMac::SetVisibleOnAllWorkspaces(bool visible, bool visibleOnFullScreen, bool skipTransformProcessType) { // In order for NSWindows to be visible on fullscreen we need to invoke // app.dock.hide() since Apple changed the underlying functionality of // NSWindows starting with 10.14 to disallow NSWindows from floating on top of // fullscreen apps. if (!skipTransformProcessType) { if (visibleOnFullScreen) { Browser::Get()->DockHide(); } else { Browser::Get()->DockShow(JavascriptEnvironment::GetIsolate()); } } SetCollectionBehavior(visible, NSWindowCollectionBehaviorCanJoinAllSpaces); SetCollectionBehavior(visibleOnFullScreen, NSWindowCollectionBehaviorFullScreenAuxiliary); } bool NativeWindowMac::IsVisibleOnAllWorkspaces() { NSUInteger collectionBehavior = [window_ collectionBehavior]; return collectionBehavior & NSWindowCollectionBehaviorCanJoinAllSpaces; } void NativeWindowMac::SetAutoHideCursor(bool auto_hide) { [window_ setDisableAutoHideCursor:!auto_hide]; } void NativeWindowMac::UpdateVibrancyRadii(bool fullscreen) { NSVisualEffectView* vibrantView = [window_ vibrantView]; if (vibrantView != nil && !vibrancy_type_.empty()) { const bool no_rounded_corner = !HasStyleMask(NSWindowStyleMaskTitled); if (!has_frame() && !is_modal() && !no_rounded_corner) { CGFloat radius; if (fullscreen) { radius = 0.0f; } else if (@available(macOS 11.0, *)) { radius = 9.0f; } else { // Smaller corner radius on versions prior to Big Sur. radius = 5.0f; } CGFloat dimension = 2 * radius + 1; NSSize size = NSMakeSize(dimension, dimension); NSImage* maskImage = [NSImage imageWithSize:size flipped:NO drawingHandler:^BOOL(NSRect rect) { NSBezierPath* bezierPath = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [[NSColor blackColor] set]; [bezierPath fill]; return YES; }]; [maskImage setCapInsets:NSEdgeInsetsMake(radius, radius, radius, radius)]; [maskImage setResizingMode:NSImageResizingModeStretch]; [vibrantView setMaskImage:maskImage]; [window_ setCornerMask:maskImage]; } } } void NativeWindowMac::UpdateWindowOriginalFrame() { original_frame_ = [window_ frame]; } void NativeWindowMac::SetVibrancy(const std::string& type) { NSVisualEffectView* vibrantView = [window_ vibrantView]; if (type.empty()) { if (vibrantView == nil) return; [vibrantView removeFromSuperview]; [window_ setVibrantView:nil]; return; } NSVisualEffectMaterial vibrancyType{}; if (type == "titlebar") { vibrancyType = NSVisualEffectMaterialTitlebar; } else if (type == "selection") { vibrancyType = NSVisualEffectMaterialSelection; } else if (type == "menu") { vibrancyType = NSVisualEffectMaterialMenu; } else if (type == "popover") { vibrancyType = NSVisualEffectMaterialPopover; } else if (type == "sidebar") { vibrancyType = NSVisualEffectMaterialSidebar; } else if (type == "header") { vibrancyType = NSVisualEffectMaterialHeaderView; } else if (type == "sheet") { vibrancyType = NSVisualEffectMaterialSheet; } else if (type == "window") { vibrancyType = NSVisualEffectMaterialWindowBackground; } else if (type == "hud") { vibrancyType = NSVisualEffectMaterialHUDWindow; } else if (type == "fullscreen-ui") { vibrancyType = NSVisualEffectMaterialFullScreenUI; } else if (type == "tooltip") { vibrancyType = NSVisualEffectMaterialToolTip; } else if (type == "content") { vibrancyType = NSVisualEffectMaterialContentBackground; } else if (type == "under-window") { vibrancyType = NSVisualEffectMaterialUnderWindowBackground; } else if (type == "under-page") { vibrancyType = NSVisualEffectMaterialUnderPageBackground; } if (vibrancyType) { vibrancy_type_ = type; if (vibrantView == nil) { vibrantView = [[NSVisualEffectView alloc] initWithFrame:[[window_ contentView] bounds]]; [window_ setVibrantView:vibrantView]; [vibrantView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable]; [vibrantView setBlendingMode:NSVisualEffectBlendingModeBehindWindow]; if (visual_effect_state_ == VisualEffectState::kActive) { [vibrantView setState:NSVisualEffectStateActive]; } else if (visual_effect_state_ == VisualEffectState::kInactive) { [vibrantView setState:NSVisualEffectStateInactive]; } else { [vibrantView setState:NSVisualEffectStateFollowsWindowActiveState]; } [[window_ contentView] addSubview:vibrantView positioned:NSWindowBelow relativeTo:nil]; UpdateVibrancyRadii(IsFullscreen()); } [vibrantView setMaterial:vibrancyType]; } } void NativeWindowMac::SetWindowButtonVisibility(bool visible) { window_button_visibility_ = visible; if (buttons_proxy_) { if (visible) [buttons_proxy_ redraw]; [buttons_proxy_ setVisible:visible]; } if (title_bar_style_ != TitleBarStyle::kCustomButtonsOnHover) InternalSetWindowButtonVisibility(visible); NotifyLayoutWindowControlsOverlay(); } bool NativeWindowMac::GetWindowButtonVisibility() const { return ![window_ standardWindowButton:NSWindowZoomButton].hidden || ![window_ standardWindowButton:NSWindowMiniaturizeButton].hidden || ![window_ standardWindowButton:NSWindowCloseButton].hidden; } void NativeWindowMac::SetWindowButtonPosition( absl::optional<gfx::Point> position) { traffic_light_position_ = std::move(position); if (buttons_proxy_) { [buttons_proxy_ setMargin:traffic_light_position_]; NotifyLayoutWindowControlsOverlay(); } } absl::optional<gfx::Point> NativeWindowMac::GetWindowButtonPosition() const { return traffic_light_position_; } void NativeWindowMac::RedrawTrafficLights() { if (buttons_proxy_ && !IsFullscreen()) [buttons_proxy_ redraw]; } // In simpleFullScreen mode, update the frame for new bounds. void NativeWindowMac::UpdateFrame() { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); NSRect fullscreenFrame = [window.screen frame]; [window setFrame:fullscreenFrame display:YES animate:YES]; } void NativeWindowMac::SetTouchBar( std::vector<gin_helper::PersistentDictionary> items) { touch_bar_ = [[ElectronTouchBar alloc] initWithDelegate:window_delegate_ window:this settings:std::move(items)]; [window_ setTouchBar:nil]; } void NativeWindowMac::RefreshTouchBarItem(const std::string& item_id) { if (touch_bar_ && [window_ touchBar]) [touch_bar_ refreshTouchBarItem:[window_ touchBar] id:item_id]; } void NativeWindowMac::SetEscapeTouchBarItem( gin_helper::PersistentDictionary item) { if (touch_bar_ && [window_ touchBar]) [touch_bar_ setEscapeTouchBarItem:std::move(item) forTouchBar:[window_ touchBar]]; } void NativeWindowMac::SelectPreviousTab() { [window_ selectPreviousTab:nil]; } void NativeWindowMac::SelectNextTab() { [window_ selectNextTab:nil]; } void NativeWindowMac::ShowAllTabs() { [window_ toggleTabOverview:nil]; } void NativeWindowMac::MergeAllWindows() { [window_ mergeAllWindows:nil]; } void NativeWindowMac::MoveTabToNewWindow() { [window_ moveTabToNewWindow:nil]; } void NativeWindowMac::ToggleTabBar() { [window_ toggleTabBar:nil]; } bool NativeWindowMac::AddTabbedWindow(NativeWindow* window) { if (window_ == window->GetNativeWindow().GetNativeNSWindow()) { return false; } else { [window_ addTabbedWindow:window->GetNativeWindow().GetNativeNSWindow() ordered:NSWindowAbove]; } return true; } void NativeWindowMac::SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) { NativeWindow::SetAspectRatio(aspect_ratio, extra_size); // Reset the behaviour to default if aspect_ratio is set to 0 or less. if (aspect_ratio > 0.0) { NSSize aspect_ratio_size = NSMakeSize(aspect_ratio, 1.0); if (has_frame()) [window_ setContentAspectRatio:aspect_ratio_size]; else [window_ setAspectRatio:aspect_ratio_size]; } else { [window_ setResizeIncrements:NSMakeSize(1.0, 1.0)]; } } void NativeWindowMac::PreviewFile(const std::string& path, const std::string& display_name) { preview_item_ = [[ElectronPreviewItem alloc] initWithURL:[NSURL fileURLWithPath:base::SysUTF8ToNSString(path)] title:base::SysUTF8ToNSString(display_name)]; [[QLPreviewPanel sharedPreviewPanel] makeKeyAndOrderFront:nil]; } void NativeWindowMac::CloseFilePreview() { if ([QLPreviewPanel sharedPreviewPanelExists]) { [[QLPreviewPanel sharedPreviewPanel] close]; } } gfx::Rect NativeWindowMac::ContentBoundsToWindowBounds( const gfx::Rect& bounds) const { if (has_frame()) { gfx::Rect window_bounds( [window_ frameRectForContentRect:bounds.ToCGRect()]); int frame_height = window_bounds.height() - bounds.height(); window_bounds.set_y(window_bounds.y() - frame_height); return window_bounds; } else { return bounds; } } gfx::Rect NativeWindowMac::WindowBoundsToContentBounds( const gfx::Rect& bounds) const { if (has_frame()) { gfx::Rect content_bounds( [window_ contentRectForFrameRect:bounds.ToCGRect()]); int frame_height = bounds.height() - content_bounds.height(); content_bounds.set_y(content_bounds.y() + frame_height); return content_bounds; } else { return bounds; } } void NativeWindowMac::NotifyWindowEnterFullScreen() { NativeWindow::NotifyWindowEnterFullScreen(); // Restore the window title under fullscreen mode. if (buttons_proxy_) [window_ setTitleVisibility:NSWindowTitleVisible]; if (transparent() || !has_frame()) [window_ setTitlebarAppearsTransparent:NO]; } void NativeWindowMac::NotifyWindowLeaveFullScreen() { NativeWindow::NotifyWindowLeaveFullScreen(); // Restore window buttons. if (buttons_proxy_ && window_button_visibility_.value_or(true)) { [buttons_proxy_ redraw]; [buttons_proxy_ setVisible:YES]; } if (transparent() || !has_frame()) [window_ setTitlebarAppearsTransparent:YES]; } void NativeWindowMac::NotifyWindowWillEnterFullScreen() { UpdateVibrancyRadii(true); } void NativeWindowMac::NotifyWindowWillLeaveFullScreen() { if (buttons_proxy_) { // Hide window title when leaving fullscreen. [window_ setTitleVisibility:NSWindowTitleHidden]; // Hide the container otherwise traffic light buttons jump. [buttons_proxy_ setVisible:NO]; } UpdateVibrancyRadii(false); } void NativeWindowMac::SetActive(bool is_key) { is_active_ = is_key; } bool NativeWindowMac::IsActive() const { return is_active_; } void NativeWindowMac::Cleanup() { DCHECK(!IsClosed()); ui::NativeTheme::GetInstanceForNativeUi()->RemoveObserver(this); display::Screen::GetScreen()->RemoveObserver(this); } class NativeAppWindowFrameViewMac : public views::NativeFrameViewMac { public: NativeAppWindowFrameViewMac(views::Widget* frame, NativeWindowMac* window) : views::NativeFrameViewMac(frame), native_window_(window) {} NativeAppWindowFrameViewMac(const NativeAppWindowFrameViewMac&) = delete; NativeAppWindowFrameViewMac& operator=(const NativeAppWindowFrameViewMac&) = delete; ~NativeAppWindowFrameViewMac() override = default; // NonClientFrameView: int NonClientHitTest(const gfx::Point& point) override { if (!bounds().Contains(point)) return HTNOWHERE; if (GetWidget()->IsFullscreen()) return HTCLIENT; // Check for possible draggable region in the client area for the frameless // window. int contents_hit_test = native_window_->NonClientHitTest(point); if (contents_hit_test != HTNOWHERE) return contents_hit_test; return HTCLIENT; } private: // Weak. raw_ptr<NativeWindowMac> const native_window_; }; std::unique_ptr<views::NonClientFrameView> NativeWindowMac::CreateNonClientFrameView(views::Widget* widget) { return std::make_unique<NativeAppWindowFrameViewMac>(widget, this); } bool NativeWindowMac::HasStyleMask(NSUInteger flag) const { return [window_ styleMask] & flag; } void NativeWindowMac::SetStyleMask(bool on, NSUInteger flag) { // Changing the styleMask of a frameless windows causes it to change size so // we explicitly disable resizing while setting it. ScopedDisableResize disable_resize; if (on) [window_ setStyleMask:[window_ styleMask] | flag]; else [window_ setStyleMask:[window_ styleMask] & (~flag)]; // Change style mask will make the zoom button revert to default, probably // a bug of Cocoa or macOS. SetMaximizable(maximizable_); } void NativeWindowMac::SetCollectionBehavior(bool on, NSUInteger flag) { if (on) [window_ setCollectionBehavior:[window_ collectionBehavior] | flag]; else [window_ setCollectionBehavior:[window_ collectionBehavior] & (~flag)]; // Change collectionBehavior will make the zoom button revert to default, // probably a bug of Cocoa or macOS. SetMaximizable(maximizable_); } views::View* NativeWindowMac::GetContentsView() { return root_view_.get(); } bool NativeWindowMac::CanMaximize() const { return maximizable_; } void NativeWindowMac::OnNativeThemeUpdated(ui::NativeTheme* observed_theme) { content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&NativeWindow::RedrawTrafficLights, GetWeakPtr())); } void NativeWindowMac::AddContentViewLayers() { // Make sure the bottom corner is rounded for non-modal windows: // http://crbug.com/396264. if (!is_modal()) { // For normal window, we need to explicitly set layer for contentView to // make setBackgroundColor work correctly. // There is no need to do so for frameless window, and doing so would make // titleBarStyle stop working. if (has_frame()) { CALayer* background_layer = [[CALayer alloc] init]; [background_layer setAutoresizingMask:kCALayerWidthSizable | kCALayerHeightSizable]; [[window_ contentView] setLayer:background_layer]; } [[window_ contentView] setWantsLayer:YES]; } } void NativeWindowMac::InternalSetWindowButtonVisibility(bool visible) { [[window_ standardWindowButton:NSWindowCloseButton] setHidden:!visible]; [[window_ standardWindowButton:NSWindowMiniaturizeButton] setHidden:!visible]; [[window_ standardWindowButton:NSWindowZoomButton] setHidden:!visible]; } void NativeWindowMac::InternalSetParentWindow(NativeWindow* new_parent, bool attach) { if (is_modal()) return; // Do not remove/add if we are already properly attached. if (attach && new_parent && [window_ parentWindow] == new_parent->GetNativeWindow().GetNativeNSWindow()) return; // Remove current parent window. RemoveChildFromParentWindow(); // Set new parent window. if (new_parent) { new_parent->add_child_window(this); if (attach) new_parent->AttachChildren(); } NativeWindow::SetParentWindow(new_parent); } void NativeWindowMac::SetForwardMouseMessages(bool forward) { [window_ setAcceptsMouseMovedEvents:forward]; } gfx::Rect NativeWindowMac::GetWindowControlsOverlayRect() { if (titlebar_overlay_ && buttons_proxy_ && window_button_visibility_.value_or(true)) { NSRect buttons = [buttons_proxy_ getButtonsContainerBounds]; gfx::Rect overlay; overlay.set_width(GetContentSize().width() - NSWidth(buttons)); if ([buttons_proxy_ useCustomHeight]) { overlay.set_height(titlebar_overlay_height()); } else { overlay.set_height(NSHeight(buttons)); } if (!base::i18n::IsRTL()) overlay.set_x(NSMaxX(buttons)); return overlay; } return gfx::Rect(); } // static NativeWindow* NativeWindow::Create(const gin_helper::Dictionary& options, NativeWindow* parent) { return new NativeWindowMac(options, parent); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
38,532
[Feature Request]: Support full frame transparency with Mica background material
### 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. ### Problem Description The [Mica `backgroundMaterial`](https://github.com/electron/electron/pull/38163) effect does not appear below the WebContents. ### Proposed Solution The `backgroundMaterial` option should behave the same as when setting the `vibrancy` option. | macOS: `vibrancy: 'medium-light'` | Windows: `backgroundMaterial: 'acrylic'` | Windows: `backgroundMaterial: 'acrylic'` + `transparent: true` | | --- | --- | --- | | ![Screenshot 2023-05-31 at 4 30 04 PM](https://github.com/electron/electron/assets/1656324/3f2a47e7-ed33-4f88-ae0d-2f67b1cb9b1d) | ![image (5)](https://github.com/electron/electron/assets/1656324/cb4c3a2e-284f-4a54-a968-7870af8be549) | ![image (6)](https://github.com/electron/electron/assets/1656324/318797e0-63ea-49d6-9feb-50cd66db0664) | When `vibrancy` is set, the WebContents is transparent by default. The same should apply to `backgroundMaterial`. Setting `transparent: true` doesn't seem to be a valid workaround, but ideally should still work. The code below needs to be updated: https://github.com/electron/electron/blob/9ffffdb6ef202bd93be496b53fdd4156dd3504ce/shell/browser/api/electron_api_browser_window.cc#L58-L64 ### Alternatives Considered None. ### Additional Information Tested on: ``` Edition Windows 11 Pro Version 22H2 OS build 22621.1778 ``` Fiddle gist: https://gist.github.com/34cf667b21a5075d1f6fbe093d7ad7f9
https://github.com/electron/electron/issues/38532
https://github.com/electron/electron/pull/39708
ab185c058f894ddc556f67b2853de4adad2bb10c
d1827941790f23b241ef3f234a9782750ac97e8d
2023-05-31T20:43:55Z
c++
2023-09-11T12:51:54Z
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 <dwmapi.h> #include <wrl/client.h> #endif #include <memory> #include <utility> #include <vector> #include "base/containers/contains.h" #include "base/memory/raw_ptr.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/ui/inspectable_web_contents.h" #include "shell/browser/ui/views/inspectable_web_contents_view_views.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/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 "shell/common/platform_util.h" #include "ui/views/widget/desktop_aura/desktop_native_widget_aura.h" #include "ui/views/window/native_frame_view.h" #if defined(USE_OZONE) #include "shell/browser/ui/views/global_menu_bar_x11.h" #include "shell/browser/ui/x/event_disabler.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" #include "ui/ozone/public/ozone_platform.h" #endif #elif BUILDFLAG(IS_WIN) #include "base/win/win_util.h" #include "base/win/windows_version.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" #include "ui/gfx/win/msg_util.h" #endif namespace electron { #if BUILDFLAG(IS_WIN) DWM_SYSTEMBACKDROP_TYPE GetBackdropFromString(const std::string& material) { if (material == "none") { return DWMSBT_NONE; } else if (material == "acrylic") { return DWMSBT_TRANSIENTWINDOW; } else if (material == "mica") { return DWMSBT_MAINWINDOW; } else if (material == "tabbed") { return DWMSBT_TABBEDWINDOW; } return DWMSBT_AUTO; } // 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; } // Chromium uses a buggy implementation that converts content rect to window // rect when calculating min/max size, we should use the same implementation // when passing min/max size so we can get correct results. gfx::Size WindowSizeToContentSizeBuggy(HWND hwnd, const gfx::Size& size) { // Calculate the size of window frame, using same code with the // HWNDMessageHandler::OnGetMinMaxInfo method. // The pitfall is, when window is minimized the calculated window frame size // will be different from other states. RECT client_rect, rect; GetClientRect(hwnd, &client_rect); GetWindowRect(hwnd, &rect); CR_DEFLATE_RECT(&rect, &client_rect); // Convert DIP size to pixel size, do calculation and then return DIP size. gfx::Rect screen_rect = DIPToScreenRect(hwnd, gfx::Rect(size)); gfx::Size screen_client_size(screen_rect.width() - (rect.right - rect.left), screen_rect.height() - (rect.bottom - rect.top)); return ScreenToDIPRect(hwnd, gfx::Rect(screen_client_size)).size(); } #endif #if defined(USE_OZONE) bool CreateGlobalMenuBar() { return ui::OzonePlatform::GetInstance() ->GetPlatformProperties() .supports_global_application_menus; } #endif #if defined(USE_OZONE_PLATFORM_X11) bool IsX11() { return ui::OzonePlatform::GetInstance() ->GetPlatformProperties() .electron_can_call_x11; } #endif class NativeWindowClientView : public views::ClientView { public: NativeWindowClientView(views::Widget* widget, views::View* root_view, NativeWindowViews* window) : views::ClientView{widget, root_view}, window_{raw_ref<NativeWindowViews>::from_ptr(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: const raw_ref<NativeWindowViews> window_; }; } // namespace NativeWindowViews::NativeWindowViews(const gin_helper::Dictionary& options, NativeWindow* parent) : NativeWindow(options, parent) { 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); // If the taskbar is re-created after we start up, we have to rebuild all of // our buttons. taskbar_created_message_ = RegisterWindowMessage(TEXT("TaskbarCreated")); #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; // Set Wayland application ID. params.wayland_app_id = platform_util::GetXdgAppId(); 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 BUILDFLAG(IS_LINUX) // 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); } if (parent) SetParentWindow(parent); #endif #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { // 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; // 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_) frame_style |= WS_THICKFRAME; if (minimizable_) frame_style |= WS_MINIMIZEBOX; if (maximizable_) frame_style |= WS_MAXIMIZEBOX; // We should not show a frame for transparent window. if (!thick_frame_) frame_style &= ~(WS_THICKFRAME | 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_OZONE_PLATFORM_X11) if (IsX11()) { 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_OZONE) if (global_menu_bar_) global_menu_bar_->OnWindowMapped(); #endif #if defined(USE_OZONE_PLATFORM_X11) // On X11, setting Z order before showing the window doesn't take effect, // so we have to call it again. if (IsX11()) widget()->SetZOrderLevel(widget()->GetZOrderLevel()); #endif } void NativeWindowViews::ShowInactive() { widget()->ShowInactive(); NotifyWindowShow(); #if defined(USE_OZONE) 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_OZONE) 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() { #if BUILDFLAG(IS_WIN) // widget()->IsVisible() calls ::IsWindowVisible, which returns non-zero if a // window or any of its parent windows are visible. We want to only check the // current window. bool visible = ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_VISIBLE; // WS_VISIBLE is true even if a window is miminized - explicitly check that. return visible && !IsMinimized(); #else return widget()->IsVisible(); #endif } bool NativeWindowViews::IsEnabled() { #if BUILDFLAG(IS_WIN) return ::IsWindowEnabled(GetAcceleratedWidget()); #elif BUILDFLAG(IS_LINUX) #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) 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_OZONE_PLATFORM_X11) if (IsX11()) { 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()); NotifyWindowShow(); } } #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() && !IsMinimized()) { // 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) { menu_bar_visible_before_fullscreen_ = IsMenuBarVisible(); SetMenuBarVisibility(false); } else { SetMenuBarVisibility(!IsMenuBarAutoHide() && menu_bar_visible_before_fullscreen_); menu_bar_visible_before_fullscreen_ = false; } #endif } bool NativeWindowViews::IsFullscreen() const { return widget()->IsFullscreen(); } void NativeWindowViews::SetBounds(const gfx::Rect& bounds, bool animate) { #if BUILDFLAG(IS_WIN) if (is_moving_ || is_resizing_) { pending_bounds_change_ = bounds; } #endif #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() { #if BUILDFLAG(IS_WIN) if (IsMaximized() && transparent()) return restore_bounds_; #endif 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; } #if BUILDFLAG(IS_WIN) // This override does almost the same with its parent, except that it uses // the WindowSizeToContentSizeBuggy method to convert window size to content // size. See the comment of the method for the reason behind this. extensions::SizeConstraints NativeWindowViews::GetContentSizeConstraints() const { if (content_size_constraints_) return *content_size_constraints_; if (!size_constraints_) return extensions::SizeConstraints(); extensions::SizeConstraints constraints; if (size_constraints_->HasMaximumSize()) { constraints.set_maximum_size(WindowSizeToContentSizeBuggy( GetAcceleratedWidget(), size_constraints_->GetMaximumSize())); } if (size_constraints_->HasMinimumSize()) { constraints.set_minimum_size(WindowSizeToContentSizeBuggy( GetAcceleratedWidget(), size_constraints_->GetMinimumSize())); } return constraints; } #endif 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_OZONE_PLATFORM_X11) if (IsX11()) { 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_OZONE_PLATFORM_X11) if (IsX11()) 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); if (IsWindowControlsOverlayEnabled()) { auto* frame_view = static_cast<WinFrameView*>(widget()->non_client_view()->frame_view()); frame_view->caption_button_container()->UpdateButtons(); } #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); if (IsWindowControlsOverlayEnabled()) { auto* frame_view = static_cast<WinFrameView*>(widget()->non_client_view()->frame_view()); frame_view->caption_button_container()->UpdateButtons(); } #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); } if (IsWindowControlsOverlayEnabled()) { auto* frame_view = static_cast<WinFrameView*>(widget()->non_client_view()->frame_view()); frame_view->caption_button_container()->UpdateButtons(); } #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()); } #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 = std::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_OZONE_PLATFORM_X11) if (IsX11()) { 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_OZONE) // 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 (CreateGlobalMenuBar() && 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_OZONE_PLATFORM_X11) if (IsX11()) 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::SetBackgroundMaterial(const std::string& material) { #if BUILDFLAG(IS_WIN) // DWMWA_USE_HOSTBACKDROPBRUSH is only supported on Windows 11 22H2 and up. if (base::win::GetVersion() < base::win::Version::WIN11_22H2) return; DWM_SYSTEMBACKDROP_TYPE backdrop_type = GetBackdropFromString(material); HRESULT result = DwmSetWindowAttribute(GetAcceleratedWidget(), DWMWA_SYSTEMBACKDROP_TYPE, &backdrop_type, sizeof(backdrop_type)); if (FAILED(result)) LOG(WARNING) << "Failed to set background material to " << material; #endif } void NativeWindowViews::SetVisibleOnAllWorkspaces( bool visible, bool visibleOnFullScreen, bool skipTransformProcessType) { widget()->SetVisibleOnAllWorkspaces(visible); } bool NativeWindowViews::IsVisibleOnAllWorkspaces() { #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { // 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 base::Contains(wm_states, sticky_atom); } #endif return false; } 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; } #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 blurred. 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_; } bool NativeWindowViews::ShouldDescendIntoChildForEventHandling( gfx::NativeView child, const gfx::Point& location) { return NonClientHitTest(location) == HTNOWHERE; } views::ClientView* NativeWindowViews::CreateClientView(views::Widget* widget) { return new NativeWindowClientView{widget, GetContentsView(), 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
38,532
[Feature Request]: Support full frame transparency with Mica background material
### 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. ### Problem Description The [Mica `backgroundMaterial`](https://github.com/electron/electron/pull/38163) effect does not appear below the WebContents. ### Proposed Solution The `backgroundMaterial` option should behave the same as when setting the `vibrancy` option. | macOS: `vibrancy: 'medium-light'` | Windows: `backgroundMaterial: 'acrylic'` | Windows: `backgroundMaterial: 'acrylic'` + `transparent: true` | | --- | --- | --- | | ![Screenshot 2023-05-31 at 4 30 04 PM](https://github.com/electron/electron/assets/1656324/3f2a47e7-ed33-4f88-ae0d-2f67b1cb9b1d) | ![image (5)](https://github.com/electron/electron/assets/1656324/cb4c3a2e-284f-4a54-a968-7870af8be549) | ![image (6)](https://github.com/electron/electron/assets/1656324/318797e0-63ea-49d6-9feb-50cd66db0664) | When `vibrancy` is set, the WebContents is transparent by default. The same should apply to `backgroundMaterial`. Setting `transparent: true` doesn't seem to be a valid workaround, but ideally should still work. The code below needs to be updated: https://github.com/electron/electron/blob/9ffffdb6ef202bd93be496b53fdd4156dd3504ce/shell/browser/api/electron_api_browser_window.cc#L58-L64 ### Alternatives Considered None. ### Additional Information Tested on: ``` Edition Windows 11 Pro Version 22H2 OS build 22621.1778 ``` Fiddle gist: https://gist.github.com/34cf667b21a5075d1f6fbe093d7ad7f9
https://github.com/electron/electron/issues/38532
https://github.com/electron/electron/pull/39708
ab185c058f894ddc556f67b2853de4adad2bb10c
d1827941790f23b241ef3f234a9782750ac97e8d
2023-05-31T20:43:55Z
c++
2023-09-11T12:51:54Z
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 enable_reset_aspect_ratio.patch boringssl_build_gn.patch pepper_plugin_support.patch gtk_visibility.patch resource_file_conflict.patch scroll_bounce_flag.patch mas_blink_no_private_api.patch mas_no_private_api.patch mas-cgdisplayusesforcetogray.patch mas_disable_remote_layer.patch mas_disable_remote_accessibility.patch mas_disable_custom_window_frame.patch mas_avoid_usage_of_private_macos_apis.patch mas_use_public_apis_to_determine_if_a_font_is_a_system_font.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 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 allow_in-process_windows_to_have_different_web_prefs.patch refactor_expose_cursor_changes_to_the_webcontentsobserver.patch crash_allow_setting_more_options.patch upload_list_add_loadsync_method.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 export_gin_v8platform_pageallocator_for_usage_outside_of_the_gin.patch fix_export_zlib_symbols.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 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 process_singleton.patch add_ui_scopedcliboardwriter_writeunsaferawdata.patch feat_add_data_parameter_to_processsingleton.patch load_v8_snapshot_in_browser_process.patch fix_adapt_exclusive_access_for_electron_needs.patch fix_aspect_ratio_with_max_size.patch fix_crash_when_saving_edited_pdf_files.patch port_autofill_colors_to_the_color_pipeline.patch build_disable_partition_alloc_on_mac.patch fix_non-client_mouse_tracking_and_message_bubbling_on_windows.patch build_make_libcxx_abi_unstable_false_for_electron.patch introduce_ozoneplatform_electron_can_call_x11_property.patch make_gtk_getlibgtk_public.patch build_disable_print_content_analysis.patch custom_protocols_plzserviceworker.patch feat_filter_out_non-shareable_windows_in_the_current_application_in.patch disable_freezing_flags_after_init_in_node.patch short-circuit_permissions_checks_in_mediastreamdevicescontroller.patch chore_add_electron_deps_to_gitignores.patch chore_allow_chromium_to_handle_synthetic_mouse_events_for_touch.patch add_maximized_parameter_to_linuxui_getwindowframeprovider.patch add_electron_deps_to_license_credits_file.patch fix_crash_loading_non-standard_schemes_in_iframes.patch create_browser_v8_snapshot_file_name_fuse.patch feat_configure_launch_options_for_service_process.patch feat_ensure_mas_builds_of_the_same_application_can_use_safestorage.patch fix_on-screen-keyboard_hides_on_input_blur_in_webview.patch preconnect_manager.patch fix_remove_caption-removing_style_call.patch build_allow_electron_to_use_exec_script.patch build_only_use_the_mas_build_config_in_the_required_components.patch chore_introduce_blocking_api_for_electron.patch chore_patch_out_partition_attribute_dcheck_for_webviews.patch expose_v8initializer_codegenerationcheckcallbackinmainthread.patch chore_patch_out_profile_methods_in_profile_selections_cc.patch add_gin_converter_support_for_arraybufferview.patch chore_defer_usb_service_getdevices_request_until_usb_service_is.patch refactor_expose_hostimportmoduledynamically_and.patch feat_expose_documentloader_setdefersloading_on_webdocumentloader.patch fix_remove_profiles_from_spellcheck_service.patch chore_patch_out_profile_methods_in_chrome_browser_pdf.patch chore_patch_out_profile_methods_in_titlebar_config.patch fix_select_the_first_menu_item_when_opened_via_keyboard.patch fix_return_v8_value_from_localframe_requestexecutescript.patch fix_harden_blink_scriptstate_maybefrom.patch chore_add_buildflag_guard_around_new_include.patch fix_use_delegated_generic_capturer_when_available.patch build_remove_ent_content_analysis_assert.patch fix_move_autopipsettingshelper_behind_branding_buildflag.patch revert_remove_the_allowaggressivethrottlingwithwebsocket_feature.patch
closed
electron/electron
https://github.com/electron/electron
38,532
[Feature Request]: Support full frame transparency with Mica background material
### 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. ### Problem Description The [Mica `backgroundMaterial`](https://github.com/electron/electron/pull/38163) effect does not appear below the WebContents. ### Proposed Solution The `backgroundMaterial` option should behave the same as when setting the `vibrancy` option. | macOS: `vibrancy: 'medium-light'` | Windows: `backgroundMaterial: 'acrylic'` | Windows: `backgroundMaterial: 'acrylic'` + `transparent: true` | | --- | --- | --- | | ![Screenshot 2023-05-31 at 4 30 04 PM](https://github.com/electron/electron/assets/1656324/3f2a47e7-ed33-4f88-ae0d-2f67b1cb9b1d) | ![image (5)](https://github.com/electron/electron/assets/1656324/cb4c3a2e-284f-4a54-a968-7870af8be549) | ![image (6)](https://github.com/electron/electron/assets/1656324/318797e0-63ea-49d6-9feb-50cd66db0664) | When `vibrancy` is set, the WebContents is transparent by default. The same should apply to `backgroundMaterial`. Setting `transparent: true` doesn't seem to be a valid workaround, but ideally should still work. The code below needs to be updated: https://github.com/electron/electron/blob/9ffffdb6ef202bd93be496b53fdd4156dd3504ce/shell/browser/api/electron_api_browser_window.cc#L58-L64 ### Alternatives Considered None. ### Additional Information Tested on: ``` Edition Windows 11 Pro Version 22H2 OS build 22621.1778 ``` Fiddle gist: https://gist.github.com/34cf667b21a5075d1f6fbe093d7ad7f9
https://github.com/electron/electron/issues/38532
https://github.com/electron/electron/pull/39708
ab185c058f894ddc556f67b2853de4adad2bb10c
d1827941790f23b241ef3f234a9782750ac97e8d
2023-05-31T20:43:55Z
c++
2023-09-11T12:51:54Z
patches/chromium/fix_activate_background_material_on_windows.patch
closed
electron/electron
https://github.com/electron/electron
38,532
[Feature Request]: Support full frame transparency with Mica background material
### 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. ### Problem Description The [Mica `backgroundMaterial`](https://github.com/electron/electron/pull/38163) effect does not appear below the WebContents. ### Proposed Solution The `backgroundMaterial` option should behave the same as when setting the `vibrancy` option. | macOS: `vibrancy: 'medium-light'` | Windows: `backgroundMaterial: 'acrylic'` | Windows: `backgroundMaterial: 'acrylic'` + `transparent: true` | | --- | --- | --- | | ![Screenshot 2023-05-31 at 4 30 04 PM](https://github.com/electron/electron/assets/1656324/3f2a47e7-ed33-4f88-ae0d-2f67b1cb9b1d) | ![image (5)](https://github.com/electron/electron/assets/1656324/cb4c3a2e-284f-4a54-a968-7870af8be549) | ![image (6)](https://github.com/electron/electron/assets/1656324/318797e0-63ea-49d6-9feb-50cd66db0664) | When `vibrancy` is set, the WebContents is transparent by default. The same should apply to `backgroundMaterial`. Setting `transparent: true` doesn't seem to be a valid workaround, but ideally should still work. The code below needs to be updated: https://github.com/electron/electron/blob/9ffffdb6ef202bd93be496b53fdd4156dd3504ce/shell/browser/api/electron_api_browser_window.cc#L58-L64 ### Alternatives Considered None. ### Additional Information Tested on: ``` Edition Windows 11 Pro Version 22H2 OS build 22621.1778 ``` Fiddle gist: https://gist.github.com/34cf667b21a5075d1f6fbe093d7ad7f9
https://github.com/electron/electron/issues/38532
https://github.com/electron/electron/pull/39708
ab185c058f894ddc556f67b2853de4adad2bb10c
d1827941790f23b241ef3f234a9782750ac97e8d
2023-05-31T20:43:55Z
c++
2023-09-11T12:51:54Z
shell/browser/api/electron_api_browser_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/api/electron_api_browser_window.h" #include "base/task/single_thread_task_runner.h" #include "content/browser/renderer_host/render_widget_host_impl.h" // nogncheck #include "content/browser/renderer_host/render_widget_host_owner_delegate.h" // nogncheck #include "content/browser/web_contents/web_contents_impl.h" // nogncheck #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/common/color_parser.h" #include "shell/browser/api/electron_api_web_contents_view.h" #include "shell/browser/browser.h" #include "shell/browser/native_browser_view.h" #include "shell/browser/web_contents_preferences.h" #include "shell/browser/window_list.h" #include "shell/common/color_util.h" #include "shell/common/gin_helper/constructor.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/gin_helper/object_template_builder.h" #include "shell/common/node_includes.h" #include "shell/common/options_switches.h" #include "ui/gl/gpu_switching_manager.h" #if defined(TOOLKIT_VIEWS) #include "shell/browser/native_window_views.h" #endif #if BUILDFLAG(IS_WIN) #include "shell/browser/ui/views/win_frame_view.h" #endif namespace electron::api { BrowserWindow::BrowserWindow(gin::Arguments* args, const gin_helper::Dictionary& options) : BaseWindow(args->isolate(), options) { // Use options.webPreferences in WebContents. v8::Isolate* isolate = args->isolate(); auto web_preferences = gin_helper::Dictionary::CreateEmpty(isolate); options.Get(options::kWebPreferences, &web_preferences); bool transparent = false; options.Get(options::kTransparent, &transparent); std::string vibrancy_type; #if BUILDFLAG(IS_MAC) options.Get(options::kVibrancyType, &vibrancy_type); #endif // Copy the backgroundColor to webContents. std::string color; if (options.Get(options::kBackgroundColor, &color)) { web_preferences.SetHidden(options::kBackgroundColor, color); } else if (!vibrancy_type.empty() || transparent) { // If the BrowserWindow is transparent or a vibrancy type has been set, // also propagate transparency to the WebContents unless a separate // backgroundColor has been set. web_preferences.SetHidden(options::kBackgroundColor, ToRGBAHex(SK_ColorTRANSPARENT)); } // Copy the show setting to webContents, but only if we don't want to paint // when initially hidden bool paint_when_initially_hidden = true; options.Get("paintWhenInitiallyHidden", &paint_when_initially_hidden); if (!paint_when_initially_hidden) { bool show = true; options.Get(options::kShow, &show); web_preferences.Set(options::kShow, show); } // Copy the webContents option to webPreferences. v8::Local<v8::Value> value; if (options.Get("webContents", &value)) { web_preferences.SetHidden("webContents", value); } // Creates the WebContentsView. gin::Handle<WebContentsView> web_contents_view = WebContentsView::Create(isolate, web_preferences); DCHECK(web_contents_view.get()); window_->AddDraggableRegionProvider(web_contents_view.get()); // Save a reference of the WebContents. gin::Handle<WebContents> web_contents = web_contents_view->GetWebContents(isolate); web_contents_.Reset(isolate, web_contents.ToV8()); api_web_contents_ = web_contents->GetWeakPtr(); api_web_contents_->AddObserver(this); Observe(api_web_contents_->web_contents()); // Associate with BrowserWindow. web_contents->SetOwnerWindow(window()); InitWithArgs(args); // Install the content view after BaseWindow's JS code is initialized. SetContentView(gin::CreateHandle<View>(isolate, web_contents_view.get())); // Init window after everything has been setup. window()->InitFromOptions(options); } BrowserWindow::~BrowserWindow() { if (api_web_contents_) { // Cleanup the observers if user destroyed this instance directly instead of // gracefully closing content::WebContents. api_web_contents_->RemoveObserver(this); // Destroy the WebContents. OnCloseContents(); api_web_contents_->Destroy(); } } void BrowserWindow::BeforeUnloadDialogCancelled() { WindowList::WindowCloseCancelled(window()); // Cancel unresponsive event when window close is cancelled. window_unresponsive_closure_.Cancel(); } void BrowserWindow::OnRendererUnresponsive(content::RenderProcessHost*) { // Schedule the unresponsive shortly later, since we may receive the // responsive event soon. This could happen after the whole application had // blocked for a while. // Also notice that when closing this event would be ignored because we have // explicitly started a close timeout counter. This is on purpose because we // don't want the unresponsive event to be sent too early when user is closing // the window. ScheduleUnresponsiveEvent(50); } void BrowserWindow::WebContentsDestroyed() { api_web_contents_ = nullptr; CloseImmediately(); } void BrowserWindow::OnCloseContents() { BaseWindow::ResetBrowserViews(); } void BrowserWindow::OnRendererResponsive(content::RenderProcessHost*) { window_unresponsive_closure_.Cancel(); Emit("responsive"); } void BrowserWindow::OnSetContentBounds(const gfx::Rect& rect) { // window.resizeTo(...) // window.moveTo(...) window()->SetBounds(rect, false); } void BrowserWindow::OnActivateContents() { // Hide the auto-hide menu when webContents is focused. #if !BUILDFLAG(IS_MAC) if (IsMenuBarAutoHide() && IsMenuBarVisible()) window()->SetMenuBarVisibility(false); #endif } void BrowserWindow::OnPageTitleUpdated(const std::u16string& title, bool explicit_set) { // Change window title to page title. auto self = GetWeakPtr(); if (!Emit("page-title-updated", title, explicit_set)) { // |this| might be deleted, or marked as destroyed by close(). if (self && !IsDestroyed()) SetTitle(base::UTF16ToUTF8(title)); } } void BrowserWindow::RequestPreferredWidth(int* width) { *width = web_contents()->GetPreferredSize().width(); } void BrowserWindow::OnCloseButtonClicked(bool* prevent_default) { // When user tries to close the window by clicking the close button, we do // not close the window immediately, instead we try to close the web page // first, and when the web page is closed the window will also be closed. *prevent_default = true; // Assume the window is not responding if it doesn't cancel the close and is // not closed in 5s, in this way we can quickly show the unresponsive // dialog when the window is busy executing some script without waiting for // the unresponsive timeout. if (window_unresponsive_closure_.IsCancelled()) ScheduleUnresponsiveEvent(5000); // Already closed by renderer. if (!web_contents() || !api_web_contents_) return; // Required to make beforeunload handler work. api_web_contents_->NotifyUserActivation(); // Trigger beforeunload events for associated BrowserViews. for (NativeBrowserView* view : window_->browser_views()) { auto* iwc = view->GetInspectableWebContents(); if (!iwc) continue; auto* vwc = iwc->GetWebContents(); auto* api_web_contents = api::WebContents::From(vwc); // Required to make beforeunload handler work. if (api_web_contents) api_web_contents->NotifyUserActivation(); if (vwc) { if (vwc->NeedToFireBeforeUnloadOrUnloadEvents()) { vwc->DispatchBeforeUnload(false /* auto_cancel */); } } } if (web_contents()->NeedToFireBeforeUnloadOrUnloadEvents()) { web_contents()->DispatchBeforeUnload(false /* auto_cancel */); } else { web_contents()->Close(); } } void BrowserWindow::OnWindowBlur() { if (api_web_contents_) web_contents()->StoreFocus(); BaseWindow::OnWindowBlur(); } void BrowserWindow::OnWindowFocus() { // focus/blur events might be emitted while closing window. if (api_web_contents_) { web_contents()->RestoreFocus(); #if !BUILDFLAG(IS_MAC) if (!api_web_contents_->IsDevToolsOpened()) web_contents()->Focus(); #endif } BaseWindow::OnWindowFocus(); } void BrowserWindow::OnWindowIsKeyChanged(bool is_key) { #if BUILDFLAG(IS_MAC) auto* rwhv = web_contents()->GetRenderWidgetHostView(); if (rwhv) rwhv->SetActive(is_key); window()->SetActive(is_key); #endif } void BrowserWindow::OnWindowLeaveFullScreen() { #if BUILDFLAG(IS_MAC) if (web_contents()->IsFullscreen()) web_contents()->ExitFullscreen(true); #endif BaseWindow::OnWindowLeaveFullScreen(); } void BrowserWindow::UpdateWindowControlsOverlay( const gfx::Rect& bounding_rect) { web_contents()->UpdateWindowControlsOverlay(bounding_rect); } void BrowserWindow::CloseImmediately() { // Close all child windows before closing current window. v8::HandleScope handle_scope(isolate()); for (v8::Local<v8::Value> value : child_windows_.Values(isolate())) { gin::Handle<BrowserWindow> child; if (gin::ConvertFromV8(isolate(), value, &child) && !child.IsEmpty()) child->window()->CloseImmediately(); } BaseWindow::CloseImmediately(); // Do not sent "unresponsive" event after window is closed. window_unresponsive_closure_.Cancel(); } void BrowserWindow::Focus() { if (api_web_contents_->IsOffScreen()) FocusOnWebView(); else BaseWindow::Focus(); } void BrowserWindow::Blur() { if (api_web_contents_->IsOffScreen()) BlurWebView(); else BaseWindow::Blur(); } void BrowserWindow::SetBackgroundColor(const std::string& color_name) { BaseWindow::SetBackgroundColor(color_name); SkColor color = ParseCSSColor(color_name); web_contents()->SetPageBaseBackgroundColor(color); auto* rwhv = web_contents()->GetRenderWidgetHostView(); if (rwhv) { rwhv->SetBackgroundColor(color); static_cast<content::RenderWidgetHostViewBase*>(rwhv) ->SetContentBackgroundColor(color); } // Also update the web preferences object otherwise the view will be reset on // the next load URL call if (api_web_contents_) { auto* web_preferences = WebContentsPreferences::From(api_web_contents_->web_contents()); if (web_preferences) { web_preferences->SetBackgroundColor(ParseCSSColor(color_name)); } } } void BrowserWindow::SetBrowserView( absl::optional<gin::Handle<BrowserView>> browser_view) { BaseWindow::ResetBrowserViews(); if (browser_view) BaseWindow::AddBrowserView(*browser_view); } void BrowserWindow::FocusOnWebView() { web_contents()->GetRenderViewHost()->GetWidget()->Focus(); } void BrowserWindow::BlurWebView() { web_contents()->GetRenderViewHost()->GetWidget()->Blur(); } bool BrowserWindow::IsWebViewFocused() { auto* host_view = web_contents()->GetRenderViewHost()->GetWidget()->GetView(); return host_view && host_view->HasFocus(); } v8::Local<v8::Value> BrowserWindow::GetWebContents(v8::Isolate* isolate) { if (web_contents_.IsEmpty()) return v8::Null(isolate); return v8::Local<v8::Value>::New(isolate, web_contents_); } #if BUILDFLAG(IS_WIN) void BrowserWindow::SetTitleBarOverlay(const gin_helper::Dictionary& options, gin_helper::Arguments* args) { // Ensure WCO is already enabled on this window if (!window_->titlebar_overlay_enabled()) { args->ThrowError("Titlebar overlay is not enabled"); return; } auto* window = static_cast<NativeWindowViews*>(window_.get()); bool updated = false; // Check and update the button color std::string btn_color; if (options.Get(options::kOverlayButtonColor, &btn_color)) { // Parse the string as a CSS color SkColor color; if (!content::ParseCssColorString(btn_color, &color)) { args->ThrowError("Could not parse color as CSS color"); return; } // Update the view window->set_overlay_button_color(color); updated = true; } // Check and update the symbol color std::string symbol_color; if (options.Get(options::kOverlaySymbolColor, &symbol_color)) { // Parse the string as a CSS color SkColor color; if (!content::ParseCssColorString(symbol_color, &color)) { args->ThrowError("Could not parse symbol color as CSS color"); return; } // Update the view window->set_overlay_symbol_color(color); updated = true; } // Check and update the height int height = 0; if (options.Get(options::kOverlayHeight, &height)) { window->set_titlebar_overlay_height(height); updated = true; } // If anything was updated, invalidate the layout and schedule a paint of the // window's frame view if (updated) { auto* frame_view = static_cast<WinFrameView*>( window->widget()->non_client_view()->frame_view()); frame_view->InvalidateCaptionButtons(); } } #endif void BrowserWindow::ScheduleUnresponsiveEvent(int ms) { if (!window_unresponsive_closure_.IsCancelled()) return; window_unresponsive_closure_.Reset(base::BindRepeating( &BrowserWindow::NotifyWindowUnresponsive, GetWeakPtr())); base::SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask( FROM_HERE, window_unresponsive_closure_.callback(), base::Milliseconds(ms)); } void BrowserWindow::NotifyWindowUnresponsive() { window_unresponsive_closure_.Cancel(); if (!window_->IsClosed() && window_->IsEnabled()) { Emit("unresponsive"); } } void BrowserWindow::OnWindowShow() { web_contents()->WasShown(); BaseWindow::OnWindowShow(); } void BrowserWindow::OnWindowHide() { web_contents()->WasOccluded(); BaseWindow::OnWindowHide(); } // static gin_helper::WrappableBase* BrowserWindow::New(gin_helper::ErrorThrower thrower, gin::Arguments* args) { if (!Browser::Get()->is_ready()) { thrower.ThrowError("Cannot create BrowserWindow before app is ready"); return nullptr; } if (args->Length() > 1) { args->ThrowError(); return nullptr; } gin_helper::Dictionary options; if (!(args->Length() == 1 && args->GetNext(&options))) { options = gin::Dictionary::CreateEmpty(args->isolate()); } return new BrowserWindow(args, options); } // static void BrowserWindow::BuildPrototype(v8::Isolate* isolate, v8::Local<v8::FunctionTemplate> prototype) { prototype->SetClassName(gin::StringToV8(isolate, "BrowserWindow")); gin_helper::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate()) .SetMethod("focusOnWebView", &BrowserWindow::FocusOnWebView) .SetMethod("blurWebView", &BrowserWindow::BlurWebView) .SetMethod("isWebViewFocused", &BrowserWindow::IsWebViewFocused) #if BUILDFLAG(IS_WIN) .SetMethod("setTitleBarOverlay", &BrowserWindow::SetTitleBarOverlay) #endif .SetProperty("webContents", &BrowserWindow::GetWebContents); } // static v8::Local<v8::Value> BrowserWindow::From(v8::Isolate* isolate, NativeWindow* native_window) { auto* existing = TrackableObject::FromWrappedClass(isolate, native_window); if (existing) return existing->GetWrapper(); else return v8::Null(isolate); } } // namespace electron::api namespace { using electron::api::BrowserWindow; 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("BrowserWindow", gin_helper::CreateConstructor<BrowserWindow>( isolate, base::BindRepeating(&BrowserWindow::New))); } } // namespace NODE_LINKED_BINDING_CONTEXT_AWARE(electron_browser_window, Initialize)
closed
electron/electron
https://github.com/electron/electron
38,532
[Feature Request]: Support full frame transparency with Mica background material
### 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. ### Problem Description The [Mica `backgroundMaterial`](https://github.com/electron/electron/pull/38163) effect does not appear below the WebContents. ### Proposed Solution The `backgroundMaterial` option should behave the same as when setting the `vibrancy` option. | macOS: `vibrancy: 'medium-light'` | Windows: `backgroundMaterial: 'acrylic'` | Windows: `backgroundMaterial: 'acrylic'` + `transparent: true` | | --- | --- | --- | | ![Screenshot 2023-05-31 at 4 30 04 PM](https://github.com/electron/electron/assets/1656324/3f2a47e7-ed33-4f88-ae0d-2f67b1cb9b1d) | ![image (5)](https://github.com/electron/electron/assets/1656324/cb4c3a2e-284f-4a54-a968-7870af8be549) | ![image (6)](https://github.com/electron/electron/assets/1656324/318797e0-63ea-49d6-9feb-50cd66db0664) | When `vibrancy` is set, the WebContents is transparent by default. The same should apply to `backgroundMaterial`. Setting `transparent: true` doesn't seem to be a valid workaround, but ideally should still work. The code below needs to be updated: https://github.com/electron/electron/blob/9ffffdb6ef202bd93be496b53fdd4156dd3504ce/shell/browser/api/electron_api_browser_window.cc#L58-L64 ### Alternatives Considered None. ### Additional Information Tested on: ``` Edition Windows 11 Pro Version 22H2 OS build 22621.1778 ``` Fiddle gist: https://gist.github.com/34cf667b21a5075d1f6fbe093d7ad7f9
https://github.com/electron/electron/issues/38532
https://github.com/electron/electron/pull/39708
ab185c058f894ddc556f67b2853de4adad2bb10c
d1827941790f23b241ef3f234a9782750ac97e8d
2023-05-31T20:43:55Z
c++
2023-09-11T12:51:54Z
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/containers/contains.h" #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/ui/drag_util.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 "third_party/skia/include/core/SkRegion.h" #include "ui/base/hit_test.h" #include "ui/views/widget/widget.h" #if !BUILDFLAG(IS_MAC) #include "shell/browser/ui/views/frameless_view.h" #endif #if BUILDFLAG(IS_WIN) #include "ui/base/win/shell.h" #include "ui/display/win/screen_win.h" #endif #if defined(USE_OZONE) #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()) 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_dict = gin::Dictionary::CreateEmpty(options.isolate()); options.Get(options::ktitleBarOverlay, &titlebar_overlay_dict); int height; if (titlebar_overlay_dict.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)); gfx::Size max_size = size_constraints.GetMaximumSize(); int max_width = max_size.width() > 0 ? max_size.width() : INT_MAX; int max_height = max_size.height() > 0 ? max_size.height() : INT_MAX; bool have_max_width = options.Get(options::kMaxWidth, &max_width); if (have_max_width && max_width <= 0) max_width = INT_MAX; bool have_max_height = options.Get(options::kMaxHeight, &max_height); if (have_max_height && max_height <= 0) max_height = INT_MAX; // By default the window has a default maximum size that prevents it // from being resized larger than the screen, so we should only set this // if the user has passed in values. if (have_max_height || have_max_width || !max_size.IsEmpty()) 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 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 } options.Get(options::kFullScreenable, &fullscreenable); SetFullScreenable(fullscreenable); if (fullscreen) SetFullScreen(true); bool resizable; if (options.Get(options::kResizable, &resizable)) { SetResizable(resizable); } 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); } #elif BUILDFLAG(IS_WIN) std::string material; if (options.Get(options::kBackgroundMaterial, &material)) { SetBackgroundMaterial(material); } #endif std::string color; if (options.Get(options::kBackgroundColor, &color)) { SetBackgroundColor(ParseCSSColor(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) { size_constraints_ = window_constraints; content_size_constraints_.reset(); } extensions::SizeConstraints NativeWindow::GetSizeConstraints() const { if (size_constraints_) return *size_constraints_; if (!content_size_constraints_) return extensions::SizeConstraints(); // Convert content size constraints to window size constraints. extensions::SizeConstraints constraints; if (content_size_constraints_->HasMaximumSize()) { gfx::Rect max_bounds = ContentBoundsToWindowBounds( gfx::Rect(content_size_constraints_->GetMaximumSize())); constraints.set_maximum_size(max_bounds.size()); } if (content_size_constraints_->HasMinimumSize()) { gfx::Rect min_bounds = ContentBoundsToWindowBounds( gfx::Rect(content_size_constraints_->GetMinimumSize())); constraints.set_minimum_size(min_bounds.size()); } return constraints; } void NativeWindow::SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints) { content_size_constraints_ = size_constraints; size_constraints_.reset(); } // The return value of GetContentSizeConstraints will be passed to Chromium // to set min/max sizes of window. Note that we are returning content size // instead of window size because that is what Chromium expects, see the // comment of |WidgetSizeIsClientSize| in Chromium's codebase to learn more. extensions::SizeConstraints NativeWindow::GetContentSizeConstraints() const { if (content_size_constraints_) return *content_size_constraints_; if (!size_constraints_) return extensions::SizeConstraints(); // Convert window size constraints to content size constraints. // Note that we are not caching the results, because Chromium reccalculates // window frame size everytime when min/max sizes are passed, and we must // do the same otherwise the resulting size with frame included will be wrong. extensions::SizeConstraints constraints; if (size_constraints_->HasMaximumSize()) { gfx::Rect max_bounds = WindowBoundsToContentBounds( gfx::Rect(size_constraints_->GetMaximumSize())); constraints.set_maximum_size(max_bounds.size()); } if (size_constraints_->HasMinimumSize()) { gfx::Rect min_bounds = WindowBoundsToContentBounds( gfx::Rect(size_constraints_->GetMinimumSize())); constraints.set_minimum_size(min_bounds.size()); } return constraints; } void NativeWindow::SetMinimumSize(const gfx::Size& size) { extensions::SizeConstraints size_constraints = GetSizeConstraints(); 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 = GetSizeConstraints(); 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::InvalidateShadow() {} void NativeWindow::SetAutoHideCursor(bool auto_hide) {} void NativeWindow::SelectPreviousTab() {} void NativeWindow::SelectNextTab() {} void NativeWindow::ShowAllTabs() {} 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::SetBackgroundMaterial(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::NotifyWindowRequestPreferredWidth(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::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, base::Value::Dict 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 int NativeWindow::NonClientHitTest(const gfx::Point& point) { #if !BUILDFLAG(IS_MAC) // We need to ensure we account for resizing borders on Windows and Linux. if ((!has_frame() || has_client_frame()) && IsResizable()) { auto* frame = static_cast<FramelessView*>(widget()->non_client_view()->frame_view()); int border_hit = frame->ResizingBorderHitTest(point); if (border_hit != HTNOWHERE) return border_hit; } #endif for (auto* provider : draggable_region_providers_) { int hit = provider->NonClientHitTest(point); if (hit != HTNOWHERE) return hit; } return HTNOWHERE; } void NativeWindow::AddDraggableRegionProvider( DraggableRegionProvider* provider) { if (!base::Contains(draggable_region_providers_, provider)) { draggable_region_providers_.push_back(provider); } } void NativeWindow::RemoveDraggableRegionProvider( DraggableRegionProvider* provider) { draggable_region_providers_.remove_if( [&provider](DraggableRegionProvider* p) { return p == provider; }); } 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_); } void NativeWindow::HandlePendingFullscreenTransitions() { if (pending_transitions_.empty()) { set_fullscreen_transition_type(FullScreenTransitionType::kNone); return; } bool next_transition = pending_transitions_.front(); pending_transitions_.pop(); SetFullScreen(next_transition); } // 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