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
33,632
[Bug]: Name = nil is a valid input for NSDistributedNotificationCenter 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 18 ### What operating system are you using? macOS ### Operating System Version Mojave ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior https://developer.apple.com/documentation/foundation/nsdistributednotificationcenter/1414136-addobserver notificationName: _"When nil, the notification center doesn’t use a notification’s name to decide whether to deliver it to the observer."_ Get a running list of all notifications from macOS (no name filter): ``` [com.resilio.Sync.FeOnExtPingAliveNotifiaction] [com.apple.backup.exclusionschanged] [com.resilio.Sync.FeOnExtPingAliveNotifiaction] [com.apple.backup.prefschanged] [com.resilio.Sync.FeOnExtPingAliveNotifiaction] [com.resilio.Sync.FeOnExtPingAliveNotifiaction] [com.resilio.Sync.FeOnExtPingAliveNotifiaction] ``` ### ### Actual Behavior Throws an error. `> [email protected] start > electron . App threw an error during load TypeError: Error processing argument at index 0, conversion failure from null at Object.<anonymous> (/node-electron-NSDNC.git/main.js:6:29) at Module._compile (node:internal/modules/cjs/loader:1116:14) at Object.Module._extensions..js (node:internal/modules/cjs/loader:1169:10) at Module.load (node:internal/modules/cjs/loader:988:32) at Module._load (node:internal/modules/cjs/loader:829:12) at Function.c._load (node:electron/js2c/asar_bundle:5:13343) at loadApplicationPackage (/node-electron-NSDNC.git/node_modules/electron/dist/Electron.app/Contents/Resources/default_app.asar/main.js:110:16) at Object.<anonymous> (/node-electron-NSDNC.git/node_modules/electron/dist/Electron.app/Contents/Resources/default_app.asar/main.js:222:9) at Module._compile (node:internal/modules/cjs/loader:1116:14) at Object.Module._extensions..js (node:internal/modules/cjs/loader:1169:10) ### Testcase Gist URL https://gist.github.com/knev/0cd2a52a0aebe8e35904641df47f60d7 ### Additional Information Electron file: `shell/browser/api/electron_api_system_preferences_mac.mm` It is obvious that `SysUTF8ToNSString(name)` will throw an error when name is `nil`. `nil` is a valid input. ``` int SystemPreferences::DoSubscribeNotification( const std::string& name, const NotificationCallback& callback, NotificationCenterKind kind) { int request_id = g_next_id++; __block NotificationCallback copied_callback = callback; g_id_map[request_id] = [GetNotificationCenter(kind) addObserverForName:base::SysUTF8ToNSString(name) object:nil queue:nil usingBlock:^(NSNotification* notification) { std::string object = ""; if ([notification.object isKindOfClass:[NSString class]]) { object = base::SysNSStringToUTF8(notification.object); } if (notification.userInfo) { copied_callback.Run( base::SysNSStringToUTF8(notification.name), NSDictionaryToDictionaryValue(notification.userInfo), object); } else { copied_callback.Run( base::SysNSStringToUTF8(notification.name), base::DictionaryValue(), object); } }]; return request_id; } ```
https://github.com/electron/electron/issues/33632
https://github.com/electron/electron/pull/33641
bfbba9dad6b9a0c4ae25dfab65cc9ecfcea86745
b66667b84350d25119d934cc7b683e3b88464908
2022-04-06T08:01:21Z
c++
2022-04-13T20:02:33Z
spec-main/api-system-preferences-spec.ts
import { expect } from 'chai'; import { systemPreferences } from 'electron/main'; import { ifdescribe } from './spec-helpers'; describe('systemPreferences module', () => { ifdescribe(process.platform === 'win32')('systemPreferences.getAccentColor', () => { it('should return a non-empty string', () => { const accentColor = systemPreferences.getAccentColor(); expect(accentColor).to.be.a('string').that.is.not.empty('accent color'); }); }); ifdescribe(process.platform === 'win32')('systemPreferences.getColor(id)', () => { it('throws an error when the id is invalid', () => { expect(() => { systemPreferences.getColor('not-a-color' as any); }).to.throw('Unknown color: not-a-color'); }); it('returns a hex RGB color string', () => { expect(systemPreferences.getColor('window')).to.match(/^#[0-9A-F]{6}$/i); }); }); ifdescribe(process.platform === 'darwin')('systemPreferences.registerDefaults(defaults)', () => { it('registers defaults', () => { const defaultsMap = [ { key: 'one', type: 'string', value: 'ONE' }, { key: 'two', value: 2, type: 'integer' }, { key: 'three', value: [1, 2, 3], type: 'array' } ]; const defaultsDict: Record<string, any> = {}; defaultsMap.forEach(row => { defaultsDict[row.key] = row.value; }); systemPreferences.registerDefaults(defaultsDict); for (const userDefault of defaultsMap) { const { key, value: expectedValue, type } = userDefault; const actualValue = systemPreferences.getUserDefault(key, type as any); expect(actualValue).to.deep.equal(expectedValue); } }); it('throws when bad defaults are passed', () => { const badDefaults = [ 1, null, new Date(), { one: null } ]; for (const badDefault of badDefaults) { expect(() => { systemPreferences.registerDefaults(badDefault as any); }).to.throw('Error processing argument at index 0, conversion failure from '); } }); }); ifdescribe(process.platform === 'darwin')('systemPreferences.getUserDefault(key, type)', () => { it('returns values for known user defaults', () => { const locale = systemPreferences.getUserDefault('AppleLocale', 'string'); expect(locale).to.be.a('string').that.is.not.empty('locale'); const languages = systemPreferences.getUserDefault('AppleLanguages', 'array'); expect(languages).to.be.an('array').that.is.not.empty('languages'); }); it('returns values for unknown user defaults', () => { expect(systemPreferences.getUserDefault('UserDefaultDoesNotExist', 'boolean')).to.equal(false); expect(systemPreferences.getUserDefault('UserDefaultDoesNotExist', 'integer')).to.equal(0); expect(systemPreferences.getUserDefault('UserDefaultDoesNotExist', 'float')).to.equal(0); expect(systemPreferences.getUserDefault('UserDefaultDoesNotExist', 'double')).to.equal(0); expect(systemPreferences.getUserDefault('UserDefaultDoesNotExist', 'string')).to.equal(''); expect(systemPreferences.getUserDefault('UserDefaultDoesNotExist', 'url')).to.equal(''); expect(systemPreferences.getUserDefault('UserDefaultDoesNotExist', 'badtype' as any)).to.be.undefined('user default'); expect(systemPreferences.getUserDefault('UserDefaultDoesNotExist', 'array')).to.deep.equal([]); expect(systemPreferences.getUserDefault('UserDefaultDoesNotExist', 'dictionary')).to.deep.equal({}); }); }); ifdescribe(process.platform === 'darwin')('systemPreferences.setUserDefault(key, type, value)', () => { const KEY = 'SystemPreferencesTest'; const TEST_CASES = [ ['string', 'abc'], ['boolean', true], ['float', 2.5], ['double', 10.1], ['integer', 11], ['url', 'https://github.com/electron'], ['array', [1, 2, 3]], ['dictionary', { a: 1, b: 2 }] ]; it('sets values', () => { for (const [type, value] of TEST_CASES) { systemPreferences.setUserDefault(KEY, type as any, value as any); const retrievedValue = systemPreferences.getUserDefault(KEY, type as any); expect(retrievedValue).to.deep.equal(value); } }); it('throws when type and value conflict', () => { for (const [type, value] of TEST_CASES) { expect(() => { systemPreferences.setUserDefault(KEY, type as any, typeof value === 'string' ? {} : 'foo' as any); }).to.throw(`Unable to convert value to: ${type}`); } }); it('throws when type is not valid', () => { expect(() => { systemPreferences.setUserDefault(KEY, 'abc' as any, 'foo'); }).to.throw('Invalid type: abc'); }); }); ifdescribe(process.platform === 'darwin')('systemPreferences.getSystemColor(color)', () => { it('throws on invalid system colors', () => { const color = 'bad-color'; expect(() => { systemPreferences.getSystemColor(color as any); }).to.throw(`Unknown system color: ${color}`); }); it('returns a valid system color', () => { const colors = ['blue', 'brown', 'gray', 'green', 'orange', 'pink', 'purple', 'red', 'yellow']; colors.forEach(color => { const sysColor = systemPreferences.getSystemColor(color as any); expect(sysColor).to.be.a('string'); }); }); }); ifdescribe(process.platform === 'darwin')('systemPreferences.getColor(color)', () => { it('throws on invalid colors', () => { const color = 'bad-color'; expect(() => { systemPreferences.getColor(color as any); }).to.throw(`Unknown color: ${color}`); }); it('returns a valid color', () => { const colors = [ 'alternate-selected-control-text', 'control-background', 'control', 'control-text', 'disabled-control-text', 'find-highlight', 'grid', 'header-text', 'highlight', 'keyboard-focus-indicator', 'label', 'link', 'placeholder-text', 'quaternary-label', 'scrubber-textured-background', 'secondary-label', 'selected-content-background', 'selected-control', 'selected-control-text', 'selected-menu-item-text', 'selected-text-background', 'selected-text', 'separator', 'shadow', 'tertiary-label', 'text-background', 'text', 'under-page-background', 'unemphasized-selected-content-background', 'unemphasized-selected-text-background', 'unemphasized-selected-text', 'window-background', 'window-frame-text' ]; colors.forEach(color => { const sysColor = systemPreferences.getColor(color as any); expect(sysColor).to.be.a('string'); }); }); }); ifdescribe(process.platform === 'darwin')('systemPreferences.appLevelAppearance', () => { const options = ['dark', 'light', 'unknown', null]; describe('with properties', () => { it('returns a valid appearance', () => { const appearance = systemPreferences.appLevelAppearance; expect(options).to.include(appearance); }); it('can be changed', () => { systemPreferences.appLevelAppearance = 'dark'; expect(systemPreferences.appLevelAppearance).to.eql('dark'); }); }); describe('with functions', () => { it('returns a valid appearance', () => { const appearance = systemPreferences.getAppLevelAppearance(); expect(options).to.include(appearance); }); it('can be changed', () => { systemPreferences.setAppLevelAppearance('dark'); const appearance = systemPreferences.getAppLevelAppearance(); expect(appearance).to.eql('dark'); }); }); }); ifdescribe(process.platform === 'darwin')('systemPreferences.effectiveAppearance', () => { const options = ['dark', 'light', 'unknown']; describe('with properties', () => { it('returns a valid appearance', () => { const appearance = systemPreferences.effectiveAppearance; expect(options).to.include(appearance); }); }); describe('with functions', () => { it('returns a valid appearance', () => { const appearance = systemPreferences.getEffectiveAppearance(); expect(options).to.include(appearance); }); }); }); ifdescribe(process.platform === 'darwin')('systemPreferences.setUserDefault(key, type, value)', () => { it('removes keys', () => { const KEY = 'SystemPreferencesTest'; systemPreferences.setUserDefault(KEY, 'string', 'foo'); systemPreferences.removeUserDefault(KEY); expect(systemPreferences.getUserDefault(KEY, 'string')).to.equal(''); }); it('does not throw for missing keys', () => { systemPreferences.removeUserDefault('some-missing-key'); }); }); ifdescribe(process.platform === 'darwin')('systemPreferences.canPromptTouchID()', () => { it('returns a boolean', () => { expect(systemPreferences.canPromptTouchID()).to.be.a('boolean'); }); }); ifdescribe(process.platform === 'darwin')('systemPreferences.isTrustedAccessibilityClient(prompt)', () => { it('returns a boolean', () => { const trusted = systemPreferences.isTrustedAccessibilityClient(false); expect(trusted).to.be.a('boolean'); }); }); ifdescribe(['win32', 'darwin'].includes(process.platform))('systemPreferences.getMediaAccessStatus(mediaType)', () => { const statuses = ['not-determined', 'granted', 'denied', 'restricted', 'unknown']; it('returns an access status for a camera access request', () => { const cameraStatus = systemPreferences.getMediaAccessStatus('camera'); expect(statuses).to.include(cameraStatus); }); it('returns an access status for a microphone access request', () => { const microphoneStatus = systemPreferences.getMediaAccessStatus('microphone'); expect(statuses).to.include(microphoneStatus); }); it('returns an access status for a screen access request', () => { const screenStatus = systemPreferences.getMediaAccessStatus('screen'); expect(statuses).to.include(screenStatus); }); }); describe('systemPreferences.getAnimationSettings()', () => { it('returns an object with all properties', () => { const settings = systemPreferences.getAnimationSettings(); expect(settings).to.be.an('object'); expect(settings).to.have.property('shouldRenderRichAnimation').that.is.a('boolean'); expect(settings).to.have.property('scrollAnimationsEnabledBySystem').that.is.a('boolean'); expect(settings).to.have.property('prefersReducedMotion').that.is.a('boolean'); }); }); });
closed
electron/electron
https://github.com/electron/electron
33,632
[Bug]: Name = nil is a valid input for NSDistributedNotificationCenter 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 18 ### What operating system are you using? macOS ### Operating System Version Mojave ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior https://developer.apple.com/documentation/foundation/nsdistributednotificationcenter/1414136-addobserver notificationName: _"When nil, the notification center doesn’t use a notification’s name to decide whether to deliver it to the observer."_ Get a running list of all notifications from macOS (no name filter): ``` [com.resilio.Sync.FeOnExtPingAliveNotifiaction] [com.apple.backup.exclusionschanged] [com.resilio.Sync.FeOnExtPingAliveNotifiaction] [com.apple.backup.prefschanged] [com.resilio.Sync.FeOnExtPingAliveNotifiaction] [com.resilio.Sync.FeOnExtPingAliveNotifiaction] [com.resilio.Sync.FeOnExtPingAliveNotifiaction] ``` ### ### Actual Behavior Throws an error. `> [email protected] start > electron . App threw an error during load TypeError: Error processing argument at index 0, conversion failure from null at Object.<anonymous> (/node-electron-NSDNC.git/main.js:6:29) at Module._compile (node:internal/modules/cjs/loader:1116:14) at Object.Module._extensions..js (node:internal/modules/cjs/loader:1169:10) at Module.load (node:internal/modules/cjs/loader:988:32) at Module._load (node:internal/modules/cjs/loader:829:12) at Function.c._load (node:electron/js2c/asar_bundle:5:13343) at loadApplicationPackage (/node-electron-NSDNC.git/node_modules/electron/dist/Electron.app/Contents/Resources/default_app.asar/main.js:110:16) at Object.<anonymous> (/node-electron-NSDNC.git/node_modules/electron/dist/Electron.app/Contents/Resources/default_app.asar/main.js:222:9) at Module._compile (node:internal/modules/cjs/loader:1116:14) at Object.Module._extensions..js (node:internal/modules/cjs/loader:1169:10) ### Testcase Gist URL https://gist.github.com/knev/0cd2a52a0aebe8e35904641df47f60d7 ### Additional Information Electron file: `shell/browser/api/electron_api_system_preferences_mac.mm` It is obvious that `SysUTF8ToNSString(name)` will throw an error when name is `nil`. `nil` is a valid input. ``` int SystemPreferences::DoSubscribeNotification( const std::string& name, const NotificationCallback& callback, NotificationCenterKind kind) { int request_id = g_next_id++; __block NotificationCallback copied_callback = callback; g_id_map[request_id] = [GetNotificationCenter(kind) addObserverForName:base::SysUTF8ToNSString(name) object:nil queue:nil usingBlock:^(NSNotification* notification) { std::string object = ""; if ([notification.object isKindOfClass:[NSString class]]) { object = base::SysNSStringToUTF8(notification.object); } if (notification.userInfo) { copied_callback.Run( base::SysNSStringToUTF8(notification.name), NSDictionaryToDictionaryValue(notification.userInfo), object); } else { copied_callback.Run( base::SysNSStringToUTF8(notification.name), base::DictionaryValue(), object); } }]; return request_id; } ```
https://github.com/electron/electron/issues/33632
https://github.com/electron/electron/pull/33641
bfbba9dad6b9a0c4ae25dfab65cc9ecfcea86745
b66667b84350d25119d934cc7b683e3b88464908
2022-04-06T08:01:21Z
c++
2022-04-13T20:02:33Z
docs/api/system-preferences.md
# systemPreferences > Get system preferences. Process: [Main](../glossary.md#main-process) ```javascript const { systemPreferences } = require('electron') console.log(systemPreferences.isDarkMode()) ``` ## Events The `systemPreferences` object emits the following events: ### Event: 'accent-color-changed' _Windows_ Returns: * `event` Event * `newColor` string - The new RGBA color the user assigned to be their system accent color. ### Event: 'color-changed' _Windows_ Returns: * `event` Event ### Event: 'inverted-color-scheme-changed' _Windows_ _Deprecated_ Returns: * `event` Event * `invertedColorScheme` boolean - `true` if an inverted color scheme (a high contrast color scheme with light text and dark backgrounds) is being used, `false` otherwise. **Deprecated:** Should use the new [`updated`](native-theme.md#event-updated) event on the `nativeTheme` module. ### Event: 'high-contrast-color-scheme-changed' _Windows_ _Deprecated_ Returns: * `event` Event * `highContrastColorScheme` boolean - `true` if a high contrast theme is being used, `false` otherwise. **Deprecated:** Should use the new [`updated`](native-theme.md#event-updated) event on the `nativeTheme` module. ## Methods ### `systemPreferences.isDarkMode()` _macOS_ _Windows_ _Deprecated_ Returns `boolean` - Whether the system is in Dark Mode. **Deprecated:** Should use the new [`nativeTheme.shouldUseDarkColors`](native-theme.md#nativethemeshouldusedarkcolors-readonly) API. ### `systemPreferences.isSwipeTrackingFromScrollEventsEnabled()` _macOS_ Returns `boolean` - Whether the Swipe between pages setting is on. ### `systemPreferences.postNotification(event, userInfo[, deliverImmediately])` _macOS_ * `event` string * `userInfo` Record<string, any> * `deliverImmediately` boolean (optional) - `true` to post notifications immediately even when the subscribing app is inactive. Posts `event` as native notifications of macOS. The `userInfo` is an Object that contains the user information dictionary sent along with the notification. ### `systemPreferences.postLocalNotification(event, userInfo)` _macOS_ * `event` string * `userInfo` Record<string, any> Posts `event` as native notifications of macOS. The `userInfo` is an Object that contains the user information dictionary sent along with the notification. ### `systemPreferences.postWorkspaceNotification(event, userInfo)` _macOS_ * `event` string * `userInfo` Record<string, any> Posts `event` as native notifications of macOS. The `userInfo` is an Object that contains the user information dictionary sent along with the notification. ### `systemPreferences.subscribeNotification(event, callback)` _macOS_ * `event` string * `callback` Function * `event` string * `userInfo` Record<string, unknown> * `object` string Returns `number` - The ID of this subscription Subscribes to native notifications of macOS, `callback` will be called with `callback(event, userInfo)` when the corresponding `event` happens. The `userInfo` is an Object that contains the user information dictionary sent along with the notification. The `object` is the sender of the notification, and only supports `NSString` values for now. The `id` of the subscriber is returned, which can be used to unsubscribe the `event`. Under the hood this API subscribes to `NSDistributedNotificationCenter`, example values of `event` are: * `AppleInterfaceThemeChangedNotification` * `AppleAquaColorVariantChanged` * `AppleColorPreferencesChangedNotification` * `AppleShowScrollBarsSettingChanged` ### `systemPreferences.subscribeLocalNotification(event, callback)` _macOS_ * `event` string * `callback` Function * `event` string * `userInfo` Record<string, unknown> * `object` string Returns `number` - The ID of this subscription Same as `subscribeNotification`, but uses `NSNotificationCenter` for local defaults. This is necessary for events such as `NSUserDefaultsDidChangeNotification`. ### `systemPreferences.subscribeWorkspaceNotification(event, callback)` _macOS_ * `event` string * `callback` Function * `event` string * `userInfo` Record<string, unknown> * `object` string Returns `number` - The ID of this subscription Same as `subscribeNotification`, but uses `NSWorkspace.sharedWorkspace.notificationCenter`. This is necessary for events such as `NSWorkspaceDidActivateApplicationNotification`. ### `systemPreferences.unsubscribeNotification(id)` _macOS_ * `id` Integer Removes the subscriber with `id`. ### `systemPreferences.unsubscribeLocalNotification(id)` _macOS_ * `id` Integer Same as `unsubscribeNotification`, but removes the subscriber from `NSNotificationCenter`. ### `systemPreferences.unsubscribeWorkspaceNotification(id)` _macOS_ * `id` Integer Same as `unsubscribeNotification`, but removes the subscriber from `NSWorkspace.sharedWorkspace.notificationCenter`. ### `systemPreferences.registerDefaults(defaults)` _macOS_ * `defaults` Record<string, string | boolean | number> - a dictionary of (`key: value`) user defaults Add the specified defaults to your application's `NSUserDefaults`. ### `systemPreferences.getUserDefault<Type extends keyof UserDefaultTypes>(key, type)` _macOS_ * `key` string * `type` Type - Can be `string`, `boolean`, `integer`, `float`, `double`, `url`, `array` or `dictionary`. Returns [`UserDefaultTypes[Type]`](structures/user-default-types.md) - The value of `key` in `NSUserDefaults`. Some popular `key` and `type`s are: * `AppleInterfaceStyle`: `string` * `AppleAquaColorVariant`: `integer` * `AppleHighlightColor`: `string` * `AppleShowScrollBars`: `string` * `NSNavRecentPlaces`: `array` * `NSPreferredWebServices`: `dictionary` * `NSUserDictionaryReplacementItems`: `array` ### `systemPreferences.setUserDefault<Type extends keyof UserDefaultTypes>(key, type, value)` _macOS_ * `key` string * `type` Type - Can be `string`, `boolean`, `integer`, `float`, `double`, `url`, `array` or `dictionary`. * `value` UserDefaultTypes[Type] Set the value of `key` in `NSUserDefaults`. Note that `type` should match actual type of `value`. An exception is thrown if they don't. Some popular `key` and `type`s are: * `ApplePressAndHoldEnabled`: `boolean` ### `systemPreferences.removeUserDefault(key)` _macOS_ * `key` string Removes the `key` in `NSUserDefaults`. This can be used to restore the default or global value of a `key` previously set with `setUserDefault`. ### `systemPreferences.isAeroGlassEnabled()` _Windows_ Returns `boolean` - `true` if [DWM composition][dwm-composition] (Aero Glass) is enabled, and `false` otherwise. An example of using it to determine if you should create a transparent window or not (transparent windows won't work correctly when DWM composition is disabled): ```javascript const { BrowserWindow, systemPreferences } = require('electron') const browserOptions = { width: 1000, height: 800 } // Make the window transparent only if the platform supports it. if (process.platform !== 'win32' || systemPreferences.isAeroGlassEnabled()) { browserOptions.transparent = true browserOptions.frame = false } // Create the window. const win = new BrowserWindow(browserOptions) // Navigate. if (browserOptions.transparent) { win.loadURL(`file://${__dirname}/index.html`) } else { // No transparency, so we load a fallback that uses basic styles. win.loadURL(`file://${__dirname}/fallback.html`) } ``` [dwm-composition]:https://msdn.microsoft.com/en-us/library/windows/desktop/aa969540.aspx ### `systemPreferences.getAccentColor()` _Windows_ _macOS_ Returns `string` - The users current system wide accent color preference in RGBA hexadecimal form. ```js const color = systemPreferences.getAccentColor() // `"aabbccdd"` const red = color.substr(0, 2) // "aa" const green = color.substr(2, 2) // "bb" const blue = color.substr(4, 2) // "cc" const alpha = color.substr(6, 2) // "dd" ``` This API is only available on macOS 10.14 Mojave or newer. ### `systemPreferences.getColor(color)` _Windows_ _macOS_ * `color` string - One of the following values: * On **Windows**: * `3d-dark-shadow` - Dark shadow for three-dimensional display elements. * `3d-face` - Face color for three-dimensional display elements and for dialog box backgrounds. * `3d-highlight` - Highlight color for three-dimensional display elements. * `3d-light` - Light color for three-dimensional display elements. * `3d-shadow` - Shadow color for three-dimensional display elements. * `active-border` - Active window border. * `active-caption` - Active window title bar. Specifies the left side color in the color gradient of an active window's title bar if the gradient effect is enabled. * `active-caption-gradient` - Right side color in the color gradient of an active window's title bar. * `app-workspace` - Background color of multiple document interface (MDI) applications. * `button-text` - Text on push buttons. * `caption-text` - Text in caption, size box, and scroll bar arrow box. * `desktop` - Desktop background color. * `disabled-text` - Grayed (disabled) text. * `highlight` - Item(s) selected in a control. * `highlight-text` - Text of item(s) selected in a control. * `hotlight` - Color for a hyperlink or hot-tracked item. * `inactive-border` - Inactive window border. * `inactive-caption` - Inactive window caption. Specifies the left side color in the color gradient of an inactive window's title bar if the gradient effect is enabled. * `inactive-caption-gradient` - Right side color in the color gradient of an inactive window's title bar. * `inactive-caption-text` - Color of text in an inactive caption. * `info-background` - Background color for tooltip controls. * `info-text` - Text color for tooltip controls. * `menu` - Menu background. * `menu-highlight` - The color used to highlight menu items when the menu appears as a flat menu. * `menubar` - The background color for the menu bar when menus appear as flat menus. * `menu-text` - Text in menus. * `scrollbar` - Scroll bar gray area. * `window` - Window background. * `window-frame` - Window frame. * `window-text` - Text in windows. * On **macOS** * `alternate-selected-control-text` - The text on a selected surface in a list or table. _deprecated_ * `control-background` - The background of a large interface element, such as a browser or table. * `control` - The surface of a control. * `control-text` -The text of a control that isn’t disabled. * `disabled-control-text` - The text of a control that’s disabled. * `find-highlight` - The color of a find indicator. * `grid` - The gridlines of an interface element such as a table. * `header-text` - The text of a header cell in a table. * `highlight` - The virtual light source onscreen. * `keyboard-focus-indicator` - The ring that appears around the currently focused control when using the keyboard for interface navigation. * `label` - The text of a label containing primary content. * `link` - A link to other content. * `placeholder-text` - A placeholder string in a control or text view. * `quaternary-label` - The text of a label of lesser importance than a tertiary label such as watermark text. * `scrubber-textured-background` - The background of a scrubber in the Touch Bar. * `secondary-label` - The text of a label of lesser importance than a normal label such as a label used to represent a subheading or additional information. * `selected-content-background` - The background for selected content in a key window or view. * `selected-control` - The surface of a selected control. * `selected-control-text` - The text of a selected control. * `selected-menu-item-text` - The text of a selected menu. * `selected-text-background` - The background of selected text. * `selected-text` - Selected text. * `separator` - A separator between different sections of content. * `shadow` - The virtual shadow cast by a raised object onscreen. * `tertiary-label` - The text of a label of lesser importance than a secondary label such as a label used to represent disabled text. * `text-background` - Text background. * `text` - The text in a document. * `under-page-background` - The background behind a document's content. * `unemphasized-selected-content-background` - The selected content in a non-key window or view. * `unemphasized-selected-text-background` - A background for selected text in a non-key window or view. * `unemphasized-selected-text` - Selected text in a non-key window or view. * `window-background` - The background of a window. * `window-frame-text` - The text in the window's titlebar area. Returns `string` - The system color setting in RGB hexadecimal form (`#ABCDEF`). See the [Windows docs][windows-colors] and the [macOS docs][macos-colors] for more details. The following colors are only available on macOS 10.14: `find-highlight`, `selected-content-background`, `separator`, `unemphasized-selected-content-background`, `unemphasized-selected-text-background`, and `unemphasized-selected-text`. [windows-colors]:https://msdn.microsoft.com/en-us/library/windows/desktop/ms724371(v=vs.85).aspx [macos-colors]:https://developer.apple.com/design/human-interface-guidelines/macos/visual-design/color#dynamic-system-colors ### `systemPreferences.getSystemColor(color)` _macOS_ * `color` string - One of the following values: * `blue` * `brown` * `gray` * `green` * `orange` * `pink` * `purple` * `red` * `yellow` Returns `string` - The standard system color formatted as `#RRGGBBAA`. Returns one of several standard system colors that automatically adapt to vibrancy and changes in accessibility settings like 'Increase contrast' and 'Reduce transparency'. See [Apple Documentation](https://developer.apple.com/design/human-interface-guidelines/macos/visual-design/color#system-colors) for more details. ### `systemPreferences.isInvertedColorScheme()` _Windows_ _Deprecated_ Returns `boolean` - `true` if an inverted color scheme (a high contrast color scheme with light text and dark backgrounds) is active, `false` otherwise. **Deprecated:** Should use the new [`nativeTheme.shouldUseInvertedColorScheme`](native-theme.md#nativethemeshoulduseinvertedcolorscheme-macos-windows-readonly) API. ### `systemPreferences.isHighContrastColorScheme()` _macOS_ _Windows_ _Deprecated_ Returns `boolean` - `true` if a high contrast theme is active, `false` otherwise. **Deprecated:** Should use the new [`nativeTheme.shouldUseHighContrastColors`](native-theme.md#nativethemeshouldusehighcontrastcolors-macos-windows-readonly) API. ### `systemPreferences.getEffectiveAppearance()` _macOS_ Returns `string` - Can be `dark`, `light` or `unknown`. Gets the macOS appearance setting that is currently applied to your application, maps to [NSApplication.effectiveAppearance](https://developer.apple.com/documentation/appkit/nsapplication/2967171-effectiveappearance?language=objc) ### `systemPreferences.getAppLevelAppearance()` _macOS_ _Deprecated_ Returns `string` | `null` - Can be `dark`, `light` or `unknown`. Gets the macOS appearance setting that you have declared you want for your application, maps to [NSApplication.appearance](https://developer.apple.com/documentation/appkit/nsapplication/2967170-appearance?language=objc). You can use the `setAppLevelAppearance` API to set this value. ### `systemPreferences.setAppLevelAppearance(appearance)` _macOS_ _Deprecated_ * `appearance` string | null - Can be `dark` or `light` Sets the appearance setting for your application, this should override the system default and override the value of `getEffectiveAppearance`. ### `systemPreferences.canPromptTouchID()` _macOS_ Returns `boolean` - whether or not this device has the ability to use Touch ID. **NOTE:** This API will return `false` on macOS systems older than Sierra 10.12.2. ### `systemPreferences.promptTouchID(reason)` _macOS_ * `reason` string - The reason you are asking for Touch ID authentication Returns `Promise<void>` - resolves if the user has successfully authenticated with Touch ID. ```javascript const { systemPreferences } = require('electron') systemPreferences.promptTouchID('To get consent for a Security-Gated Thing').then(success => { console.log('You have successfully authenticated with Touch ID!') }).catch(err => { console.log(err) }) ``` This API itself will not protect your user data; rather, it is a mechanism to allow you to do so. Native apps will need to set [Access Control Constants](https://developer.apple.com/documentation/security/secaccesscontrolcreateflags?language=objc) like [`kSecAccessControlUserPresence`](https://developer.apple.com/documentation/security/secaccesscontrolcreateflags/ksecaccesscontroluserpresence?language=objc) on their keychain entry so that reading it would auto-prompt for Touch ID biometric consent. This could be done with [`node-keytar`](https://github.com/atom/node-keytar), such that one would store an encryption key with `node-keytar` and only fetch it if `promptTouchID()` resolves. **NOTE:** This API will return a rejected Promise on macOS systems older than Sierra 10.12.2. ### `systemPreferences.isTrustedAccessibilityClient(prompt)` _macOS_ * `prompt` boolean - whether or not the user will be informed via prompt if the current process is untrusted. Returns `boolean` - `true` if the current process is a trusted accessibility client and `false` if it is not. ### `systemPreferences.getMediaAccessStatus(mediaType)` _Windows_ _macOS_ * `mediaType` string - Can be `microphone`, `camera` or `screen`. Returns `string` - Can be `not-determined`, `granted`, `denied`, `restricted` or `unknown`. This user consent was not required on macOS 10.13 High Sierra or lower so this method will always return `granted`. macOS 10.14 Mojave or higher requires consent for `microphone` and `camera` access. macOS 10.15 Catalina or higher requires consent for `screen` access. Windows 10 has a global setting controlling `microphone` and `camera` access for all win32 applications. It will always return `granted` for `screen` and for all media types on older versions of Windows. ### `systemPreferences.askForMediaAccess(mediaType)` _macOS_ * `mediaType` string - the type of media being requested; can be `microphone`, `camera`. Returns `Promise<boolean>` - A promise that resolves with `true` if consent was granted and `false` if it was denied. If an invalid `mediaType` is passed, the promise will be rejected. If an access request was denied and later is changed through the System Preferences pane, a restart of the app will be required for the new permissions to take effect. If access has already been requested and denied, it _must_ be changed through the preference pane; an alert will not pop up and the promise will resolve with the existing access status. **Important:** In order to properly leverage this API, you [must set](https://developer.apple.com/documentation/avfoundation/cameras_and_media_capture/requesting_authorization_for_media_capture_on_macos?language=objc) the `NSMicrophoneUsageDescription` and `NSCameraUsageDescription` strings in your app's `Info.plist` file. The values for these keys will be used to populate the permission dialogs so that the user will be properly informed as to the purpose of the permission request. See [Electron Application Distribution](../tutorial/application-distribution.md#macos) for more information about how to set these in the context of Electron. This user consent was not required until macOS 10.14 Mojave, so this method will always return `true` if your system is running 10.13 High Sierra or lower. ### `systemPreferences.getAnimationSettings()` Returns `Object`: * `shouldRenderRichAnimation` boolean - Returns true if rich animations should be rendered. Looks at session type (e.g. remote desktop) and accessibility settings to give guidance for heavy animations. * `scrollAnimationsEnabledBySystem` boolean - Determines on a per-platform basis whether scroll animations (e.g. produced by home/end key) should be enabled. * `prefersReducedMotion` boolean - Determines whether the user desires reduced motion based on platform APIs. Returns an object with system animation settings. ## Properties ### `systemPreferences.appLevelAppearance` _macOS_ A `string` property that can be `dark`, `light` or `unknown`. It determines the macOS appearance setting for your application. This maps to values in: [NSApplication.appearance](https://developer.apple.com/documentation/appkit/nsapplication/2967170-appearance?language=objc). Setting this will override the system default as well as the value of `getEffectiveAppearance`. Possible values that can be set are `dark` and `light`, and possible return values are `dark`, `light`, and `unknown`. This property is only available on macOS 10.14 Mojave or newer. ### `systemPreferences.effectiveAppearance` _macOS_ _Readonly_ A `string` property that can be `dark`, `light` or `unknown`. Returns the macOS appearance setting that is currently applied to your application, maps to [NSApplication.effectiveAppearance](https://developer.apple.com/documentation/appkit/nsapplication/2967171-effectiveappearance?language=objc)
closed
electron/electron
https://github.com/electron/electron
33,632
[Bug]: Name = nil is a valid input for NSDistributedNotificationCenter 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 18 ### What operating system are you using? macOS ### Operating System Version Mojave ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior https://developer.apple.com/documentation/foundation/nsdistributednotificationcenter/1414136-addobserver notificationName: _"When nil, the notification center doesn’t use a notification’s name to decide whether to deliver it to the observer."_ Get a running list of all notifications from macOS (no name filter): ``` [com.resilio.Sync.FeOnExtPingAliveNotifiaction] [com.apple.backup.exclusionschanged] [com.resilio.Sync.FeOnExtPingAliveNotifiaction] [com.apple.backup.prefschanged] [com.resilio.Sync.FeOnExtPingAliveNotifiaction] [com.resilio.Sync.FeOnExtPingAliveNotifiaction] [com.resilio.Sync.FeOnExtPingAliveNotifiaction] ``` ### ### Actual Behavior Throws an error. `> [email protected] start > electron . App threw an error during load TypeError: Error processing argument at index 0, conversion failure from null at Object.<anonymous> (/node-electron-NSDNC.git/main.js:6:29) at Module._compile (node:internal/modules/cjs/loader:1116:14) at Object.Module._extensions..js (node:internal/modules/cjs/loader:1169:10) at Module.load (node:internal/modules/cjs/loader:988:32) at Module._load (node:internal/modules/cjs/loader:829:12) at Function.c._load (node:electron/js2c/asar_bundle:5:13343) at loadApplicationPackage (/node-electron-NSDNC.git/node_modules/electron/dist/Electron.app/Contents/Resources/default_app.asar/main.js:110:16) at Object.<anonymous> (/node-electron-NSDNC.git/node_modules/electron/dist/Electron.app/Contents/Resources/default_app.asar/main.js:222:9) at Module._compile (node:internal/modules/cjs/loader:1116:14) at Object.Module._extensions..js (node:internal/modules/cjs/loader:1169:10) ### Testcase Gist URL https://gist.github.com/knev/0cd2a52a0aebe8e35904641df47f60d7 ### Additional Information Electron file: `shell/browser/api/electron_api_system_preferences_mac.mm` It is obvious that `SysUTF8ToNSString(name)` will throw an error when name is `nil`. `nil` is a valid input. ``` int SystemPreferences::DoSubscribeNotification( const std::string& name, const NotificationCallback& callback, NotificationCenterKind kind) { int request_id = g_next_id++; __block NotificationCallback copied_callback = callback; g_id_map[request_id] = [GetNotificationCenter(kind) addObserverForName:base::SysUTF8ToNSString(name) object:nil queue:nil usingBlock:^(NSNotification* notification) { std::string object = ""; if ([notification.object isKindOfClass:[NSString class]]) { object = base::SysNSStringToUTF8(notification.object); } if (notification.userInfo) { copied_callback.Run( base::SysNSStringToUTF8(notification.name), NSDictionaryToDictionaryValue(notification.userInfo), object); } else { copied_callback.Run( base::SysNSStringToUTF8(notification.name), base::DictionaryValue(), object); } }]; return request_id; } ```
https://github.com/electron/electron/issues/33632
https://github.com/electron/electron/pull/33641
bfbba9dad6b9a0c4ae25dfab65cc9ecfcea86745
b66667b84350d25119d934cc7b683e3b88464908
2022-04-06T08:01:21Z
c++
2022-04-13T20:02:33Z
shell/browser/api/electron_api_system_preferences.h
// Copyright (c) 2016 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_SYSTEM_PREFERENCES_H_ #define ELECTRON_SHELL_BROWSER_API_ELECTRON_API_SYSTEM_PREFERENCES_H_ #include <memory> #include <string> #include "base/values.h" #include "gin/handle.h" #include "gin/wrappable.h" #include "shell/browser/event_emitter_mixin.h" #include "shell/common/gin_helper/error_thrower.h" #include "shell/common/gin_helper/promise.h" #if BUILDFLAG(IS_WIN) #include "shell/browser/browser.h" #include "shell/browser/browser_observer.h" #include "ui/gfx/sys_color_change_listener.h" #endif namespace electron { namespace api { #if BUILDFLAG(IS_MAC) enum class NotificationCenterKind { kNSDistributedNotificationCenter = 0, kNSNotificationCenter, kNSWorkspaceNotificationCenter, }; #endif class SystemPreferences : public gin::Wrappable<SystemPreferences>, public gin_helper::EventEmitterMixin<SystemPreferences> #if BUILDFLAG(IS_WIN) , public BrowserObserver, public gfx::SysColorChangeListener #endif { public: static gin::Handle<SystemPreferences> Create(v8::Isolate* isolate); // gin::Wrappable static gin::WrapperInfo kWrapperInfo; gin::ObjectTemplateBuilder GetObjectTemplateBuilder( v8::Isolate* isolate) override; const char* GetTypeName() override; #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC) std::string GetAccentColor(); std::string GetColor(gin_helper::ErrorThrower thrower, const std::string& color); std::string GetMediaAccessStatus(gin_helper::ErrorThrower thrower, const std::string& media_type); #endif #if BUILDFLAG(IS_WIN) bool IsAeroGlassEnabled(); void InitializeWindow(); // gfx::SysColorChangeListener: void OnSysColorChange() override; // BrowserObserver: void OnFinishLaunching(const base::DictionaryValue& launch_info) override; #elif BUILDFLAG(IS_MAC) using NotificationCallback = base::RepeatingCallback< void(const std::string&, base::DictionaryValue, const std::string&)>; void PostNotification(const std::string& name, base::DictionaryValue user_info, gin::Arguments* args); int SubscribeNotification(const std::string& name, const NotificationCallback& callback); void UnsubscribeNotification(int id); void PostLocalNotification(const std::string& name, base::DictionaryValue user_info); int SubscribeLocalNotification(const std::string& name, const NotificationCallback& callback); void UnsubscribeLocalNotification(int request_id); void PostWorkspaceNotification(const std::string& name, base::DictionaryValue user_info); int SubscribeWorkspaceNotification(const std::string& name, const NotificationCallback& callback); void UnsubscribeWorkspaceNotification(int request_id); v8::Local<v8::Value> GetUserDefault(v8::Isolate* isolate, const std::string& name, const std::string& type); void RegisterDefaults(gin::Arguments* args); void SetUserDefault(const std::string& name, const std::string& type, gin::Arguments* args); void RemoveUserDefault(const std::string& name); bool IsSwipeTrackingFromScrollEventsEnabled(); std::string GetSystemColor(gin_helper::ErrorThrower thrower, const std::string& color); bool CanPromptTouchID(); v8::Local<v8::Promise> PromptTouchID(v8::Isolate* isolate, const std::string& reason); static bool IsTrustedAccessibilityClient(bool prompt); v8::Local<v8::Promise> AskForMediaAccess(v8::Isolate* isolate, const std::string& media_type); // TODO(MarshallOfSound): Write tests for these methods once we // are running tests on a Mojave machine v8::Local<v8::Value> GetEffectiveAppearance(v8::Isolate* isolate); v8::Local<v8::Value> GetAppLevelAppearance(v8::Isolate* isolate); void SetAppLevelAppearance(gin::Arguments* args); #endif bool IsInvertedColorScheme(); bool IsHighContrastColorScheme(); v8::Local<v8::Value> GetAnimationSettings(v8::Isolate* isolate); // disable copy SystemPreferences(const SystemPreferences&) = delete; SystemPreferences& operator=(const SystemPreferences&) = delete; protected: SystemPreferences(); ~SystemPreferences() override; #if BUILDFLAG(IS_MAC) int DoSubscribeNotification(const std::string& name, const NotificationCallback& callback, NotificationCenterKind kind); void DoUnsubscribeNotification(int request_id, NotificationCenterKind kind); #endif private: #if BUILDFLAG(IS_WIN) // Static callback invoked when a message comes in to our messaging window. static LRESULT CALLBACK WndProcStatic(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam); LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam); // The window class of |window_|. ATOM atom_; // The handle of the module that contains the window procedure of |window_|. HMODULE instance_; // The window used for processing events. HWND window_; std::string current_color_; bool invertered_color_scheme_ = false; bool high_contrast_color_scheme_ = false; std::unique_ptr<gfx::ScopedSysColorChangeListener> color_change_listener_; #endif }; } // namespace api } // namespace electron #endif // ELECTRON_SHELL_BROWSER_API_ELECTRON_API_SYSTEM_PREFERENCES_H_
closed
electron/electron
https://github.com/electron/electron
33,632
[Bug]: Name = nil is a valid input for NSDistributedNotificationCenter 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 18 ### What operating system are you using? macOS ### Operating System Version Mojave ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior https://developer.apple.com/documentation/foundation/nsdistributednotificationcenter/1414136-addobserver notificationName: _"When nil, the notification center doesn’t use a notification’s name to decide whether to deliver it to the observer."_ Get a running list of all notifications from macOS (no name filter): ``` [com.resilio.Sync.FeOnExtPingAliveNotifiaction] [com.apple.backup.exclusionschanged] [com.resilio.Sync.FeOnExtPingAliveNotifiaction] [com.apple.backup.prefschanged] [com.resilio.Sync.FeOnExtPingAliveNotifiaction] [com.resilio.Sync.FeOnExtPingAliveNotifiaction] [com.resilio.Sync.FeOnExtPingAliveNotifiaction] ``` ### ### Actual Behavior Throws an error. `> [email protected] start > electron . App threw an error during load TypeError: Error processing argument at index 0, conversion failure from null at Object.<anonymous> (/node-electron-NSDNC.git/main.js:6:29) at Module._compile (node:internal/modules/cjs/loader:1116:14) at Object.Module._extensions..js (node:internal/modules/cjs/loader:1169:10) at Module.load (node:internal/modules/cjs/loader:988:32) at Module._load (node:internal/modules/cjs/loader:829:12) at Function.c._load (node:electron/js2c/asar_bundle:5:13343) at loadApplicationPackage (/node-electron-NSDNC.git/node_modules/electron/dist/Electron.app/Contents/Resources/default_app.asar/main.js:110:16) at Object.<anonymous> (/node-electron-NSDNC.git/node_modules/electron/dist/Electron.app/Contents/Resources/default_app.asar/main.js:222:9) at Module._compile (node:internal/modules/cjs/loader:1116:14) at Object.Module._extensions..js (node:internal/modules/cjs/loader:1169:10) ### Testcase Gist URL https://gist.github.com/knev/0cd2a52a0aebe8e35904641df47f60d7 ### Additional Information Electron file: `shell/browser/api/electron_api_system_preferences_mac.mm` It is obvious that `SysUTF8ToNSString(name)` will throw an error when name is `nil`. `nil` is a valid input. ``` int SystemPreferences::DoSubscribeNotification( const std::string& name, const NotificationCallback& callback, NotificationCenterKind kind) { int request_id = g_next_id++; __block NotificationCallback copied_callback = callback; g_id_map[request_id] = [GetNotificationCenter(kind) addObserverForName:base::SysUTF8ToNSString(name) object:nil queue:nil usingBlock:^(NSNotification* notification) { std::string object = ""; if ([notification.object isKindOfClass:[NSString class]]) { object = base::SysNSStringToUTF8(notification.object); } if (notification.userInfo) { copied_callback.Run( base::SysNSStringToUTF8(notification.name), NSDictionaryToDictionaryValue(notification.userInfo), object); } else { copied_callback.Run( base::SysNSStringToUTF8(notification.name), base::DictionaryValue(), object); } }]; return request_id; } ```
https://github.com/electron/electron/issues/33632
https://github.com/electron/electron/pull/33641
bfbba9dad6b9a0c4ae25dfab65cc9ecfcea86745
b66667b84350d25119d934cc7b683e3b88464908
2022-04-06T08:01:21Z
c++
2022-04-13T20:02:33Z
shell/browser/api/electron_api_system_preferences_mac.mm
// Copyright (c) 2016 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_system_preferences.h" #include <map> #include <memory> #include <string> #include <utility> #import <AVFoundation/AVFoundation.h> #import <Cocoa/Cocoa.h> #import <LocalAuthentication/LocalAuthentication.h> #import <Security/Security.h> #include "base/mac/scoped_cftyperef.h" #include "base/mac/sdk_forward_declarations.h" #include "base/strings/stringprintf.h" #include "base/strings/sys_string_conversions.h" #include "base/task/sequenced_task_runner.h" #include "base/threading/sequenced_task_runner_handle.h" #include "base/values.h" #include "chrome/browser/media/webrtc/system_media_capture_permissions_mac.h" #include "net/base/mac/url_conversions.h" #include "shell/browser/mac/dict_util.h" #include "shell/browser/mac/electron_application.h" #include "shell/browser/ui/cocoa/NSColor+Hex.h" #include "shell/common/color_util.h" #include "shell/common/gin_converters/gurl_converter.h" #include "shell/common/gin_converters/value_converter.h" #include "shell/common/node_includes.h" #include "shell/common/process_util.h" #include "skia/ext/skia_utils_mac.h" #include "ui/native_theme/native_theme.h" namespace gin { template <> struct Converter<NSAppearance*> { static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, NSAppearance** out) { if (val->IsNull()) { *out = nil; return true; } std::string name; if (!gin::ConvertFromV8(isolate, val, &name)) { return false; } if (name == "light") { *out = [NSAppearance appearanceNamed:NSAppearanceNameAqua]; return true; } else if (name == "dark") { if (@available(macOS 10.14, *)) { *out = [NSAppearance appearanceNamed:NSAppearanceNameDarkAqua]; } else { *out = [NSAppearance appearanceNamed:NSAppearanceNameAqua]; } return true; } return false; } static v8::Local<v8::Value> ToV8(v8::Isolate* isolate, NSAppearance* val) { if (val == nil) { return v8::Null(isolate); } if ([val.name isEqualToString:NSAppearanceNameAqua]) { return gin::ConvertToV8(isolate, "light"); } if (@available(macOS 10.14, *)) { if ([val.name isEqualToString:NSAppearanceNameDarkAqua]) { return gin::ConvertToV8(isolate, "dark"); } } return gin::ConvertToV8(isolate, "unknown"); } }; } // namespace gin namespace electron { namespace api { namespace { int g_next_id = 0; // The map to convert |id| to |int|. std::map<int, id> g_id_map; AVMediaType ParseMediaType(const std::string& media_type) { if (media_type == "camera") { return AVMediaTypeVideo; } else if (media_type == "microphone") { return AVMediaTypeAudio; } else { return nil; } } std::string ConvertSystemPermission( system_media_permissions::SystemPermission value) { using SystemPermission = system_media_permissions::SystemPermission; switch (value) { case SystemPermission::kNotDetermined: return "not-determined"; case SystemPermission::kRestricted: return "restricted"; case SystemPermission::kDenied: return "denied"; case SystemPermission::kAllowed: return "granted"; default: return "unknown"; } } NSNotificationCenter* GetNotificationCenter(NotificationCenterKind kind) { switch (kind) { case NotificationCenterKind::kNSDistributedNotificationCenter: return [NSDistributedNotificationCenter defaultCenter]; case NotificationCenterKind::kNSNotificationCenter: return [NSNotificationCenter defaultCenter]; case NotificationCenterKind::kNSWorkspaceNotificationCenter: return [[NSWorkspace sharedWorkspace] notificationCenter]; default: return nil; } } } // namespace void SystemPreferences::PostNotification(const std::string& name, base::DictionaryValue user_info, gin::Arguments* args) { bool immediate = false; args->GetNext(&immediate); NSDistributedNotificationCenter* center = [NSDistributedNotificationCenter defaultCenter]; [center postNotificationName:base::SysUTF8ToNSString(name) object:nil userInfo:DictionaryValueToNSDictionary(user_info) deliverImmediately:immediate]; } int SystemPreferences::SubscribeNotification( const std::string& name, const NotificationCallback& callback) { return DoSubscribeNotification( name, callback, NotificationCenterKind::kNSDistributedNotificationCenter); } void SystemPreferences::UnsubscribeNotification(int request_id) { DoUnsubscribeNotification( request_id, NotificationCenterKind::kNSDistributedNotificationCenter); } void SystemPreferences::PostLocalNotification(const std::string& name, base::DictionaryValue user_info) { NSNotificationCenter* center = [NSNotificationCenter defaultCenter]; [center postNotificationName:base::SysUTF8ToNSString(name) object:nil userInfo:DictionaryValueToNSDictionary(user_info)]; } int SystemPreferences::SubscribeLocalNotification( const std::string& name, const NotificationCallback& callback) { return DoSubscribeNotification(name, callback, NotificationCenterKind::kNSNotificationCenter); } void SystemPreferences::UnsubscribeLocalNotification(int request_id) { DoUnsubscribeNotification(request_id, NotificationCenterKind::kNSNotificationCenter); } void SystemPreferences::PostWorkspaceNotification( const std::string& name, base::DictionaryValue user_info) { NSNotificationCenter* center = [[NSWorkspace sharedWorkspace] notificationCenter]; [center postNotificationName:base::SysUTF8ToNSString(name) object:nil userInfo:DictionaryValueToNSDictionary(user_info)]; } int SystemPreferences::SubscribeWorkspaceNotification( const std::string& name, const NotificationCallback& callback) { return DoSubscribeNotification( name, callback, NotificationCenterKind::kNSWorkspaceNotificationCenter); } void SystemPreferences::UnsubscribeWorkspaceNotification(int request_id) { DoUnsubscribeNotification( request_id, NotificationCenterKind::kNSWorkspaceNotificationCenter); } int SystemPreferences::DoSubscribeNotification( const std::string& name, const NotificationCallback& callback, NotificationCenterKind kind) { int request_id = g_next_id++; __block NotificationCallback copied_callback = callback; g_id_map[request_id] = [GetNotificationCenter(kind) addObserverForName:base::SysUTF8ToNSString(name) object:nil queue:nil usingBlock:^(NSNotification* notification) { std::string object = ""; if ([notification.object isKindOfClass:[NSString class]]) { object = base::SysNSStringToUTF8(notification.object); } if (notification.userInfo) { copied_callback.Run( base::SysNSStringToUTF8(notification.name), NSDictionaryToDictionaryValue(notification.userInfo), object); } else { copied_callback.Run( base::SysNSStringToUTF8(notification.name), base::DictionaryValue(), object); } }]; return request_id; } void SystemPreferences::DoUnsubscribeNotification(int request_id, NotificationCenterKind kind) { auto iter = g_id_map.find(request_id); if (iter != g_id_map.end()) { id observer = iter->second; [GetNotificationCenter(kind) removeObserver:observer]; g_id_map.erase(iter); } } v8::Local<v8::Value> SystemPreferences::GetUserDefault( v8::Isolate* isolate, const std::string& name, const std::string& type) { NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults]; NSString* key = base::SysUTF8ToNSString(name); if (type == "string") { return gin::StringToV8( isolate, base::SysNSStringToUTF8([defaults stringForKey:key])); } else if (type == "boolean") { return v8::Boolean::New(isolate, [defaults boolForKey:key]); } else if (type == "float") { return v8::Number::New(isolate, [defaults floatForKey:key]); } else if (type == "integer") { return v8::Integer::New(isolate, [defaults integerForKey:key]); } else if (type == "double") { return v8::Number::New(isolate, [defaults doubleForKey:key]); } else if (type == "url") { return gin::ConvertToV8(isolate, net::GURLWithNSURL([defaults URLForKey:key])); } else if (type == "array") { return gin::ConvertToV8(isolate, NSArrayToListValue([defaults arrayForKey:key])); } else if (type == "dictionary") { return gin::ConvertToV8(isolate, NSDictionaryToDictionaryValue( [defaults dictionaryForKey:key])); } else { return v8::Undefined(isolate); } } void SystemPreferences::RegisterDefaults(gin::Arguments* args) { base::DictionaryValue value; if (!args->GetNext(&value)) { args->ThrowError(); } else { @try { NSDictionary* dict = DictionaryValueToNSDictionary(value); for (id key in dict) { id value = [dict objectForKey:key]; if ([value isKindOfClass:[NSNull class]] || value == nil) { args->ThrowError(); return; } } [[NSUserDefaults standardUserDefaults] registerDefaults:dict]; } @catch (NSException* exception) { args->ThrowError(); } } } void SystemPreferences::SetUserDefault(const std::string& name, const std::string& type, gin::Arguments* args) { NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults]; NSString* key = base::SysUTF8ToNSString(name); if (type == "string") { std::string value; if (args->GetNext(&value)) { [defaults setObject:base::SysUTF8ToNSString(value) forKey:key]; return; } } else if (type == "boolean") { bool value; v8::Local<v8::Value> next = args->PeekNext(); if (!next.IsEmpty() && next->IsBoolean() && args->GetNext(&value)) { [defaults setBool:value forKey:key]; return; } } else if (type == "float") { float value; if (args->GetNext(&value)) { [defaults setFloat:value forKey:key]; return; } } else if (type == "integer") { int value; if (args->GetNext(&value)) { [defaults setInteger:value forKey:key]; return; } } else if (type == "double") { double value; if (args->GetNext(&value)) { [defaults setDouble:value forKey:key]; return; } } else if (type == "url") { GURL value; if (args->GetNext(&value)) { if (NSURL* url = net::NSURLWithGURL(value)) { [defaults setURL:url forKey:key]; return; } } } else if (type == "array") { base::ListValue value; if (args->GetNext(&value)) { if (NSArray* array = ListValueToNSArray(value)) { [defaults setObject:array forKey:key]; return; } } } else if (type == "dictionary") { base::DictionaryValue value; if (args->GetNext(&value)) { if (NSDictionary* dict = DictionaryValueToNSDictionary(value)) { [defaults setObject:dict forKey:key]; return; } } } else { gin_helper::ErrorThrower(args->isolate()) .ThrowTypeError("Invalid type: " + type); return; } gin_helper::ErrorThrower(args->isolate()) .ThrowTypeError("Unable to convert value to: " + type); } std::string SystemPreferences::GetAccentColor() { NSColor* sysColor = nil; if (@available(macOS 10.14, *)) sysColor = [NSColor controlAccentColor]; return ToRGBAHex(skia::NSSystemColorToSkColor(sysColor), false /* include_hash */); } std::string SystemPreferences::GetSystemColor(gin_helper::ErrorThrower thrower, const std::string& color) { NSColor* sysColor = nil; if (color == "blue") { sysColor = [NSColor systemBlueColor]; } else if (color == "brown") { sysColor = [NSColor systemBrownColor]; } else if (color == "gray") { sysColor = [NSColor systemGrayColor]; } else if (color == "green") { sysColor = [NSColor systemGreenColor]; } else if (color == "orange") { sysColor = [NSColor systemOrangeColor]; } else if (color == "pink") { sysColor = [NSColor systemPinkColor]; } else if (color == "purple") { sysColor = [NSColor systemPurpleColor]; } else if (color == "red") { sysColor = [NSColor systemRedColor]; } else if (color == "yellow") { sysColor = [NSColor systemYellowColor]; } else { thrower.ThrowError("Unknown system color: " + color); return ""; } return ToRGBAHex(skia::NSSystemColorToSkColor(sysColor)); } bool SystemPreferences::CanPromptTouchID() { if (@available(macOS 10.12.2, *)) { base::scoped_nsobject<LAContext> context([[LAContext alloc] init]); if (![context canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:nil]) return false; if (@available(macOS 10.13.2, *)) return [context biometryType] == LABiometryTypeTouchID; return true; } return false; } v8::Local<v8::Promise> SystemPreferences::PromptTouchID( v8::Isolate* isolate, const std::string& reason) { gin_helper::Promise<void> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); if (@available(macOS 10.12.2, *)) { base::scoped_nsobject<LAContext> context([[LAContext alloc] init]); base::ScopedCFTypeRef<SecAccessControlRef> access_control = base::ScopedCFTypeRef<SecAccessControlRef>( SecAccessControlCreateWithFlags( kCFAllocatorDefault, kSecAttrAccessibleWhenUnlockedThisDeviceOnly, kSecAccessControlPrivateKeyUsage | kSecAccessControlUserPresence, nullptr)); scoped_refptr<base::SequencedTaskRunner> runner = base::SequencedTaskRunnerHandle::Get(); __block gin_helper::Promise<void> p = std::move(promise); [context evaluateAccessControl:access_control operation:LAAccessControlOperationUseKeySign localizedReason:[NSString stringWithUTF8String:reason.c_str()] reply:^(BOOL success, NSError* error) { if (!success) { std::string err_msg = std::string( [error.localizedDescription UTF8String]); runner->PostTask( FROM_HERE, base::BindOnce( gin_helper::Promise<void>::RejectPromise, std::move(p), std::move(err_msg))); } else { runner->PostTask( FROM_HERE, base::BindOnce( gin_helper::Promise<void>::ResolvePromise, std::move(p))); } }]; } else { promise.RejectWithErrorMessage( "This API is not available on macOS versions older than 10.12.2"); } return handle; } // static bool SystemPreferences::IsTrustedAccessibilityClient(bool prompt) { NSDictionary* options = @{(id)kAXTrustedCheckOptionPrompt : @(prompt)}; return AXIsProcessTrustedWithOptions((CFDictionaryRef)options); } std::string SystemPreferences::GetColor(gin_helper::ErrorThrower thrower, const std::string& color) { NSColor* sysColor = nil; if (color == "alternate-selected-control-text") { sysColor = [NSColor alternateSelectedControlTextColor]; EmitWarning( node::Environment::GetCurrent(thrower.isolate()), "'alternate-selected-control-text' is deprecated as an input to " "getColor. Use 'selected-content-background' instead.", "electron"); } else if (color == "control-background") { sysColor = [NSColor controlBackgroundColor]; } else if (color == "control") { sysColor = [NSColor controlColor]; } else if (color == "control-text") { sysColor = [NSColor controlTextColor]; } else if (color == "disabled-control-text") { sysColor = [NSColor disabledControlTextColor]; } else if (color == "find-highlight") { if (@available(macOS 10.14, *)) sysColor = [NSColor findHighlightColor]; } else if (color == "grid") { sysColor = [NSColor gridColor]; } else if (color == "header-text") { sysColor = [NSColor headerTextColor]; } else if (color == "highlight") { sysColor = [NSColor highlightColor]; } else if (color == "keyboard-focus-indicator") { sysColor = [NSColor keyboardFocusIndicatorColor]; } else if (color == "label") { sysColor = [NSColor labelColor]; } else if (color == "link") { sysColor = [NSColor linkColor]; } else if (color == "placeholder-text") { sysColor = [NSColor placeholderTextColor]; } else if (color == "quaternary-label") { sysColor = [NSColor quaternaryLabelColor]; } else if (color == "scrubber-textured-background") { if (@available(macOS 10.12.2, *)) sysColor = [NSColor scrubberTexturedBackgroundColor]; } else if (color == "secondary-label") { sysColor = [NSColor secondaryLabelColor]; } else if (color == "selected-content-background") { if (@available(macOS 10.14, *)) sysColor = [NSColor selectedContentBackgroundColor]; } else if (color == "selected-control") { sysColor = [NSColor selectedControlColor]; } else if (color == "selected-control-text") { sysColor = [NSColor selectedControlTextColor]; } else if (color == "selected-menu-item-text") { sysColor = [NSColor selectedMenuItemTextColor]; } else if (color == "selected-text-background") { sysColor = [NSColor selectedTextBackgroundColor]; } else if (color == "selected-text") { sysColor = [NSColor selectedTextColor]; } else if (color == "separator") { if (@available(macOS 10.14, *)) sysColor = [NSColor separatorColor]; } else if (color == "shadow") { sysColor = [NSColor shadowColor]; } else if (color == "tertiary-label") { sysColor = [NSColor tertiaryLabelColor]; } else if (color == "text-background") { sysColor = [NSColor textBackgroundColor]; } else if (color == "text") { sysColor = [NSColor textColor]; } else if (color == "under-page-background") { sysColor = [NSColor underPageBackgroundColor]; } else if (color == "unemphasized-selected-content-background") { if (@available(macOS 10.14, *)) sysColor = [NSColor unemphasizedSelectedContentBackgroundColor]; } else if (color == "unemphasized-selected-text-background") { if (@available(macOS 10.14, *)) sysColor = [NSColor unemphasizedSelectedTextBackgroundColor]; } else if (color == "unemphasized-selected-text") { if (@available(macOS 10.14, *)) sysColor = [NSColor unemphasizedSelectedTextColor]; } else if (color == "window-background") { sysColor = [NSColor windowBackgroundColor]; } else if (color == "window-frame-text") { sysColor = [NSColor windowFrameTextColor]; } else { thrower.ThrowError("Unknown color: " + color); } if (sysColor) return ToRGBHex(skia::NSSystemColorToSkColor(sysColor)); return ""; } std::string SystemPreferences::GetMediaAccessStatus( gin_helper::ErrorThrower thrower, const std::string& media_type) { if (media_type == "camera") { return ConvertSystemPermission( system_media_permissions::CheckSystemVideoCapturePermission()); } else if (media_type == "microphone") { return ConvertSystemPermission( system_media_permissions::CheckSystemAudioCapturePermission()); } else if (media_type == "screen") { return ConvertSystemPermission( system_media_permissions::CheckSystemScreenCapturePermission()); } else { thrower.ThrowError("Invalid media type"); return std::string(); } } v8::Local<v8::Promise> SystemPreferences::AskForMediaAccess( v8::Isolate* isolate, const std::string& media_type) { gin_helper::Promise<bool> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); if (auto type = ParseMediaType(media_type)) { if (@available(macOS 10.14, *)) { __block gin_helper::Promise<bool> p = std::move(promise); [AVCaptureDevice requestAccessForMediaType:type completionHandler:^(BOOL granted) { dispatch_async(dispatch_get_main_queue(), ^{ p.Resolve(!!granted); }); }]; } else { // access always allowed pre-10.14 Mojave promise.Resolve(true); } } else { promise.RejectWithErrorMessage("Invalid media type"); } return handle; } void SystemPreferences::RemoveUserDefault(const std::string& name) { NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults]; [defaults removeObjectForKey:base::SysUTF8ToNSString(name)]; } bool SystemPreferences::IsSwipeTrackingFromScrollEventsEnabled() { return [NSEvent isSwipeTrackingFromScrollEventsEnabled]; } v8::Local<v8::Value> SystemPreferences::GetEffectiveAppearance( v8::Isolate* isolate) { if (@available(macOS 10.14, *)) { return gin::ConvertToV8( isolate, [NSApplication sharedApplication].effectiveAppearance); } return v8::Null(isolate); } v8::Local<v8::Value> SystemPreferences::GetAppLevelAppearance( v8::Isolate* isolate) { if (@available(macOS 10.14, *)) { return gin::ConvertToV8(isolate, [NSApplication sharedApplication].appearance); } return v8::Null(isolate); } void SystemPreferences::SetAppLevelAppearance(gin::Arguments* args) { if (@available(macOS 10.14, *)) { NSAppearance* appearance; if (args->GetNext(&appearance)) { [[NSApplication sharedApplication] setAppearance:appearance]; } else { args->ThrowError(); } } } } // namespace api } // namespace electron
closed
electron/electron
https://github.com/electron/electron
33,632
[Bug]: Name = nil is a valid input for NSDistributedNotificationCenter 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 18 ### What operating system are you using? macOS ### Operating System Version Mojave ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior https://developer.apple.com/documentation/foundation/nsdistributednotificationcenter/1414136-addobserver notificationName: _"When nil, the notification center doesn’t use a notification’s name to decide whether to deliver it to the observer."_ Get a running list of all notifications from macOS (no name filter): ``` [com.resilio.Sync.FeOnExtPingAliveNotifiaction] [com.apple.backup.exclusionschanged] [com.resilio.Sync.FeOnExtPingAliveNotifiaction] [com.apple.backup.prefschanged] [com.resilio.Sync.FeOnExtPingAliveNotifiaction] [com.resilio.Sync.FeOnExtPingAliveNotifiaction] [com.resilio.Sync.FeOnExtPingAliveNotifiaction] ``` ### ### Actual Behavior Throws an error. `> [email protected] start > electron . App threw an error during load TypeError: Error processing argument at index 0, conversion failure from null at Object.<anonymous> (/node-electron-NSDNC.git/main.js:6:29) at Module._compile (node:internal/modules/cjs/loader:1116:14) at Object.Module._extensions..js (node:internal/modules/cjs/loader:1169:10) at Module.load (node:internal/modules/cjs/loader:988:32) at Module._load (node:internal/modules/cjs/loader:829:12) at Function.c._load (node:electron/js2c/asar_bundle:5:13343) at loadApplicationPackage (/node-electron-NSDNC.git/node_modules/electron/dist/Electron.app/Contents/Resources/default_app.asar/main.js:110:16) at Object.<anonymous> (/node-electron-NSDNC.git/node_modules/electron/dist/Electron.app/Contents/Resources/default_app.asar/main.js:222:9) at Module._compile (node:internal/modules/cjs/loader:1116:14) at Object.Module._extensions..js (node:internal/modules/cjs/loader:1169:10) ### Testcase Gist URL https://gist.github.com/knev/0cd2a52a0aebe8e35904641df47f60d7 ### Additional Information Electron file: `shell/browser/api/electron_api_system_preferences_mac.mm` It is obvious that `SysUTF8ToNSString(name)` will throw an error when name is `nil`. `nil` is a valid input. ``` int SystemPreferences::DoSubscribeNotification( const std::string& name, const NotificationCallback& callback, NotificationCenterKind kind) { int request_id = g_next_id++; __block NotificationCallback copied_callback = callback; g_id_map[request_id] = [GetNotificationCenter(kind) addObserverForName:base::SysUTF8ToNSString(name) object:nil queue:nil usingBlock:^(NSNotification* notification) { std::string object = ""; if ([notification.object isKindOfClass:[NSString class]]) { object = base::SysNSStringToUTF8(notification.object); } if (notification.userInfo) { copied_callback.Run( base::SysNSStringToUTF8(notification.name), NSDictionaryToDictionaryValue(notification.userInfo), object); } else { copied_callback.Run( base::SysNSStringToUTF8(notification.name), base::DictionaryValue(), object); } }]; return request_id; } ```
https://github.com/electron/electron/issues/33632
https://github.com/electron/electron/pull/33641
bfbba9dad6b9a0c4ae25dfab65cc9ecfcea86745
b66667b84350d25119d934cc7b683e3b88464908
2022-04-06T08:01:21Z
c++
2022-04-13T20:02:33Z
spec-main/api-system-preferences-spec.ts
import { expect } from 'chai'; import { systemPreferences } from 'electron/main'; import { ifdescribe } from './spec-helpers'; describe('systemPreferences module', () => { ifdescribe(process.platform === 'win32')('systemPreferences.getAccentColor', () => { it('should return a non-empty string', () => { const accentColor = systemPreferences.getAccentColor(); expect(accentColor).to.be.a('string').that.is.not.empty('accent color'); }); }); ifdescribe(process.platform === 'win32')('systemPreferences.getColor(id)', () => { it('throws an error when the id is invalid', () => { expect(() => { systemPreferences.getColor('not-a-color' as any); }).to.throw('Unknown color: not-a-color'); }); it('returns a hex RGB color string', () => { expect(systemPreferences.getColor('window')).to.match(/^#[0-9A-F]{6}$/i); }); }); ifdescribe(process.platform === 'darwin')('systemPreferences.registerDefaults(defaults)', () => { it('registers defaults', () => { const defaultsMap = [ { key: 'one', type: 'string', value: 'ONE' }, { key: 'two', value: 2, type: 'integer' }, { key: 'three', value: [1, 2, 3], type: 'array' } ]; const defaultsDict: Record<string, any> = {}; defaultsMap.forEach(row => { defaultsDict[row.key] = row.value; }); systemPreferences.registerDefaults(defaultsDict); for (const userDefault of defaultsMap) { const { key, value: expectedValue, type } = userDefault; const actualValue = systemPreferences.getUserDefault(key, type as any); expect(actualValue).to.deep.equal(expectedValue); } }); it('throws when bad defaults are passed', () => { const badDefaults = [ 1, null, new Date(), { one: null } ]; for (const badDefault of badDefaults) { expect(() => { systemPreferences.registerDefaults(badDefault as any); }).to.throw('Error processing argument at index 0, conversion failure from '); } }); }); ifdescribe(process.platform === 'darwin')('systemPreferences.getUserDefault(key, type)', () => { it('returns values for known user defaults', () => { const locale = systemPreferences.getUserDefault('AppleLocale', 'string'); expect(locale).to.be.a('string').that.is.not.empty('locale'); const languages = systemPreferences.getUserDefault('AppleLanguages', 'array'); expect(languages).to.be.an('array').that.is.not.empty('languages'); }); it('returns values for unknown user defaults', () => { expect(systemPreferences.getUserDefault('UserDefaultDoesNotExist', 'boolean')).to.equal(false); expect(systemPreferences.getUserDefault('UserDefaultDoesNotExist', 'integer')).to.equal(0); expect(systemPreferences.getUserDefault('UserDefaultDoesNotExist', 'float')).to.equal(0); expect(systemPreferences.getUserDefault('UserDefaultDoesNotExist', 'double')).to.equal(0); expect(systemPreferences.getUserDefault('UserDefaultDoesNotExist', 'string')).to.equal(''); expect(systemPreferences.getUserDefault('UserDefaultDoesNotExist', 'url')).to.equal(''); expect(systemPreferences.getUserDefault('UserDefaultDoesNotExist', 'badtype' as any)).to.be.undefined('user default'); expect(systemPreferences.getUserDefault('UserDefaultDoesNotExist', 'array')).to.deep.equal([]); expect(systemPreferences.getUserDefault('UserDefaultDoesNotExist', 'dictionary')).to.deep.equal({}); }); }); ifdescribe(process.platform === 'darwin')('systemPreferences.setUserDefault(key, type, value)', () => { const KEY = 'SystemPreferencesTest'; const TEST_CASES = [ ['string', 'abc'], ['boolean', true], ['float', 2.5], ['double', 10.1], ['integer', 11], ['url', 'https://github.com/electron'], ['array', [1, 2, 3]], ['dictionary', { a: 1, b: 2 }] ]; it('sets values', () => { for (const [type, value] of TEST_CASES) { systemPreferences.setUserDefault(KEY, type as any, value as any); const retrievedValue = systemPreferences.getUserDefault(KEY, type as any); expect(retrievedValue).to.deep.equal(value); } }); it('throws when type and value conflict', () => { for (const [type, value] of TEST_CASES) { expect(() => { systemPreferences.setUserDefault(KEY, type as any, typeof value === 'string' ? {} : 'foo' as any); }).to.throw(`Unable to convert value to: ${type}`); } }); it('throws when type is not valid', () => { expect(() => { systemPreferences.setUserDefault(KEY, 'abc' as any, 'foo'); }).to.throw('Invalid type: abc'); }); }); ifdescribe(process.platform === 'darwin')('systemPreferences.getSystemColor(color)', () => { it('throws on invalid system colors', () => { const color = 'bad-color'; expect(() => { systemPreferences.getSystemColor(color as any); }).to.throw(`Unknown system color: ${color}`); }); it('returns a valid system color', () => { const colors = ['blue', 'brown', 'gray', 'green', 'orange', 'pink', 'purple', 'red', 'yellow']; colors.forEach(color => { const sysColor = systemPreferences.getSystemColor(color as any); expect(sysColor).to.be.a('string'); }); }); }); ifdescribe(process.platform === 'darwin')('systemPreferences.getColor(color)', () => { it('throws on invalid colors', () => { const color = 'bad-color'; expect(() => { systemPreferences.getColor(color as any); }).to.throw(`Unknown color: ${color}`); }); it('returns a valid color', () => { const colors = [ 'alternate-selected-control-text', 'control-background', 'control', 'control-text', 'disabled-control-text', 'find-highlight', 'grid', 'header-text', 'highlight', 'keyboard-focus-indicator', 'label', 'link', 'placeholder-text', 'quaternary-label', 'scrubber-textured-background', 'secondary-label', 'selected-content-background', 'selected-control', 'selected-control-text', 'selected-menu-item-text', 'selected-text-background', 'selected-text', 'separator', 'shadow', 'tertiary-label', 'text-background', 'text', 'under-page-background', 'unemphasized-selected-content-background', 'unemphasized-selected-text-background', 'unemphasized-selected-text', 'window-background', 'window-frame-text' ]; colors.forEach(color => { const sysColor = systemPreferences.getColor(color as any); expect(sysColor).to.be.a('string'); }); }); }); ifdescribe(process.platform === 'darwin')('systemPreferences.appLevelAppearance', () => { const options = ['dark', 'light', 'unknown', null]; describe('with properties', () => { it('returns a valid appearance', () => { const appearance = systemPreferences.appLevelAppearance; expect(options).to.include(appearance); }); it('can be changed', () => { systemPreferences.appLevelAppearance = 'dark'; expect(systemPreferences.appLevelAppearance).to.eql('dark'); }); }); describe('with functions', () => { it('returns a valid appearance', () => { const appearance = systemPreferences.getAppLevelAppearance(); expect(options).to.include(appearance); }); it('can be changed', () => { systemPreferences.setAppLevelAppearance('dark'); const appearance = systemPreferences.getAppLevelAppearance(); expect(appearance).to.eql('dark'); }); }); }); ifdescribe(process.platform === 'darwin')('systemPreferences.effectiveAppearance', () => { const options = ['dark', 'light', 'unknown']; describe('with properties', () => { it('returns a valid appearance', () => { const appearance = systemPreferences.effectiveAppearance; expect(options).to.include(appearance); }); }); describe('with functions', () => { it('returns a valid appearance', () => { const appearance = systemPreferences.getEffectiveAppearance(); expect(options).to.include(appearance); }); }); }); ifdescribe(process.platform === 'darwin')('systemPreferences.setUserDefault(key, type, value)', () => { it('removes keys', () => { const KEY = 'SystemPreferencesTest'; systemPreferences.setUserDefault(KEY, 'string', 'foo'); systemPreferences.removeUserDefault(KEY); expect(systemPreferences.getUserDefault(KEY, 'string')).to.equal(''); }); it('does not throw for missing keys', () => { systemPreferences.removeUserDefault('some-missing-key'); }); }); ifdescribe(process.platform === 'darwin')('systemPreferences.canPromptTouchID()', () => { it('returns a boolean', () => { expect(systemPreferences.canPromptTouchID()).to.be.a('boolean'); }); }); ifdescribe(process.platform === 'darwin')('systemPreferences.isTrustedAccessibilityClient(prompt)', () => { it('returns a boolean', () => { const trusted = systemPreferences.isTrustedAccessibilityClient(false); expect(trusted).to.be.a('boolean'); }); }); ifdescribe(['win32', 'darwin'].includes(process.platform))('systemPreferences.getMediaAccessStatus(mediaType)', () => { const statuses = ['not-determined', 'granted', 'denied', 'restricted', 'unknown']; it('returns an access status for a camera access request', () => { const cameraStatus = systemPreferences.getMediaAccessStatus('camera'); expect(statuses).to.include(cameraStatus); }); it('returns an access status for a microphone access request', () => { const microphoneStatus = systemPreferences.getMediaAccessStatus('microphone'); expect(statuses).to.include(microphoneStatus); }); it('returns an access status for a screen access request', () => { const screenStatus = systemPreferences.getMediaAccessStatus('screen'); expect(statuses).to.include(screenStatus); }); }); describe('systemPreferences.getAnimationSettings()', () => { it('returns an object with all properties', () => { const settings = systemPreferences.getAnimationSettings(); expect(settings).to.be.an('object'); expect(settings).to.have.property('shouldRenderRichAnimation').that.is.a('boolean'); expect(settings).to.have.property('scrollAnimationsEnabledBySystem').that.is.a('boolean'); expect(settings).to.have.property('prefersReducedMotion').that.is.a('boolean'); }); }); });
closed
electron/electron
https://github.com/electron/electron
33,722
[Bug]: `ipcRenderer.postMessage` results in `undefined` for `event.senderFrame` in browser process
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.x ### What operating system are you using? macOS ### Operating System Version 12.3.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior The `IpcMainEvent.senderFrame` is always defined. ### Actual Behavior The `IpcMainEvent.senderFrame` is `undefined` when `postMessage` is used. ### Testcase Gist URL _No response_ ### Additional Information Install a handler in browser process: ```js ipcMain.on('vscode:postMessage', (event => { console.log('vscode:postMessage', event.senderFrame); })); ``` And from the `preload.js` script simply run this code: ```js ipcRenderer.postMessage('vscode:postMessage', 'message'); ``` //cc @deepak1556
https://github.com/electron/electron/issues/33722
https://github.com/electron/electron/pull/33756
3d4d39d67b072a7c355dada2881cb6791e9e9f53
16f8d713ab05fe325a664f0fd79cb41c403c9755
2022-04-12T05:54:33Z
c++
2022-04-14T04:01:00Z
lib/browser/api/web-contents.ts
import { app, ipcMain, session, webFrameMain, deprecate } from 'electron/main'; import type { BrowserWindowConstructorOptions, LoadURLOptions } from 'electron/main'; import * as url from 'url'; import * as path from 'path'; import { openGuestWindow, makeWebPreferences, parseContentTypeFormat } from '@electron/internal/browser/guest-window-manager'; import { parseFeatures } from '@electron/internal/browser/parse-features-string'; import { ipcMainInternal } from '@electron/internal/browser/ipc-main-internal'; import * as ipcMainUtils from '@electron/internal/browser/ipc-main-internal-utils'; import { MessagePortMain } from '@electron/internal/browser/message-port-main'; import { IPC_MESSAGES } from '@electron/internal/common/ipc-messages'; // session is not used here, the purpose is to make sure session is initalized // before the webContents module. // eslint-disable-next-line session let nextId = 0; const getNextId = function () { return ++nextId; }; type PostData = LoadURLOptions['postData'] // Stock page sizes const PDFPageSizes: Record<string, ElectronInternal.MediaSize> = { A5: { custom_display_name: 'A5', height_microns: 210000, name: 'ISO_A5', width_microns: 148000 }, A4: { custom_display_name: 'A4', height_microns: 297000, name: 'ISO_A4', is_default: 'true', width_microns: 210000 }, A3: { custom_display_name: 'A3', height_microns: 420000, name: 'ISO_A3', width_microns: 297000 }, Legal: { custom_display_name: 'Legal', height_microns: 355600, name: 'NA_LEGAL', width_microns: 215900 }, Letter: { custom_display_name: 'Letter', height_microns: 279400, name: 'NA_LETTER', width_microns: 215900 }, Tabloid: { height_microns: 431800, name: 'NA_LEDGER', width_microns: 279400, custom_display_name: 'Tabloid' } } as const; // The minimum micron size Chromium accepts is that where: // Per printing/units.h: // * kMicronsPerInch - Length of an inch in 0.001mm unit. // * kPointsPerInch - Length of an inch in CSS's 1pt unit. // // Formula: (kPointsPerInch / kMicronsPerInch) * size >= 1 // // Practically, this means microns need to be > 352 microns. // We therefore need to verify this or it will silently fail. const isValidCustomPageSize = (width: number, height: number) => { return [width, height].every(x => x > 352); }; // Default printing setting const defaultPrintingSetting = { // Customizable. pageRange: [] as {from: number, to: number}[], mediaSize: {} as ElectronInternal.MediaSize, landscape: false, headerFooterEnabled: false, marginsType: 0, scaleFactor: 100, shouldPrintBackgrounds: false, shouldPrintSelectionOnly: false, // Non-customizable. printWithCloudPrint: false, printWithPrivet: false, printWithExtension: false, pagesPerSheet: 1, isFirstRequest: false, previewUIID: 0, // True, if the document source is modifiable. e.g. HTML and not PDF. previewModifiable: true, printToPDF: true, deviceName: 'Save as PDF', generateDraftData: true, dpiHorizontal: 72, dpiVertical: 72, rasterizePDF: false, duplex: 0, copies: 1, // 2 = color - see ColorModel in //printing/print_job_constants.h color: 2, collate: true, printerType: 2, title: undefined as string | undefined, url: undefined as string | undefined } as const; // JavaScript implementations of WebContents. const binding = process._linkedBinding('electron_browser_web_contents'); const printing = process._linkedBinding('electron_browser_printing'); const { WebContents } = binding as { WebContents: { prototype: Electron.WebContents } }; WebContents.prototype.postMessage = function (...args) { return this.mainFrame.postMessage(...args); }; WebContents.prototype.send = function (channel, ...args) { return this.mainFrame.send(channel, ...args); }; WebContents.prototype._sendInternal = function (channel, ...args) { return this.mainFrame._sendInternal(channel, ...args); }; function getWebFrame (contents: Electron.WebContents, frame: number | [number, number]) { if (typeof frame === 'number') { return webFrameMain.fromId(contents.mainFrame.processId, frame); } else if (Array.isArray(frame) && frame.length === 2 && frame.every(value => typeof value === 'number')) { return webFrameMain.fromId(frame[0], frame[1]); } else { throw new Error('Missing required frame argument (must be number or [processId, frameId])'); } } WebContents.prototype.sendToFrame = function (frameId, channel, ...args) { const frame = getWebFrame(this, frameId); if (!frame) return false; frame.send(channel, ...args); return true; }; WebContents.prototype._sendToFrameInternal = function (frameId, channel, ...args) { const frame = getWebFrame(this, frameId); if (!frame) return false; frame._sendInternal(channel, ...args); return true; }; // Following methods are mapped to webFrame. const webFrameMethods = [ 'insertCSS', 'insertText', 'removeInsertedCSS', 'setVisualZoomLevelLimits' ] as ('insertCSS' | 'insertText' | 'removeInsertedCSS' | 'setVisualZoomLevelLimits')[]; for (const method of webFrameMethods) { WebContents.prototype[method] = function (...args: any[]): Promise<any> { return ipcMainUtils.invokeInWebContents(this, IPC_MESSAGES.RENDERER_WEB_FRAME_METHOD, method, ...args); }; } const waitTillCanExecuteJavaScript = async (webContents: Electron.WebContents) => { if (webContents.getURL() && !webContents.isLoadingMainFrame()) return; return new Promise<void>((resolve) => { webContents.once('did-stop-loading', () => { resolve(); }); }); }; // Make sure WebContents::executeJavaScript would run the code only when the // WebContents has been loaded. WebContents.prototype.executeJavaScript = async function (code, hasUserGesture) { await waitTillCanExecuteJavaScript(this); return ipcMainUtils.invokeInWebContents(this, IPC_MESSAGES.RENDERER_WEB_FRAME_METHOD, 'executeJavaScript', String(code), !!hasUserGesture); }; WebContents.prototype.executeJavaScriptInIsolatedWorld = async function (worldId, code, hasUserGesture) { await waitTillCanExecuteJavaScript(this); return ipcMainUtils.invokeInWebContents(this, IPC_MESSAGES.RENDERER_WEB_FRAME_METHOD, 'executeJavaScriptInIsolatedWorld', worldId, code, !!hasUserGesture); }; // Translate the options of printToPDF. let pendingPromise: Promise<any> | undefined; WebContents.prototype.printToPDF = async function (options) { const printSettings: Record<string, any> = { ...defaultPrintingSetting, requestID: getNextId() }; if (options.landscape !== undefined) { if (typeof options.landscape !== 'boolean') { const error = new Error('landscape must be a Boolean'); return Promise.reject(error); } printSettings.landscape = options.landscape; } if (options.scaleFactor !== undefined) { if (typeof options.scaleFactor !== 'number') { const error = new Error('scaleFactor must be a Number'); return Promise.reject(error); } printSettings.scaleFactor = options.scaleFactor; } if (options.marginsType !== undefined) { if (typeof options.marginsType !== 'number') { const error = new Error('marginsType must be a Number'); return Promise.reject(error); } printSettings.marginsType = options.marginsType; } if (options.printSelectionOnly !== undefined) { if (typeof options.printSelectionOnly !== 'boolean') { const error = new Error('printSelectionOnly must be a Boolean'); return Promise.reject(error); } printSettings.shouldPrintSelectionOnly = options.printSelectionOnly; } if (options.printBackground !== undefined) { if (typeof options.printBackground !== 'boolean') { const error = new Error('printBackground must be a Boolean'); return Promise.reject(error); } printSettings.shouldPrintBackgrounds = options.printBackground; } if (options.pageRanges !== undefined) { const pageRanges = options.pageRanges; if (!Object.prototype.hasOwnProperty.call(pageRanges, 'from') || !Object.prototype.hasOwnProperty.call(pageRanges, 'to')) { const error = new Error('pageRanges must be an Object with \'from\' and \'to\' properties'); return Promise.reject(error); } if (typeof pageRanges.from !== 'number') { const error = new Error('pageRanges.from must be a Number'); return Promise.reject(error); } if (typeof pageRanges.to !== 'number') { const error = new Error('pageRanges.to must be a Number'); return Promise.reject(error); } // Chromium uses 1-based page ranges, so increment each by 1. printSettings.pageRange = [{ from: pageRanges.from + 1, to: pageRanges.to + 1 }]; } if (options.headerFooter !== undefined) { const headerFooter = options.headerFooter; printSettings.headerFooterEnabled = true; if (typeof headerFooter === 'object') { if (!headerFooter.url || !headerFooter.title) { const error = new Error('url and title properties are required for headerFooter'); return Promise.reject(error); } if (typeof headerFooter.title !== 'string') { const error = new Error('headerFooter.title must be a String'); return Promise.reject(error); } printSettings.title = headerFooter.title; if (typeof headerFooter.url !== 'string') { const error = new Error('headerFooter.url must be a String'); return Promise.reject(error); } printSettings.url = headerFooter.url; } else { const error = new Error('headerFooter must be an Object'); return Promise.reject(error); } } // Optionally set size for PDF. if (options.pageSize !== undefined) { const pageSize = options.pageSize; if (typeof pageSize === 'object') { if (!pageSize.height || !pageSize.width) { const error = new Error('height and width properties are required for pageSize'); return Promise.reject(error); } // Dimensions in Microns - 1 meter = 10^6 microns const height = Math.ceil(pageSize.height); const width = Math.ceil(pageSize.width); if (!isValidCustomPageSize(width, height)) { const error = new Error('height and width properties must be minimum 352 microns.'); return Promise.reject(error); } printSettings.mediaSize = { name: 'CUSTOM', custom_display_name: 'Custom', height_microns: height, width_microns: width }; } else if (Object.prototype.hasOwnProperty.call(PDFPageSizes, pageSize)) { printSettings.mediaSize = PDFPageSizes[pageSize]; } else { const error = new Error(`Unsupported pageSize: ${pageSize}`); return Promise.reject(error); } } else { printSettings.mediaSize = PDFPageSizes.A4; } // Chromium expects this in a 0-100 range number, not as float printSettings.scaleFactor = Math.ceil(printSettings.scaleFactor) % 100; // PrinterType enum from //printing/print_job_constants.h printSettings.printerType = 2; if (this._printToPDF) { if (pendingPromise) { pendingPromise = pendingPromise.then(() => this._printToPDF(printSettings)); } else { pendingPromise = this._printToPDF(printSettings); } return pendingPromise; } else { const error = new Error('Printing feature is disabled'); return Promise.reject(error); } }; WebContents.prototype.print = function (options: ElectronInternal.WebContentsPrintOptions = {}, callback) { // TODO(codebytere): deduplicate argument sanitization by moving rest of // print param logic into new file shared between printToPDF and print if (typeof options === 'object') { // Optionally set size for PDF. if (options.pageSize !== undefined) { const pageSize = options.pageSize; if (typeof pageSize === 'object') { if (!pageSize.height || !pageSize.width) { throw new Error('height and width properties are required for pageSize'); } // Dimensions in Microns - 1 meter = 10^6 microns const height = Math.ceil(pageSize.height); const width = Math.ceil(pageSize.width); if (!isValidCustomPageSize(width, height)) { throw new Error('height and width properties must be minimum 352 microns.'); } options.mediaSize = { name: 'CUSTOM', custom_display_name: 'Custom', height_microns: height, width_microns: width }; } else if (PDFPageSizes[pageSize]) { options.mediaSize = PDFPageSizes[pageSize]; } else { throw new Error(`Unsupported pageSize: ${pageSize}`); } } } if (this._print) { if (callback) { this._print(options, callback); } else { this._print(options); } } else { console.error('Error: Printing feature is disabled.'); } }; WebContents.prototype.getPrinters = function () { // TODO(nornagon): this API has nothing to do with WebContents and should be // moved. if (printing.getPrinterList) { return printing.getPrinterList(); } else { console.error('Error: Printing feature is disabled.'); return []; } }; WebContents.prototype.getPrintersAsync = async function () { // TODO(nornagon): this API has nothing to do with WebContents and should be // moved. if (printing.getPrinterListAsync) { return printing.getPrinterListAsync(); } else { console.error('Error: Printing feature is disabled.'); return []; } }; WebContents.prototype.loadFile = function (filePath, options = {}) { if (typeof filePath !== 'string') { throw new Error('Must pass filePath as a string'); } const { query, search, hash } = options; return this.loadURL(url.format({ protocol: 'file', slashes: true, pathname: path.resolve(app.getAppPath(), filePath), query, search, hash })); }; WebContents.prototype.loadURL = function (url, options) { if (!options) { options = {}; } const p = new Promise<void>((resolve, reject) => { const resolveAndCleanup = () => { removeListeners(); resolve(); }; const rejectAndCleanup = (errorCode: number, errorDescription: string, url: string) => { const err = new Error(`${errorDescription} (${errorCode}) loading '${typeof url === 'string' ? url.substr(0, 2048) : url}'`); Object.assign(err, { errno: errorCode, code: errorDescription, url }); removeListeners(); reject(err); }; const finishListener = () => { resolveAndCleanup(); }; const failListener = (event: Electron.Event, errorCode: number, errorDescription: string, validatedURL: string, isMainFrame: boolean) => { if (isMainFrame) { rejectAndCleanup(errorCode, errorDescription, validatedURL); } }; let navigationStarted = false; const navigationListener = (event: Electron.Event, url: string, isSameDocument: boolean, isMainFrame: boolean) => { if (isMainFrame) { if (navigationStarted && !isSameDocument) { // the webcontents has started another unrelated navigation in the // main frame (probably from the app calling `loadURL` again); reject // the promise // We should only consider the request aborted if the "navigation" is // actually navigating and not simply transitioning URL state in the // current context. E.g. pushState and `location.hash` changes are // considered navigation events but are triggered with isSameDocument. // We can ignore these to allow virtual routing on page load as long // as the routing does not leave the document return rejectAndCleanup(-3, 'ERR_ABORTED', url); } navigationStarted = true; } }; const stopLoadingListener = () => { // By the time we get here, either 'finish' or 'fail' should have fired // if the navigation occurred. However, in some situations (e.g. when // attempting to load a page with a bad scheme), loading will stop // without emitting finish or fail. In this case, we reject the promise // with a generic failure. // TODO(jeremy): enumerate all the cases in which this can happen. If // the only one is with a bad scheme, perhaps ERR_INVALID_ARGUMENT // would be more appropriate. rejectAndCleanup(-2, 'ERR_FAILED', url); }; const removeListeners = () => { this.removeListener('did-finish-load', finishListener); this.removeListener('did-fail-load', failListener); this.removeListener('did-start-navigation', navigationListener); this.removeListener('did-stop-loading', stopLoadingListener); this.removeListener('destroyed', stopLoadingListener); }; this.on('did-finish-load', finishListener); this.on('did-fail-load', failListener); this.on('did-start-navigation', navigationListener); this.on('did-stop-loading', stopLoadingListener); this.on('destroyed', stopLoadingListener); }); // Add a no-op rejection handler to silence the unhandled rejection error. p.catch(() => {}); this._loadURL(url, options); this.emit('load-url', url, options); return p; }; WebContents.prototype.setWindowOpenHandler = function (handler: (details: Electron.HandlerDetails) => ({action: 'deny'} | {action: 'allow', overrideBrowserWindowOptions?: BrowserWindowConstructorOptions, outlivesOpener?: boolean})) { this._windowOpenHandler = handler; }; WebContents.prototype._callWindowOpenHandler = function (event: Electron.Event, details: Electron.HandlerDetails): {browserWindowConstructorOptions: BrowserWindowConstructorOptions | null, outlivesOpener: boolean} { const defaultResponse = { browserWindowConstructorOptions: null, outlivesOpener: false }; if (!this._windowOpenHandler) { return defaultResponse; } const response = this._windowOpenHandler(details); if (typeof response !== 'object') { event.preventDefault(); console.error(`The window open handler response must be an object, but was instead of type '${typeof response}'.`); return defaultResponse; } if (response === null) { event.preventDefault(); console.error('The window open handler response must be an object, but was instead null.'); return defaultResponse; } if (response.action === 'deny') { event.preventDefault(); return defaultResponse; } else if (response.action === 'allow') { if (typeof response.overrideBrowserWindowOptions === 'object' && response.overrideBrowserWindowOptions !== null) { return { browserWindowConstructorOptions: response.overrideBrowserWindowOptions, outlivesOpener: typeof response.outlivesOpener === 'boolean' ? response.outlivesOpener : false }; } else { return { browserWindowConstructorOptions: {}, outlivesOpener: typeof response.outlivesOpener === 'boolean' ? response.outlivesOpener : false }; } } else { event.preventDefault(); console.error('The window open handler response must be an object with an \'action\' property of \'allow\' or \'deny\'.'); return defaultResponse; } }; const addReplyToEvent = (event: Electron.IpcMainEvent) => { const { processId, frameId } = event; event.reply = (channel: string, ...args: any[]) => { event.sender.sendToFrame([processId, frameId], channel, ...args); }; }; const addSenderFrameToEvent = (event: Electron.IpcMainEvent | Electron.IpcMainInvokeEvent) => { const { processId, frameId } = event; Object.defineProperty(event, 'senderFrame', { get: () => webFrameMain.fromId(processId, frameId) }); }; const addReturnValueToEvent = (event: Electron.IpcMainEvent) => { Object.defineProperty(event, 'returnValue', { set: (value) => event.sendReply(value), get: () => {} }); }; const commandLine = process._linkedBinding('electron_common_command_line'); const environment = process._linkedBinding('electron_common_environment'); const loggingEnabled = () => { return environment.hasVar('ELECTRON_ENABLE_LOGGING') || commandLine.hasSwitch('enable-logging'); }; // Add JavaScript wrappers for WebContents class. WebContents.prototype._init = function () { const prefs = this.getLastWebPreferences() || {}; if (!prefs.nodeIntegration && prefs.preload != null && prefs.sandbox == null) { deprecate.log('The default sandbox option for windows without nodeIntegration is changing. Presently, by default, when a window has a preload script, it defaults to being unsandboxed. In Electron 20, this default will be changing, and all windows that have nodeIntegration: false (which is the default) will be sandboxed by default. If your preload script doesn\'t use Node, no action is needed. If your preload script does use Node, either refactor it to move Node usage to the main process, or specify sandbox: false in your WebPreferences.'); } // Read off the ID at construction time, so that it's accessible even after // the underlying C++ WebContents is destroyed. const id = this.id; Object.defineProperty(this, 'id', { value: id, writable: false }); this._windowOpenHandler = null; // Dispatch IPC messages to the ipc module. this.on('-ipc-message' as any, function (this: Electron.WebContents, event: Electron.IpcMainEvent, internal: boolean, channel: string, args: any[]) { addSenderFrameToEvent(event); if (internal) { ipcMainInternal.emit(channel, event, ...args); } else { addReplyToEvent(event); this.emit('ipc-message', event, channel, ...args); ipcMain.emit(channel, event, ...args); } }); this.on('-ipc-invoke' as any, function (event: Electron.IpcMainInvokeEvent, internal: boolean, channel: string, args: any[]) { addSenderFrameToEvent(event); event._reply = (result: any) => event.sendReply({ result }); event._throw = (error: Error) => { console.error(`Error occurred in handler for '${channel}':`, error); event.sendReply({ error: error.toString() }); }; const target = internal ? ipcMainInternal : ipcMain; if ((target as any)._invokeHandlers.has(channel)) { (target as any)._invokeHandlers.get(channel)(event, ...args); } else { event._throw(`No handler registered for '${channel}'`); } }); this.on('-ipc-message-sync' as any, function (this: Electron.WebContents, event: Electron.IpcMainEvent, internal: boolean, channel: string, args: any[]) { addSenderFrameToEvent(event); addReturnValueToEvent(event); if (internal) { ipcMainInternal.emit(channel, event, ...args); } else { addReplyToEvent(event); if (this.listenerCount('ipc-message-sync') === 0 && ipcMain.listenerCount(channel) === 0) { console.warn(`WebContents #${this.id} called ipcRenderer.sendSync() with '${channel}' channel without listeners.`); } this.emit('ipc-message-sync', event, channel, ...args); ipcMain.emit(channel, event, ...args); } }); this.on('-ipc-ports' as any, function (event: Electron.IpcMainEvent, internal: boolean, channel: string, message: any, ports: any[]) { event.ports = ports.map(p => new MessagePortMain(p)); ipcMain.emit(channel, event, message); }); this.on('crashed', (event, ...args) => { app.emit('renderer-process-crashed', event, this, ...args); }); this.on('render-process-gone', (event, details) => { app.emit('render-process-gone', event, this, details); // Log out a hint to help users better debug renderer crashes. if (loggingEnabled()) { console.info(`Renderer process ${details.reason} - see https://www.electronjs.org/docs/tutorial/application-debugging for potential debugging information.`); } }); // The devtools requests the webContents to reload. this.on('devtools-reload-page', function (this: Electron.WebContents) { this.reload(); }); if (this.getType() !== 'remote') { // Make new windows requested by links behave like "window.open". this.on('-new-window' as any, (event: ElectronInternal.Event, url: string, frameName: string, disposition: Electron.HandlerDetails['disposition'], rawFeatures: string, referrer: Electron.Referrer, postData: PostData) => { const postBody = postData ? { data: postData, ...parseContentTypeFormat(postData) } : undefined; const details: Electron.HandlerDetails = { url, frameName, features: rawFeatures, referrer, postBody, disposition }; const result = this._callWindowOpenHandler(event, details); const options = result.browserWindowConstructorOptions; if (!event.defaultPrevented) { openGuestWindow({ event, embedder: event.sender, disposition, referrer, postData, overrideBrowserWindowOptions: options || {}, windowOpenArgs: details, outlivesOpener: result.outlivesOpener }); } }); let windowOpenOverriddenOptions: BrowserWindowConstructorOptions | null = null; let windowOpenOutlivesOpenerOption: boolean = false; this.on('-will-add-new-contents' as any, (event: ElectronInternal.Event, url: string, frameName: string, rawFeatures: string, disposition: Electron.HandlerDetails['disposition'], referrer: Electron.Referrer, postData: PostData) => { const postBody = postData ? { data: postData, ...parseContentTypeFormat(postData) } : undefined; const details: Electron.HandlerDetails = { url, frameName, features: rawFeatures, disposition, referrer, postBody }; const result = this._callWindowOpenHandler(event, details); windowOpenOutlivesOpenerOption = result.outlivesOpener; windowOpenOverriddenOptions = result.browserWindowConstructorOptions; if (!event.defaultPrevented) { const secureOverrideWebPreferences = windowOpenOverriddenOptions ? { // Allow setting of backgroundColor as a webPreference even though // it's technically a BrowserWindowConstructorOptions option because // we need to access it in the renderer at init time. backgroundColor: windowOpenOverriddenOptions.backgroundColor, transparent: windowOpenOverriddenOptions.transparent, ...windowOpenOverriddenOptions.webPreferences } : undefined; // TODO(zcbenz): The features string is parsed twice: here where it is // passed to C++, and in |makeBrowserWindowOptions| later where it is // not actually used since the WebContents is created here. // We should be able to remove the latter once the |new-window| event // is removed. const { webPreferences: parsedWebPreferences } = parseFeatures(rawFeatures); // Parameters should keep same with |makeBrowserWindowOptions|. const webPreferences = makeWebPreferences({ embedder: event.sender, insecureParsedWebPreferences: parsedWebPreferences, secureOverrideWebPreferences }); this._setNextChildWebPreferences(webPreferences); } }); // Create a new browser window for "window.open" this.on('-add-new-contents' as any, (event: ElectronInternal.Event, webContents: Electron.WebContents, disposition: string, _userGesture: boolean, _left: number, _top: number, _width: number, _height: number, url: string, frameName: string, referrer: Electron.Referrer, rawFeatures: string, postData: PostData) => { const overriddenOptions = windowOpenOverriddenOptions || undefined; const outlivesOpener = windowOpenOutlivesOpenerOption; windowOpenOverriddenOptions = null; // false is the default windowOpenOutlivesOpenerOption = false; if ((disposition !== 'foreground-tab' && disposition !== 'new-window' && disposition !== 'background-tab')) { event.preventDefault(); return; } openGuestWindow({ event, embedder: event.sender, guest: webContents, overrideBrowserWindowOptions: overriddenOptions, disposition, referrer, postData, windowOpenArgs: { url, frameName, features: rawFeatures }, outlivesOpener }); }); } this.on('login', (event, ...args) => { app.emit('login', event, this, ...args); }); this.on('ready-to-show' as any, () => { const owner = this.getOwnerBrowserWindow(); if (owner && !owner.isDestroyed()) { process.nextTick(() => { owner.emit('ready-to-show'); }); } }); this.on('select-bluetooth-device', (event, devices, callback) => { if (this.listenerCount('select-bluetooth-device') === 1) { // Cancel it if there are no handlers event.preventDefault(); callback(''); } }); const event = process._linkedBinding('electron_browser_event').createEmpty(); app.emit('web-contents-created', event, this); // Properties Object.defineProperty(this, 'audioMuted', { get: () => this.isAudioMuted(), set: (muted) => this.setAudioMuted(muted) }); Object.defineProperty(this, 'userAgent', { get: () => this.getUserAgent(), set: (agent) => this.setUserAgent(agent) }); Object.defineProperty(this, 'zoomLevel', { get: () => this.getZoomLevel(), set: (level) => this.setZoomLevel(level) }); Object.defineProperty(this, 'zoomFactor', { get: () => this.getZoomFactor(), set: (factor) => this.setZoomFactor(factor) }); Object.defineProperty(this, 'frameRate', { get: () => this.getFrameRate(), set: (rate) => this.setFrameRate(rate) }); Object.defineProperty(this, 'backgroundThrottling', { get: () => this.getBackgroundThrottling(), set: (allowed) => this.setBackgroundThrottling(allowed) }); }; // Public APIs. export function create (options = {}): Electron.WebContents { return new (WebContents as any)(options); } export function fromId (id: string) { return binding.fromId(id); } export function fromDevToolsTargetId (targetId: string) { return binding.fromDevToolsTargetId(targetId); } export function getFocusedWebContents () { let focused = null; for (const contents of binding.getAllWebContents()) { if (!contents.isFocused()) continue; if (focused == null) focused = contents; // Return webview web contents which may be embedded inside another // web contents that is also reporting as focused if (contents.getType() === 'webview') return contents; } return focused; } export function getAllWebContents () { return binding.getAllWebContents(); }
closed
electron/electron
https://github.com/electron/electron
33,722
[Bug]: `ipcRenderer.postMessage` results in `undefined` for `event.senderFrame` in browser process
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.x ### What operating system are you using? macOS ### Operating System Version 12.3.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior The `IpcMainEvent.senderFrame` is always defined. ### Actual Behavior The `IpcMainEvent.senderFrame` is `undefined` when `postMessage` is used. ### Testcase Gist URL _No response_ ### Additional Information Install a handler in browser process: ```js ipcMain.on('vscode:postMessage', (event => { console.log('vscode:postMessage', event.senderFrame); })); ``` And from the `preload.js` script simply run this code: ```js ipcRenderer.postMessage('vscode:postMessage', 'message'); ``` //cc @deepak1556
https://github.com/electron/electron/issues/33722
https://github.com/electron/electron/pull/33756
3d4d39d67b072a7c355dada2881cb6791e9e9f53
16f8d713ab05fe325a664f0fd79cb41c403c9755
2022-04-12T05:54:33Z
c++
2022-04-14T04:01:00Z
spec-main/api-ipc-spec.ts
import { EventEmitter } from 'events'; import { expect } from 'chai'; import { BrowserWindow, ipcMain, IpcMainInvokeEvent, MessageChannelMain, WebContents } from 'electron/main'; import { closeAllWindows } from './window-helpers'; import { emittedOnce } from './events-helpers'; const v8Util = process._linkedBinding('electron_common_v8_util'); describe('ipc module', () => { describe('invoke', () => { let w = (null as unknown as BrowserWindow); before(async () => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); await w.loadURL('about:blank'); }); after(async () => { w.destroy(); }); async function rendererInvoke (...args: any[]) { const { ipcRenderer } = require('electron'); try { const result = await ipcRenderer.invoke('test', ...args); ipcRenderer.send('result', { result }); } catch (e) { ipcRenderer.send('result', { error: (e as Error).message }); } } it('receives a response from a synchronous handler', async () => { ipcMain.handleOnce('test', (e: IpcMainInvokeEvent, arg: number) => { expect(arg).to.equal(123); return 3; }); const done = new Promise<void>(resolve => ipcMain.once('result', (e, arg) => { expect(arg).to.deep.equal({ result: 3 }); resolve(); })); await w.webContents.executeJavaScript(`(${rendererInvoke})(123)`); await done; }); it('receives a response from an asynchronous handler', async () => { ipcMain.handleOnce('test', async (e: IpcMainInvokeEvent, arg: number) => { expect(arg).to.equal(123); await new Promise(setImmediate); return 3; }); const done = new Promise<void>(resolve => ipcMain.once('result', (e, arg) => { expect(arg).to.deep.equal({ result: 3 }); resolve(); })); await w.webContents.executeJavaScript(`(${rendererInvoke})(123)`); await done; }); it('receives an error from a synchronous handler', async () => { ipcMain.handleOnce('test', () => { throw new Error('some error'); }); const done = new Promise<void>(resolve => ipcMain.once('result', (e, arg) => { expect(arg.error).to.match(/some error/); resolve(); })); await w.webContents.executeJavaScript(`(${rendererInvoke})()`); await done; }); it('receives an error from an asynchronous handler', async () => { ipcMain.handleOnce('test', async () => { await new Promise(setImmediate); throw new Error('some error'); }); const done = new Promise<void>(resolve => ipcMain.once('result', (e, arg) => { expect(arg.error).to.match(/some error/); resolve(); })); await w.webContents.executeJavaScript(`(${rendererInvoke})()`); await done; }); it('throws an error if no handler is registered', async () => { const done = new Promise<void>(resolve => ipcMain.once('result', (e, arg) => { expect(arg.error).to.match(/No handler registered/); resolve(); })); await w.webContents.executeJavaScript(`(${rendererInvoke})()`); await done; }); it('throws an error when invoking a handler that was removed', async () => { ipcMain.handle('test', () => {}); ipcMain.removeHandler('test'); const done = new Promise<void>(resolve => ipcMain.once('result', (e, arg) => { expect(arg.error).to.match(/No handler registered/); resolve(); })); await w.webContents.executeJavaScript(`(${rendererInvoke})()`); await done; }); it('forbids multiple handlers', async () => { ipcMain.handle('test', () => {}); try { expect(() => { ipcMain.handle('test', () => {}); }).to.throw(/second handler/); } finally { ipcMain.removeHandler('test'); } }); it('throws an error in the renderer if the reply callback is dropped', async () => { // eslint-disable-next-line @typescript-eslint/no-unused-vars ipcMain.handleOnce('test', () => new Promise(resolve => { setTimeout(() => v8Util.requestGarbageCollectionForTesting()); /* never resolve */ })); w.webContents.executeJavaScript(`(${rendererInvoke})()`); const [, { error }] = await emittedOnce(ipcMain, 'result'); expect(error).to.match(/reply was never sent/); }); }); describe('ordering', () => { let w = (null as unknown as BrowserWindow); before(async () => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); await w.loadURL('about:blank'); }); after(async () => { w.destroy(); }); it('between send and sendSync is consistent', async () => { const received: number[] = []; ipcMain.on('test-async', (e, i) => { received.push(i); }); ipcMain.on('test-sync', (e, i) => { received.push(i); e.returnValue = null; }); const done = new Promise<void>(resolve => ipcMain.once('done', () => { resolve(); })); function rendererStressTest () { const { ipcRenderer } = require('electron'); for (let i = 0; i < 1000; i++) { switch ((Math.random() * 2) | 0) { case 0: ipcRenderer.send('test-async', i); break; case 1: ipcRenderer.sendSync('test-sync', i); break; } } ipcRenderer.send('done'); } try { w.webContents.executeJavaScript(`(${rendererStressTest})()`); await done; } finally { ipcMain.removeAllListeners('test-async'); ipcMain.removeAllListeners('test-sync'); } expect(received).to.have.lengthOf(1000); expect(received).to.deep.equal([...received].sort((a, b) => a - b)); }); it('between send, sendSync, and invoke is consistent', async () => { const received: number[] = []; ipcMain.handle('test-invoke', (e, i) => { received.push(i); }); ipcMain.on('test-async', (e, i) => { received.push(i); }); ipcMain.on('test-sync', (e, i) => { received.push(i); e.returnValue = null; }); const done = new Promise<void>(resolve => ipcMain.once('done', () => { resolve(); })); function rendererStressTest () { const { ipcRenderer } = require('electron'); for (let i = 0; i < 1000; i++) { switch ((Math.random() * 3) | 0) { case 0: ipcRenderer.send('test-async', i); break; case 1: ipcRenderer.sendSync('test-sync', i); break; case 2: ipcRenderer.invoke('test-invoke', i); break; } } ipcRenderer.send('done'); } try { w.webContents.executeJavaScript(`(${rendererStressTest})()`); await done; } finally { ipcMain.removeHandler('test-invoke'); ipcMain.removeAllListeners('test-async'); ipcMain.removeAllListeners('test-sync'); } expect(received).to.have.lengthOf(1000); expect(received).to.deep.equal([...received].sort((a, b) => a - b)); }); }); describe('MessagePort', () => { afterEach(closeAllWindows); it('can send a port to the main process', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadURL('about:blank'); const p = emittedOnce(ipcMain, 'port'); await w.webContents.executeJavaScript(`(${function () { const channel = new MessageChannel(); require('electron').ipcRenderer.postMessage('port', 'hi', [channel.port1]); }})()`); const [ev, msg] = await p; expect(msg).to.equal('hi'); expect(ev.ports).to.have.length(1); const [port] = ev.ports; expect(port).to.be.an.instanceOf(EventEmitter); }); it('can sent a message without a transfer', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadURL('about:blank'); const p = emittedOnce(ipcMain, 'port'); await w.webContents.executeJavaScript(`(${function () { require('electron').ipcRenderer.postMessage('port', 'hi'); }})()`); const [ev, msg] = await p; expect(msg).to.equal('hi'); expect(ev.ports).to.deep.equal([]); }); it('can communicate between main and renderer', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadURL('about:blank'); const p = emittedOnce(ipcMain, 'port'); await w.webContents.executeJavaScript(`(${function () { const channel = new MessageChannel(); (channel.port2 as any).onmessage = (ev: any) => { channel.port2.postMessage(ev.data * 2); }; require('electron').ipcRenderer.postMessage('port', '', [channel.port1]); }})()`); const [ev] = await p; expect(ev.ports).to.have.length(1); const [port] = ev.ports; port.start(); port.postMessage(42); const [ev2] = await emittedOnce(port, 'message'); expect(ev2.data).to.equal(84); }); it('can receive a port from a renderer over a MessagePort connection', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadURL('about:blank'); function fn () { const channel1 = new MessageChannel(); const channel2 = new MessageChannel(); channel1.port2.postMessage('', [channel2.port1]); channel2.port2.postMessage('matryoshka'); require('electron').ipcRenderer.postMessage('port', '', [channel1.port1]); } w.webContents.executeJavaScript(`(${fn})()`); const [{ ports: [port1] }] = await emittedOnce(ipcMain, 'port'); port1.start(); const [{ ports: [port2] }] = await emittedOnce(port1, 'message'); port2.start(); const [{ data }] = await emittedOnce(port2, 'message'); expect(data).to.equal('matryoshka'); }); it('can forward a port from one renderer to another renderer', async () => { const w1 = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); const w2 = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w1.loadURL('about:blank'); w2.loadURL('about:blank'); w1.webContents.executeJavaScript(`(${function () { const channel = new MessageChannel(); (channel.port2 as any).onmessage = (ev: any) => { require('electron').ipcRenderer.send('message received', ev.data); }; require('electron').ipcRenderer.postMessage('port', '', [channel.port1]); }})()`); const [{ ports: [port] }] = await emittedOnce(ipcMain, 'port'); await w2.webContents.executeJavaScript(`(${function () { require('electron').ipcRenderer.on('port', ({ ports: [port] }: any) => { port.postMessage('a message'); }); }})()`); w2.webContents.postMessage('port', '', [port]); const [, data] = await emittedOnce(ipcMain, 'message received'); expect(data).to.equal('a message'); }); describe('close event', () => { describe('in renderer', () => { it('is emitted when the main process closes its end of the port', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadURL('about:blank'); await w.webContents.executeJavaScript(`(${function () { const { ipcRenderer } = require('electron'); ipcRenderer.on('port', e => { const [port] = e.ports; port.start(); (port as any).onclose = () => { ipcRenderer.send('closed'); }; }); }})()`); const { port1, port2 } = new MessageChannelMain(); w.webContents.postMessage('port', null, [port2]); port1.close(); await emittedOnce(ipcMain, 'closed'); }); it('is emitted when the other end of a port is garbage-collected', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadURL('about:blank'); await w.webContents.executeJavaScript(`(${async function () { const { port2 } = new MessageChannel(); await new Promise(resolve => { port2.start(); (port2 as any).onclose = resolve; process._linkedBinding('electron_common_v8_util').requestGarbageCollectionForTesting(); }); }})()`); }); it('is emitted when the other end of a port is sent to nowhere', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadURL('about:blank'); ipcMain.once('do-a-gc', () => v8Util.requestGarbageCollectionForTesting()); await w.webContents.executeJavaScript(`(${async function () { const { port1, port2 } = new MessageChannel(); await new Promise(resolve => { port2.start(); (port2 as any).onclose = resolve; require('electron').ipcRenderer.postMessage('nobody-listening', null, [port1]); require('electron').ipcRenderer.send('do-a-gc'); }); }})()`); }); }); }); describe('MessageChannelMain', () => { it('can be created', () => { const { port1, port2 } = new MessageChannelMain(); expect(port1).not.to.be.null(); expect(port2).not.to.be.null(); }); it('can send messages within the process', async () => { const { port1, port2 } = new MessageChannelMain(); port2.postMessage('hello'); port1.start(); const [ev] = await emittedOnce(port1, 'message'); expect(ev.data).to.equal('hello'); }); it('can pass one end to a WebContents', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadURL('about:blank'); await w.webContents.executeJavaScript(`(${function () { const { ipcRenderer } = require('electron'); ipcRenderer.on('port', ev => { const [port] = ev.ports; port.onmessage = () => { ipcRenderer.send('done'); }; }); }})()`); const { port1, port2 } = new MessageChannelMain(); port1.postMessage('hello'); w.webContents.postMessage('port', null, [port2]); await emittedOnce(ipcMain, 'done'); }); it('can be passed over another channel', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadURL('about:blank'); await w.webContents.executeJavaScript(`(${function () { const { ipcRenderer } = require('electron'); ipcRenderer.on('port', e1 => { e1.ports[0].onmessage = e2 => { e2.ports[0].onmessage = e3 => { ipcRenderer.send('done', e3.data); }; }; }); }})()`); const { port1, port2 } = new MessageChannelMain(); const { port1: port3, port2: port4 } = new MessageChannelMain(); port1.postMessage(null, [port4]); port3.postMessage('hello'); w.webContents.postMessage('port', null, [port2]); const [, message] = await emittedOnce(ipcMain, 'done'); expect(message).to.equal('hello'); }); it('can send messages to a closed port', () => { const { port1, port2 } = new MessageChannelMain(); port2.start(); port2.on('message', () => { throw new Error('unexpected message received'); }); port1.close(); port1.postMessage('hello'); }); it('can send messages to a port whose remote end is closed', () => { const { port1, port2 } = new MessageChannelMain(); port2.start(); port2.on('message', () => { throw new Error('unexpected message received'); }); port2.close(); port1.postMessage('hello'); }); it('throws when passing null ports', () => { const { port1 } = new MessageChannelMain(); expect(() => { port1.postMessage(null, [null] as any); }).to.throw(/conversion failure/); }); it('throws when passing duplicate ports', () => { const { port1 } = new MessageChannelMain(); const { port1: port3 } = new MessageChannelMain(); expect(() => { port1.postMessage(null, [port3, port3]); }).to.throw(/duplicate/); }); it('throws when passing ports that have already been neutered', () => { const { port1 } = new MessageChannelMain(); const { port1: port3 } = new MessageChannelMain(); port1.postMessage(null, [port3]); expect(() => { port1.postMessage(null, [port3]); }).to.throw(/already neutered/); }); it('throws when passing itself', () => { const { port1 } = new MessageChannelMain(); expect(() => { port1.postMessage(null, [port1]); }).to.throw(/contains the source port/); }); describe('GC behavior', () => { it('is not collected while it could still receive messages', async () => { let trigger: Function; const promise = new Promise(resolve => { trigger = resolve; }); const port1 = (() => { const { port1, port2 } = new MessageChannelMain(); port2.on('message', (e) => { trigger(e.data); }); port2.start(); return port1; })(); v8Util.requestGarbageCollectionForTesting(); port1.postMessage('hello'); expect(await promise).to.equal('hello'); }); }); }); const generateTests = (title: string, postMessage: (contents: WebContents) => WebContents['postMessage']) => { describe(title, () => { it('sends a message', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadURL('about:blank'); await w.webContents.executeJavaScript(`(${function () { const { ipcRenderer } = require('electron'); ipcRenderer.on('foo', (_e, msg) => { ipcRenderer.send('bar', msg); }); }})()`); postMessage(w.webContents)('foo', { some: 'message' }); const [, msg] = await emittedOnce(ipcMain, 'bar'); expect(msg).to.deep.equal({ some: 'message' }); }); describe('error handling', () => { it('throws on missing channel', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); expect(() => { (postMessage(w.webContents) as any)(); }).to.throw(/Insufficient number of arguments/); }); it('throws on invalid channel', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); expect(() => { postMessage(w.webContents)(null as any, '', []); }).to.throw(/Error processing argument at index 0/); }); it('throws on missing message', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); expect(() => { (postMessage(w.webContents) as any)('channel'); }).to.throw(/Insufficient number of arguments/); }); it('throws on non-serializable message', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); expect(() => { postMessage(w.webContents)('channel', w); }).to.throw(/An object could not be cloned/); }); it('throws on invalid transferable list', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); expect(() => { postMessage(w.webContents)('', '', null as any); }).to.throw(/Invalid value for transfer/); }); it('throws on transferring non-transferable', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); expect(() => { (postMessage(w.webContents) as any)('channel', '', [123]); }).to.throw(/Invalid value for transfer/); }); it('throws when passing null ports', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); expect(() => { postMessage(w.webContents)('foo', null, [null] as any); }).to.throw(/Invalid value for transfer/); }); it('throws when passing duplicate ports', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const { port1 } = new MessageChannelMain(); expect(() => { postMessage(w.webContents)('foo', null, [port1, port1]); }).to.throw(/duplicate/); }); it('throws when passing ports that have already been neutered', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const { port1 } = new MessageChannelMain(); postMessage(w.webContents)('foo', null, [port1]); expect(() => { postMessage(w.webContents)('foo', null, [port1]); }).to.throw(/already neutered/); }); }); }); }; generateTests('WebContents.postMessage', contents => contents.postMessage.bind(contents)); generateTests('WebFrameMain.postMessage', contents => contents.mainFrame.postMessage.bind(contents.mainFrame)); }); });
closed
electron/electron
https://github.com/electron/electron
33,722
[Bug]: `ipcRenderer.postMessage` results in `undefined` for `event.senderFrame` in browser process
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.x ### What operating system are you using? macOS ### Operating System Version 12.3.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior The `IpcMainEvent.senderFrame` is always defined. ### Actual Behavior The `IpcMainEvent.senderFrame` is `undefined` when `postMessage` is used. ### Testcase Gist URL _No response_ ### Additional Information Install a handler in browser process: ```js ipcMain.on('vscode:postMessage', (event => { console.log('vscode:postMessage', event.senderFrame); })); ``` And from the `preload.js` script simply run this code: ```js ipcRenderer.postMessage('vscode:postMessage', 'message'); ``` //cc @deepak1556
https://github.com/electron/electron/issues/33722
https://github.com/electron/electron/pull/33756
3d4d39d67b072a7c355dada2881cb6791e9e9f53
16f8d713ab05fe325a664f0fd79cb41c403c9755
2022-04-12T05:54:33Z
c++
2022-04-14T04:01:00Z
lib/browser/api/web-contents.ts
import { app, ipcMain, session, webFrameMain, deprecate } from 'electron/main'; import type { BrowserWindowConstructorOptions, LoadURLOptions } from 'electron/main'; import * as url from 'url'; import * as path from 'path'; import { openGuestWindow, makeWebPreferences, parseContentTypeFormat } from '@electron/internal/browser/guest-window-manager'; import { parseFeatures } from '@electron/internal/browser/parse-features-string'; import { ipcMainInternal } from '@electron/internal/browser/ipc-main-internal'; import * as ipcMainUtils from '@electron/internal/browser/ipc-main-internal-utils'; import { MessagePortMain } from '@electron/internal/browser/message-port-main'; import { IPC_MESSAGES } from '@electron/internal/common/ipc-messages'; // session is not used here, the purpose is to make sure session is initalized // before the webContents module. // eslint-disable-next-line session let nextId = 0; const getNextId = function () { return ++nextId; }; type PostData = LoadURLOptions['postData'] // Stock page sizes const PDFPageSizes: Record<string, ElectronInternal.MediaSize> = { A5: { custom_display_name: 'A5', height_microns: 210000, name: 'ISO_A5', width_microns: 148000 }, A4: { custom_display_name: 'A4', height_microns: 297000, name: 'ISO_A4', is_default: 'true', width_microns: 210000 }, A3: { custom_display_name: 'A3', height_microns: 420000, name: 'ISO_A3', width_microns: 297000 }, Legal: { custom_display_name: 'Legal', height_microns: 355600, name: 'NA_LEGAL', width_microns: 215900 }, Letter: { custom_display_name: 'Letter', height_microns: 279400, name: 'NA_LETTER', width_microns: 215900 }, Tabloid: { height_microns: 431800, name: 'NA_LEDGER', width_microns: 279400, custom_display_name: 'Tabloid' } } as const; // The minimum micron size Chromium accepts is that where: // Per printing/units.h: // * kMicronsPerInch - Length of an inch in 0.001mm unit. // * kPointsPerInch - Length of an inch in CSS's 1pt unit. // // Formula: (kPointsPerInch / kMicronsPerInch) * size >= 1 // // Practically, this means microns need to be > 352 microns. // We therefore need to verify this or it will silently fail. const isValidCustomPageSize = (width: number, height: number) => { return [width, height].every(x => x > 352); }; // Default printing setting const defaultPrintingSetting = { // Customizable. pageRange: [] as {from: number, to: number}[], mediaSize: {} as ElectronInternal.MediaSize, landscape: false, headerFooterEnabled: false, marginsType: 0, scaleFactor: 100, shouldPrintBackgrounds: false, shouldPrintSelectionOnly: false, // Non-customizable. printWithCloudPrint: false, printWithPrivet: false, printWithExtension: false, pagesPerSheet: 1, isFirstRequest: false, previewUIID: 0, // True, if the document source is modifiable. e.g. HTML and not PDF. previewModifiable: true, printToPDF: true, deviceName: 'Save as PDF', generateDraftData: true, dpiHorizontal: 72, dpiVertical: 72, rasterizePDF: false, duplex: 0, copies: 1, // 2 = color - see ColorModel in //printing/print_job_constants.h color: 2, collate: true, printerType: 2, title: undefined as string | undefined, url: undefined as string | undefined } as const; // JavaScript implementations of WebContents. const binding = process._linkedBinding('electron_browser_web_contents'); const printing = process._linkedBinding('electron_browser_printing'); const { WebContents } = binding as { WebContents: { prototype: Electron.WebContents } }; WebContents.prototype.postMessage = function (...args) { return this.mainFrame.postMessage(...args); }; WebContents.prototype.send = function (channel, ...args) { return this.mainFrame.send(channel, ...args); }; WebContents.prototype._sendInternal = function (channel, ...args) { return this.mainFrame._sendInternal(channel, ...args); }; function getWebFrame (contents: Electron.WebContents, frame: number | [number, number]) { if (typeof frame === 'number') { return webFrameMain.fromId(contents.mainFrame.processId, frame); } else if (Array.isArray(frame) && frame.length === 2 && frame.every(value => typeof value === 'number')) { return webFrameMain.fromId(frame[0], frame[1]); } else { throw new Error('Missing required frame argument (must be number or [processId, frameId])'); } } WebContents.prototype.sendToFrame = function (frameId, channel, ...args) { const frame = getWebFrame(this, frameId); if (!frame) return false; frame.send(channel, ...args); return true; }; WebContents.prototype._sendToFrameInternal = function (frameId, channel, ...args) { const frame = getWebFrame(this, frameId); if (!frame) return false; frame._sendInternal(channel, ...args); return true; }; // Following methods are mapped to webFrame. const webFrameMethods = [ 'insertCSS', 'insertText', 'removeInsertedCSS', 'setVisualZoomLevelLimits' ] as ('insertCSS' | 'insertText' | 'removeInsertedCSS' | 'setVisualZoomLevelLimits')[]; for (const method of webFrameMethods) { WebContents.prototype[method] = function (...args: any[]): Promise<any> { return ipcMainUtils.invokeInWebContents(this, IPC_MESSAGES.RENDERER_WEB_FRAME_METHOD, method, ...args); }; } const waitTillCanExecuteJavaScript = async (webContents: Electron.WebContents) => { if (webContents.getURL() && !webContents.isLoadingMainFrame()) return; return new Promise<void>((resolve) => { webContents.once('did-stop-loading', () => { resolve(); }); }); }; // Make sure WebContents::executeJavaScript would run the code only when the // WebContents has been loaded. WebContents.prototype.executeJavaScript = async function (code, hasUserGesture) { await waitTillCanExecuteJavaScript(this); return ipcMainUtils.invokeInWebContents(this, IPC_MESSAGES.RENDERER_WEB_FRAME_METHOD, 'executeJavaScript', String(code), !!hasUserGesture); }; WebContents.prototype.executeJavaScriptInIsolatedWorld = async function (worldId, code, hasUserGesture) { await waitTillCanExecuteJavaScript(this); return ipcMainUtils.invokeInWebContents(this, IPC_MESSAGES.RENDERER_WEB_FRAME_METHOD, 'executeJavaScriptInIsolatedWorld', worldId, code, !!hasUserGesture); }; // Translate the options of printToPDF. let pendingPromise: Promise<any> | undefined; WebContents.prototype.printToPDF = async function (options) { const printSettings: Record<string, any> = { ...defaultPrintingSetting, requestID: getNextId() }; if (options.landscape !== undefined) { if (typeof options.landscape !== 'boolean') { const error = new Error('landscape must be a Boolean'); return Promise.reject(error); } printSettings.landscape = options.landscape; } if (options.scaleFactor !== undefined) { if (typeof options.scaleFactor !== 'number') { const error = new Error('scaleFactor must be a Number'); return Promise.reject(error); } printSettings.scaleFactor = options.scaleFactor; } if (options.marginsType !== undefined) { if (typeof options.marginsType !== 'number') { const error = new Error('marginsType must be a Number'); return Promise.reject(error); } printSettings.marginsType = options.marginsType; } if (options.printSelectionOnly !== undefined) { if (typeof options.printSelectionOnly !== 'boolean') { const error = new Error('printSelectionOnly must be a Boolean'); return Promise.reject(error); } printSettings.shouldPrintSelectionOnly = options.printSelectionOnly; } if (options.printBackground !== undefined) { if (typeof options.printBackground !== 'boolean') { const error = new Error('printBackground must be a Boolean'); return Promise.reject(error); } printSettings.shouldPrintBackgrounds = options.printBackground; } if (options.pageRanges !== undefined) { const pageRanges = options.pageRanges; if (!Object.prototype.hasOwnProperty.call(pageRanges, 'from') || !Object.prototype.hasOwnProperty.call(pageRanges, 'to')) { const error = new Error('pageRanges must be an Object with \'from\' and \'to\' properties'); return Promise.reject(error); } if (typeof pageRanges.from !== 'number') { const error = new Error('pageRanges.from must be a Number'); return Promise.reject(error); } if (typeof pageRanges.to !== 'number') { const error = new Error('pageRanges.to must be a Number'); return Promise.reject(error); } // Chromium uses 1-based page ranges, so increment each by 1. printSettings.pageRange = [{ from: pageRanges.from + 1, to: pageRanges.to + 1 }]; } if (options.headerFooter !== undefined) { const headerFooter = options.headerFooter; printSettings.headerFooterEnabled = true; if (typeof headerFooter === 'object') { if (!headerFooter.url || !headerFooter.title) { const error = new Error('url and title properties are required for headerFooter'); return Promise.reject(error); } if (typeof headerFooter.title !== 'string') { const error = new Error('headerFooter.title must be a String'); return Promise.reject(error); } printSettings.title = headerFooter.title; if (typeof headerFooter.url !== 'string') { const error = new Error('headerFooter.url must be a String'); return Promise.reject(error); } printSettings.url = headerFooter.url; } else { const error = new Error('headerFooter must be an Object'); return Promise.reject(error); } } // Optionally set size for PDF. if (options.pageSize !== undefined) { const pageSize = options.pageSize; if (typeof pageSize === 'object') { if (!pageSize.height || !pageSize.width) { const error = new Error('height and width properties are required for pageSize'); return Promise.reject(error); } // Dimensions in Microns - 1 meter = 10^6 microns const height = Math.ceil(pageSize.height); const width = Math.ceil(pageSize.width); if (!isValidCustomPageSize(width, height)) { const error = new Error('height and width properties must be minimum 352 microns.'); return Promise.reject(error); } printSettings.mediaSize = { name: 'CUSTOM', custom_display_name: 'Custom', height_microns: height, width_microns: width }; } else if (Object.prototype.hasOwnProperty.call(PDFPageSizes, pageSize)) { printSettings.mediaSize = PDFPageSizes[pageSize]; } else { const error = new Error(`Unsupported pageSize: ${pageSize}`); return Promise.reject(error); } } else { printSettings.mediaSize = PDFPageSizes.A4; } // Chromium expects this in a 0-100 range number, not as float printSettings.scaleFactor = Math.ceil(printSettings.scaleFactor) % 100; // PrinterType enum from //printing/print_job_constants.h printSettings.printerType = 2; if (this._printToPDF) { if (pendingPromise) { pendingPromise = pendingPromise.then(() => this._printToPDF(printSettings)); } else { pendingPromise = this._printToPDF(printSettings); } return pendingPromise; } else { const error = new Error('Printing feature is disabled'); return Promise.reject(error); } }; WebContents.prototype.print = function (options: ElectronInternal.WebContentsPrintOptions = {}, callback) { // TODO(codebytere): deduplicate argument sanitization by moving rest of // print param logic into new file shared between printToPDF and print if (typeof options === 'object') { // Optionally set size for PDF. if (options.pageSize !== undefined) { const pageSize = options.pageSize; if (typeof pageSize === 'object') { if (!pageSize.height || !pageSize.width) { throw new Error('height and width properties are required for pageSize'); } // Dimensions in Microns - 1 meter = 10^6 microns const height = Math.ceil(pageSize.height); const width = Math.ceil(pageSize.width); if (!isValidCustomPageSize(width, height)) { throw new Error('height and width properties must be minimum 352 microns.'); } options.mediaSize = { name: 'CUSTOM', custom_display_name: 'Custom', height_microns: height, width_microns: width }; } else if (PDFPageSizes[pageSize]) { options.mediaSize = PDFPageSizes[pageSize]; } else { throw new Error(`Unsupported pageSize: ${pageSize}`); } } } if (this._print) { if (callback) { this._print(options, callback); } else { this._print(options); } } else { console.error('Error: Printing feature is disabled.'); } }; WebContents.prototype.getPrinters = function () { // TODO(nornagon): this API has nothing to do with WebContents and should be // moved. if (printing.getPrinterList) { return printing.getPrinterList(); } else { console.error('Error: Printing feature is disabled.'); return []; } }; WebContents.prototype.getPrintersAsync = async function () { // TODO(nornagon): this API has nothing to do with WebContents and should be // moved. if (printing.getPrinterListAsync) { return printing.getPrinterListAsync(); } else { console.error('Error: Printing feature is disabled.'); return []; } }; WebContents.prototype.loadFile = function (filePath, options = {}) { if (typeof filePath !== 'string') { throw new Error('Must pass filePath as a string'); } const { query, search, hash } = options; return this.loadURL(url.format({ protocol: 'file', slashes: true, pathname: path.resolve(app.getAppPath(), filePath), query, search, hash })); }; WebContents.prototype.loadURL = function (url, options) { if (!options) { options = {}; } const p = new Promise<void>((resolve, reject) => { const resolveAndCleanup = () => { removeListeners(); resolve(); }; const rejectAndCleanup = (errorCode: number, errorDescription: string, url: string) => { const err = new Error(`${errorDescription} (${errorCode}) loading '${typeof url === 'string' ? url.substr(0, 2048) : url}'`); Object.assign(err, { errno: errorCode, code: errorDescription, url }); removeListeners(); reject(err); }; const finishListener = () => { resolveAndCleanup(); }; const failListener = (event: Electron.Event, errorCode: number, errorDescription: string, validatedURL: string, isMainFrame: boolean) => { if (isMainFrame) { rejectAndCleanup(errorCode, errorDescription, validatedURL); } }; let navigationStarted = false; const navigationListener = (event: Electron.Event, url: string, isSameDocument: boolean, isMainFrame: boolean) => { if (isMainFrame) { if (navigationStarted && !isSameDocument) { // the webcontents has started another unrelated navigation in the // main frame (probably from the app calling `loadURL` again); reject // the promise // We should only consider the request aborted if the "navigation" is // actually navigating and not simply transitioning URL state in the // current context. E.g. pushState and `location.hash` changes are // considered navigation events but are triggered with isSameDocument. // We can ignore these to allow virtual routing on page load as long // as the routing does not leave the document return rejectAndCleanup(-3, 'ERR_ABORTED', url); } navigationStarted = true; } }; const stopLoadingListener = () => { // By the time we get here, either 'finish' or 'fail' should have fired // if the navigation occurred. However, in some situations (e.g. when // attempting to load a page with a bad scheme), loading will stop // without emitting finish or fail. In this case, we reject the promise // with a generic failure. // TODO(jeremy): enumerate all the cases in which this can happen. If // the only one is with a bad scheme, perhaps ERR_INVALID_ARGUMENT // would be more appropriate. rejectAndCleanup(-2, 'ERR_FAILED', url); }; const removeListeners = () => { this.removeListener('did-finish-load', finishListener); this.removeListener('did-fail-load', failListener); this.removeListener('did-start-navigation', navigationListener); this.removeListener('did-stop-loading', stopLoadingListener); this.removeListener('destroyed', stopLoadingListener); }; this.on('did-finish-load', finishListener); this.on('did-fail-load', failListener); this.on('did-start-navigation', navigationListener); this.on('did-stop-loading', stopLoadingListener); this.on('destroyed', stopLoadingListener); }); // Add a no-op rejection handler to silence the unhandled rejection error. p.catch(() => {}); this._loadURL(url, options); this.emit('load-url', url, options); return p; }; WebContents.prototype.setWindowOpenHandler = function (handler: (details: Electron.HandlerDetails) => ({action: 'deny'} | {action: 'allow', overrideBrowserWindowOptions?: BrowserWindowConstructorOptions, outlivesOpener?: boolean})) { this._windowOpenHandler = handler; }; WebContents.prototype._callWindowOpenHandler = function (event: Electron.Event, details: Electron.HandlerDetails): {browserWindowConstructorOptions: BrowserWindowConstructorOptions | null, outlivesOpener: boolean} { const defaultResponse = { browserWindowConstructorOptions: null, outlivesOpener: false }; if (!this._windowOpenHandler) { return defaultResponse; } const response = this._windowOpenHandler(details); if (typeof response !== 'object') { event.preventDefault(); console.error(`The window open handler response must be an object, but was instead of type '${typeof response}'.`); return defaultResponse; } if (response === null) { event.preventDefault(); console.error('The window open handler response must be an object, but was instead null.'); return defaultResponse; } if (response.action === 'deny') { event.preventDefault(); return defaultResponse; } else if (response.action === 'allow') { if (typeof response.overrideBrowserWindowOptions === 'object' && response.overrideBrowserWindowOptions !== null) { return { browserWindowConstructorOptions: response.overrideBrowserWindowOptions, outlivesOpener: typeof response.outlivesOpener === 'boolean' ? response.outlivesOpener : false }; } else { return { browserWindowConstructorOptions: {}, outlivesOpener: typeof response.outlivesOpener === 'boolean' ? response.outlivesOpener : false }; } } else { event.preventDefault(); console.error('The window open handler response must be an object with an \'action\' property of \'allow\' or \'deny\'.'); return defaultResponse; } }; const addReplyToEvent = (event: Electron.IpcMainEvent) => { const { processId, frameId } = event; event.reply = (channel: string, ...args: any[]) => { event.sender.sendToFrame([processId, frameId], channel, ...args); }; }; const addSenderFrameToEvent = (event: Electron.IpcMainEvent | Electron.IpcMainInvokeEvent) => { const { processId, frameId } = event; Object.defineProperty(event, 'senderFrame', { get: () => webFrameMain.fromId(processId, frameId) }); }; const addReturnValueToEvent = (event: Electron.IpcMainEvent) => { Object.defineProperty(event, 'returnValue', { set: (value) => event.sendReply(value), get: () => {} }); }; const commandLine = process._linkedBinding('electron_common_command_line'); const environment = process._linkedBinding('electron_common_environment'); const loggingEnabled = () => { return environment.hasVar('ELECTRON_ENABLE_LOGGING') || commandLine.hasSwitch('enable-logging'); }; // Add JavaScript wrappers for WebContents class. WebContents.prototype._init = function () { const prefs = this.getLastWebPreferences() || {}; if (!prefs.nodeIntegration && prefs.preload != null && prefs.sandbox == null) { deprecate.log('The default sandbox option for windows without nodeIntegration is changing. Presently, by default, when a window has a preload script, it defaults to being unsandboxed. In Electron 20, this default will be changing, and all windows that have nodeIntegration: false (which is the default) will be sandboxed by default. If your preload script doesn\'t use Node, no action is needed. If your preload script does use Node, either refactor it to move Node usage to the main process, or specify sandbox: false in your WebPreferences.'); } // Read off the ID at construction time, so that it's accessible even after // the underlying C++ WebContents is destroyed. const id = this.id; Object.defineProperty(this, 'id', { value: id, writable: false }); this._windowOpenHandler = null; // Dispatch IPC messages to the ipc module. this.on('-ipc-message' as any, function (this: Electron.WebContents, event: Electron.IpcMainEvent, internal: boolean, channel: string, args: any[]) { addSenderFrameToEvent(event); if (internal) { ipcMainInternal.emit(channel, event, ...args); } else { addReplyToEvent(event); this.emit('ipc-message', event, channel, ...args); ipcMain.emit(channel, event, ...args); } }); this.on('-ipc-invoke' as any, function (event: Electron.IpcMainInvokeEvent, internal: boolean, channel: string, args: any[]) { addSenderFrameToEvent(event); event._reply = (result: any) => event.sendReply({ result }); event._throw = (error: Error) => { console.error(`Error occurred in handler for '${channel}':`, error); event.sendReply({ error: error.toString() }); }; const target = internal ? ipcMainInternal : ipcMain; if ((target as any)._invokeHandlers.has(channel)) { (target as any)._invokeHandlers.get(channel)(event, ...args); } else { event._throw(`No handler registered for '${channel}'`); } }); this.on('-ipc-message-sync' as any, function (this: Electron.WebContents, event: Electron.IpcMainEvent, internal: boolean, channel: string, args: any[]) { addSenderFrameToEvent(event); addReturnValueToEvent(event); if (internal) { ipcMainInternal.emit(channel, event, ...args); } else { addReplyToEvent(event); if (this.listenerCount('ipc-message-sync') === 0 && ipcMain.listenerCount(channel) === 0) { console.warn(`WebContents #${this.id} called ipcRenderer.sendSync() with '${channel}' channel without listeners.`); } this.emit('ipc-message-sync', event, channel, ...args); ipcMain.emit(channel, event, ...args); } }); this.on('-ipc-ports' as any, function (event: Electron.IpcMainEvent, internal: boolean, channel: string, message: any, ports: any[]) { event.ports = ports.map(p => new MessagePortMain(p)); ipcMain.emit(channel, event, message); }); this.on('crashed', (event, ...args) => { app.emit('renderer-process-crashed', event, this, ...args); }); this.on('render-process-gone', (event, details) => { app.emit('render-process-gone', event, this, details); // Log out a hint to help users better debug renderer crashes. if (loggingEnabled()) { console.info(`Renderer process ${details.reason} - see https://www.electronjs.org/docs/tutorial/application-debugging for potential debugging information.`); } }); // The devtools requests the webContents to reload. this.on('devtools-reload-page', function (this: Electron.WebContents) { this.reload(); }); if (this.getType() !== 'remote') { // Make new windows requested by links behave like "window.open". this.on('-new-window' as any, (event: ElectronInternal.Event, url: string, frameName: string, disposition: Electron.HandlerDetails['disposition'], rawFeatures: string, referrer: Electron.Referrer, postData: PostData) => { const postBody = postData ? { data: postData, ...parseContentTypeFormat(postData) } : undefined; const details: Electron.HandlerDetails = { url, frameName, features: rawFeatures, referrer, postBody, disposition }; const result = this._callWindowOpenHandler(event, details); const options = result.browserWindowConstructorOptions; if (!event.defaultPrevented) { openGuestWindow({ event, embedder: event.sender, disposition, referrer, postData, overrideBrowserWindowOptions: options || {}, windowOpenArgs: details, outlivesOpener: result.outlivesOpener }); } }); let windowOpenOverriddenOptions: BrowserWindowConstructorOptions | null = null; let windowOpenOutlivesOpenerOption: boolean = false; this.on('-will-add-new-contents' as any, (event: ElectronInternal.Event, url: string, frameName: string, rawFeatures: string, disposition: Electron.HandlerDetails['disposition'], referrer: Electron.Referrer, postData: PostData) => { const postBody = postData ? { data: postData, ...parseContentTypeFormat(postData) } : undefined; const details: Electron.HandlerDetails = { url, frameName, features: rawFeatures, disposition, referrer, postBody }; const result = this._callWindowOpenHandler(event, details); windowOpenOutlivesOpenerOption = result.outlivesOpener; windowOpenOverriddenOptions = result.browserWindowConstructorOptions; if (!event.defaultPrevented) { const secureOverrideWebPreferences = windowOpenOverriddenOptions ? { // Allow setting of backgroundColor as a webPreference even though // it's technically a BrowserWindowConstructorOptions option because // we need to access it in the renderer at init time. backgroundColor: windowOpenOverriddenOptions.backgroundColor, transparent: windowOpenOverriddenOptions.transparent, ...windowOpenOverriddenOptions.webPreferences } : undefined; // TODO(zcbenz): The features string is parsed twice: here where it is // passed to C++, and in |makeBrowserWindowOptions| later where it is // not actually used since the WebContents is created here. // We should be able to remove the latter once the |new-window| event // is removed. const { webPreferences: parsedWebPreferences } = parseFeatures(rawFeatures); // Parameters should keep same with |makeBrowserWindowOptions|. const webPreferences = makeWebPreferences({ embedder: event.sender, insecureParsedWebPreferences: parsedWebPreferences, secureOverrideWebPreferences }); this._setNextChildWebPreferences(webPreferences); } }); // Create a new browser window for "window.open" this.on('-add-new-contents' as any, (event: ElectronInternal.Event, webContents: Electron.WebContents, disposition: string, _userGesture: boolean, _left: number, _top: number, _width: number, _height: number, url: string, frameName: string, referrer: Electron.Referrer, rawFeatures: string, postData: PostData) => { const overriddenOptions = windowOpenOverriddenOptions || undefined; const outlivesOpener = windowOpenOutlivesOpenerOption; windowOpenOverriddenOptions = null; // false is the default windowOpenOutlivesOpenerOption = false; if ((disposition !== 'foreground-tab' && disposition !== 'new-window' && disposition !== 'background-tab')) { event.preventDefault(); return; } openGuestWindow({ event, embedder: event.sender, guest: webContents, overrideBrowserWindowOptions: overriddenOptions, disposition, referrer, postData, windowOpenArgs: { url, frameName, features: rawFeatures }, outlivesOpener }); }); } this.on('login', (event, ...args) => { app.emit('login', event, this, ...args); }); this.on('ready-to-show' as any, () => { const owner = this.getOwnerBrowserWindow(); if (owner && !owner.isDestroyed()) { process.nextTick(() => { owner.emit('ready-to-show'); }); } }); this.on('select-bluetooth-device', (event, devices, callback) => { if (this.listenerCount('select-bluetooth-device') === 1) { // Cancel it if there are no handlers event.preventDefault(); callback(''); } }); const event = process._linkedBinding('electron_browser_event').createEmpty(); app.emit('web-contents-created', event, this); // Properties Object.defineProperty(this, 'audioMuted', { get: () => this.isAudioMuted(), set: (muted) => this.setAudioMuted(muted) }); Object.defineProperty(this, 'userAgent', { get: () => this.getUserAgent(), set: (agent) => this.setUserAgent(agent) }); Object.defineProperty(this, 'zoomLevel', { get: () => this.getZoomLevel(), set: (level) => this.setZoomLevel(level) }); Object.defineProperty(this, 'zoomFactor', { get: () => this.getZoomFactor(), set: (factor) => this.setZoomFactor(factor) }); Object.defineProperty(this, 'frameRate', { get: () => this.getFrameRate(), set: (rate) => this.setFrameRate(rate) }); Object.defineProperty(this, 'backgroundThrottling', { get: () => this.getBackgroundThrottling(), set: (allowed) => this.setBackgroundThrottling(allowed) }); }; // Public APIs. export function create (options = {}): Electron.WebContents { return new (WebContents as any)(options); } export function fromId (id: string) { return binding.fromId(id); } export function fromDevToolsTargetId (targetId: string) { return binding.fromDevToolsTargetId(targetId); } export function getFocusedWebContents () { let focused = null; for (const contents of binding.getAllWebContents()) { if (!contents.isFocused()) continue; if (focused == null) focused = contents; // Return webview web contents which may be embedded inside another // web contents that is also reporting as focused if (contents.getType() === 'webview') return contents; } return focused; } export function getAllWebContents () { return binding.getAllWebContents(); }
closed
electron/electron
https://github.com/electron/electron
33,722
[Bug]: `ipcRenderer.postMessage` results in `undefined` for `event.senderFrame` in browser process
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.x ### What operating system are you using? macOS ### Operating System Version 12.3.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior The `IpcMainEvent.senderFrame` is always defined. ### Actual Behavior The `IpcMainEvent.senderFrame` is `undefined` when `postMessage` is used. ### Testcase Gist URL _No response_ ### Additional Information Install a handler in browser process: ```js ipcMain.on('vscode:postMessage', (event => { console.log('vscode:postMessage', event.senderFrame); })); ``` And from the `preload.js` script simply run this code: ```js ipcRenderer.postMessage('vscode:postMessage', 'message'); ``` //cc @deepak1556
https://github.com/electron/electron/issues/33722
https://github.com/electron/electron/pull/33756
3d4d39d67b072a7c355dada2881cb6791e9e9f53
16f8d713ab05fe325a664f0fd79cb41c403c9755
2022-04-12T05:54:33Z
c++
2022-04-14T04:01:00Z
spec-main/api-ipc-spec.ts
import { EventEmitter } from 'events'; import { expect } from 'chai'; import { BrowserWindow, ipcMain, IpcMainInvokeEvent, MessageChannelMain, WebContents } from 'electron/main'; import { closeAllWindows } from './window-helpers'; import { emittedOnce } from './events-helpers'; const v8Util = process._linkedBinding('electron_common_v8_util'); describe('ipc module', () => { describe('invoke', () => { let w = (null as unknown as BrowserWindow); before(async () => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); await w.loadURL('about:blank'); }); after(async () => { w.destroy(); }); async function rendererInvoke (...args: any[]) { const { ipcRenderer } = require('electron'); try { const result = await ipcRenderer.invoke('test', ...args); ipcRenderer.send('result', { result }); } catch (e) { ipcRenderer.send('result', { error: (e as Error).message }); } } it('receives a response from a synchronous handler', async () => { ipcMain.handleOnce('test', (e: IpcMainInvokeEvent, arg: number) => { expect(arg).to.equal(123); return 3; }); const done = new Promise<void>(resolve => ipcMain.once('result', (e, arg) => { expect(arg).to.deep.equal({ result: 3 }); resolve(); })); await w.webContents.executeJavaScript(`(${rendererInvoke})(123)`); await done; }); it('receives a response from an asynchronous handler', async () => { ipcMain.handleOnce('test', async (e: IpcMainInvokeEvent, arg: number) => { expect(arg).to.equal(123); await new Promise(setImmediate); return 3; }); const done = new Promise<void>(resolve => ipcMain.once('result', (e, arg) => { expect(arg).to.deep.equal({ result: 3 }); resolve(); })); await w.webContents.executeJavaScript(`(${rendererInvoke})(123)`); await done; }); it('receives an error from a synchronous handler', async () => { ipcMain.handleOnce('test', () => { throw new Error('some error'); }); const done = new Promise<void>(resolve => ipcMain.once('result', (e, arg) => { expect(arg.error).to.match(/some error/); resolve(); })); await w.webContents.executeJavaScript(`(${rendererInvoke})()`); await done; }); it('receives an error from an asynchronous handler', async () => { ipcMain.handleOnce('test', async () => { await new Promise(setImmediate); throw new Error('some error'); }); const done = new Promise<void>(resolve => ipcMain.once('result', (e, arg) => { expect(arg.error).to.match(/some error/); resolve(); })); await w.webContents.executeJavaScript(`(${rendererInvoke})()`); await done; }); it('throws an error if no handler is registered', async () => { const done = new Promise<void>(resolve => ipcMain.once('result', (e, arg) => { expect(arg.error).to.match(/No handler registered/); resolve(); })); await w.webContents.executeJavaScript(`(${rendererInvoke})()`); await done; }); it('throws an error when invoking a handler that was removed', async () => { ipcMain.handle('test', () => {}); ipcMain.removeHandler('test'); const done = new Promise<void>(resolve => ipcMain.once('result', (e, arg) => { expect(arg.error).to.match(/No handler registered/); resolve(); })); await w.webContents.executeJavaScript(`(${rendererInvoke})()`); await done; }); it('forbids multiple handlers', async () => { ipcMain.handle('test', () => {}); try { expect(() => { ipcMain.handle('test', () => {}); }).to.throw(/second handler/); } finally { ipcMain.removeHandler('test'); } }); it('throws an error in the renderer if the reply callback is dropped', async () => { // eslint-disable-next-line @typescript-eslint/no-unused-vars ipcMain.handleOnce('test', () => new Promise(resolve => { setTimeout(() => v8Util.requestGarbageCollectionForTesting()); /* never resolve */ })); w.webContents.executeJavaScript(`(${rendererInvoke})()`); const [, { error }] = await emittedOnce(ipcMain, 'result'); expect(error).to.match(/reply was never sent/); }); }); describe('ordering', () => { let w = (null as unknown as BrowserWindow); before(async () => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); await w.loadURL('about:blank'); }); after(async () => { w.destroy(); }); it('between send and sendSync is consistent', async () => { const received: number[] = []; ipcMain.on('test-async', (e, i) => { received.push(i); }); ipcMain.on('test-sync', (e, i) => { received.push(i); e.returnValue = null; }); const done = new Promise<void>(resolve => ipcMain.once('done', () => { resolve(); })); function rendererStressTest () { const { ipcRenderer } = require('electron'); for (let i = 0; i < 1000; i++) { switch ((Math.random() * 2) | 0) { case 0: ipcRenderer.send('test-async', i); break; case 1: ipcRenderer.sendSync('test-sync', i); break; } } ipcRenderer.send('done'); } try { w.webContents.executeJavaScript(`(${rendererStressTest})()`); await done; } finally { ipcMain.removeAllListeners('test-async'); ipcMain.removeAllListeners('test-sync'); } expect(received).to.have.lengthOf(1000); expect(received).to.deep.equal([...received].sort((a, b) => a - b)); }); it('between send, sendSync, and invoke is consistent', async () => { const received: number[] = []; ipcMain.handle('test-invoke', (e, i) => { received.push(i); }); ipcMain.on('test-async', (e, i) => { received.push(i); }); ipcMain.on('test-sync', (e, i) => { received.push(i); e.returnValue = null; }); const done = new Promise<void>(resolve => ipcMain.once('done', () => { resolve(); })); function rendererStressTest () { const { ipcRenderer } = require('electron'); for (let i = 0; i < 1000; i++) { switch ((Math.random() * 3) | 0) { case 0: ipcRenderer.send('test-async', i); break; case 1: ipcRenderer.sendSync('test-sync', i); break; case 2: ipcRenderer.invoke('test-invoke', i); break; } } ipcRenderer.send('done'); } try { w.webContents.executeJavaScript(`(${rendererStressTest})()`); await done; } finally { ipcMain.removeHandler('test-invoke'); ipcMain.removeAllListeners('test-async'); ipcMain.removeAllListeners('test-sync'); } expect(received).to.have.lengthOf(1000); expect(received).to.deep.equal([...received].sort((a, b) => a - b)); }); }); describe('MessagePort', () => { afterEach(closeAllWindows); it('can send a port to the main process', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadURL('about:blank'); const p = emittedOnce(ipcMain, 'port'); await w.webContents.executeJavaScript(`(${function () { const channel = new MessageChannel(); require('electron').ipcRenderer.postMessage('port', 'hi', [channel.port1]); }})()`); const [ev, msg] = await p; expect(msg).to.equal('hi'); expect(ev.ports).to.have.length(1); const [port] = ev.ports; expect(port).to.be.an.instanceOf(EventEmitter); }); it('can sent a message without a transfer', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadURL('about:blank'); const p = emittedOnce(ipcMain, 'port'); await w.webContents.executeJavaScript(`(${function () { require('electron').ipcRenderer.postMessage('port', 'hi'); }})()`); const [ev, msg] = await p; expect(msg).to.equal('hi'); expect(ev.ports).to.deep.equal([]); }); it('can communicate between main and renderer', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadURL('about:blank'); const p = emittedOnce(ipcMain, 'port'); await w.webContents.executeJavaScript(`(${function () { const channel = new MessageChannel(); (channel.port2 as any).onmessage = (ev: any) => { channel.port2.postMessage(ev.data * 2); }; require('electron').ipcRenderer.postMessage('port', '', [channel.port1]); }})()`); const [ev] = await p; expect(ev.ports).to.have.length(1); const [port] = ev.ports; port.start(); port.postMessage(42); const [ev2] = await emittedOnce(port, 'message'); expect(ev2.data).to.equal(84); }); it('can receive a port from a renderer over a MessagePort connection', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadURL('about:blank'); function fn () { const channel1 = new MessageChannel(); const channel2 = new MessageChannel(); channel1.port2.postMessage('', [channel2.port1]); channel2.port2.postMessage('matryoshka'); require('electron').ipcRenderer.postMessage('port', '', [channel1.port1]); } w.webContents.executeJavaScript(`(${fn})()`); const [{ ports: [port1] }] = await emittedOnce(ipcMain, 'port'); port1.start(); const [{ ports: [port2] }] = await emittedOnce(port1, 'message'); port2.start(); const [{ data }] = await emittedOnce(port2, 'message'); expect(data).to.equal('matryoshka'); }); it('can forward a port from one renderer to another renderer', async () => { const w1 = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); const w2 = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w1.loadURL('about:blank'); w2.loadURL('about:blank'); w1.webContents.executeJavaScript(`(${function () { const channel = new MessageChannel(); (channel.port2 as any).onmessage = (ev: any) => { require('electron').ipcRenderer.send('message received', ev.data); }; require('electron').ipcRenderer.postMessage('port', '', [channel.port1]); }})()`); const [{ ports: [port] }] = await emittedOnce(ipcMain, 'port'); await w2.webContents.executeJavaScript(`(${function () { require('electron').ipcRenderer.on('port', ({ ports: [port] }: any) => { port.postMessage('a message'); }); }})()`); w2.webContents.postMessage('port', '', [port]); const [, data] = await emittedOnce(ipcMain, 'message received'); expect(data).to.equal('a message'); }); describe('close event', () => { describe('in renderer', () => { it('is emitted when the main process closes its end of the port', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadURL('about:blank'); await w.webContents.executeJavaScript(`(${function () { const { ipcRenderer } = require('electron'); ipcRenderer.on('port', e => { const [port] = e.ports; port.start(); (port as any).onclose = () => { ipcRenderer.send('closed'); }; }); }})()`); const { port1, port2 } = new MessageChannelMain(); w.webContents.postMessage('port', null, [port2]); port1.close(); await emittedOnce(ipcMain, 'closed'); }); it('is emitted when the other end of a port is garbage-collected', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadURL('about:blank'); await w.webContents.executeJavaScript(`(${async function () { const { port2 } = new MessageChannel(); await new Promise(resolve => { port2.start(); (port2 as any).onclose = resolve; process._linkedBinding('electron_common_v8_util').requestGarbageCollectionForTesting(); }); }})()`); }); it('is emitted when the other end of a port is sent to nowhere', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadURL('about:blank'); ipcMain.once('do-a-gc', () => v8Util.requestGarbageCollectionForTesting()); await w.webContents.executeJavaScript(`(${async function () { const { port1, port2 } = new MessageChannel(); await new Promise(resolve => { port2.start(); (port2 as any).onclose = resolve; require('electron').ipcRenderer.postMessage('nobody-listening', null, [port1]); require('electron').ipcRenderer.send('do-a-gc'); }); }})()`); }); }); }); describe('MessageChannelMain', () => { it('can be created', () => { const { port1, port2 } = new MessageChannelMain(); expect(port1).not.to.be.null(); expect(port2).not.to.be.null(); }); it('can send messages within the process', async () => { const { port1, port2 } = new MessageChannelMain(); port2.postMessage('hello'); port1.start(); const [ev] = await emittedOnce(port1, 'message'); expect(ev.data).to.equal('hello'); }); it('can pass one end to a WebContents', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadURL('about:blank'); await w.webContents.executeJavaScript(`(${function () { const { ipcRenderer } = require('electron'); ipcRenderer.on('port', ev => { const [port] = ev.ports; port.onmessage = () => { ipcRenderer.send('done'); }; }); }})()`); const { port1, port2 } = new MessageChannelMain(); port1.postMessage('hello'); w.webContents.postMessage('port', null, [port2]); await emittedOnce(ipcMain, 'done'); }); it('can be passed over another channel', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadURL('about:blank'); await w.webContents.executeJavaScript(`(${function () { const { ipcRenderer } = require('electron'); ipcRenderer.on('port', e1 => { e1.ports[0].onmessage = e2 => { e2.ports[0].onmessage = e3 => { ipcRenderer.send('done', e3.data); }; }; }); }})()`); const { port1, port2 } = new MessageChannelMain(); const { port1: port3, port2: port4 } = new MessageChannelMain(); port1.postMessage(null, [port4]); port3.postMessage('hello'); w.webContents.postMessage('port', null, [port2]); const [, message] = await emittedOnce(ipcMain, 'done'); expect(message).to.equal('hello'); }); it('can send messages to a closed port', () => { const { port1, port2 } = new MessageChannelMain(); port2.start(); port2.on('message', () => { throw new Error('unexpected message received'); }); port1.close(); port1.postMessage('hello'); }); it('can send messages to a port whose remote end is closed', () => { const { port1, port2 } = new MessageChannelMain(); port2.start(); port2.on('message', () => { throw new Error('unexpected message received'); }); port2.close(); port1.postMessage('hello'); }); it('throws when passing null ports', () => { const { port1 } = new MessageChannelMain(); expect(() => { port1.postMessage(null, [null] as any); }).to.throw(/conversion failure/); }); it('throws when passing duplicate ports', () => { const { port1 } = new MessageChannelMain(); const { port1: port3 } = new MessageChannelMain(); expect(() => { port1.postMessage(null, [port3, port3]); }).to.throw(/duplicate/); }); it('throws when passing ports that have already been neutered', () => { const { port1 } = new MessageChannelMain(); const { port1: port3 } = new MessageChannelMain(); port1.postMessage(null, [port3]); expect(() => { port1.postMessage(null, [port3]); }).to.throw(/already neutered/); }); it('throws when passing itself', () => { const { port1 } = new MessageChannelMain(); expect(() => { port1.postMessage(null, [port1]); }).to.throw(/contains the source port/); }); describe('GC behavior', () => { it('is not collected while it could still receive messages', async () => { let trigger: Function; const promise = new Promise(resolve => { trigger = resolve; }); const port1 = (() => { const { port1, port2 } = new MessageChannelMain(); port2.on('message', (e) => { trigger(e.data); }); port2.start(); return port1; })(); v8Util.requestGarbageCollectionForTesting(); port1.postMessage('hello'); expect(await promise).to.equal('hello'); }); }); }); const generateTests = (title: string, postMessage: (contents: WebContents) => WebContents['postMessage']) => { describe(title, () => { it('sends a message', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadURL('about:blank'); await w.webContents.executeJavaScript(`(${function () { const { ipcRenderer } = require('electron'); ipcRenderer.on('foo', (_e, msg) => { ipcRenderer.send('bar', msg); }); }})()`); postMessage(w.webContents)('foo', { some: 'message' }); const [, msg] = await emittedOnce(ipcMain, 'bar'); expect(msg).to.deep.equal({ some: 'message' }); }); describe('error handling', () => { it('throws on missing channel', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); expect(() => { (postMessage(w.webContents) as any)(); }).to.throw(/Insufficient number of arguments/); }); it('throws on invalid channel', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); expect(() => { postMessage(w.webContents)(null as any, '', []); }).to.throw(/Error processing argument at index 0/); }); it('throws on missing message', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); expect(() => { (postMessage(w.webContents) as any)('channel'); }).to.throw(/Insufficient number of arguments/); }); it('throws on non-serializable message', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); expect(() => { postMessage(w.webContents)('channel', w); }).to.throw(/An object could not be cloned/); }); it('throws on invalid transferable list', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); expect(() => { postMessage(w.webContents)('', '', null as any); }).to.throw(/Invalid value for transfer/); }); it('throws on transferring non-transferable', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); expect(() => { (postMessage(w.webContents) as any)('channel', '', [123]); }).to.throw(/Invalid value for transfer/); }); it('throws when passing null ports', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); expect(() => { postMessage(w.webContents)('foo', null, [null] as any); }).to.throw(/Invalid value for transfer/); }); it('throws when passing duplicate ports', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const { port1 } = new MessageChannelMain(); expect(() => { postMessage(w.webContents)('foo', null, [port1, port1]); }).to.throw(/duplicate/); }); it('throws when passing ports that have already been neutered', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const { port1 } = new MessageChannelMain(); postMessage(w.webContents)('foo', null, [port1]); expect(() => { postMessage(w.webContents)('foo', null, [port1]); }).to.throw(/already neutered/); }); }); }); }; generateTests('WebContents.postMessage', contents => contents.postMessage.bind(contents)); generateTests('WebFrameMain.postMessage', contents => contents.mainFrame.postMessage.bind(contents.mainFrame)); }); });
closed
electron/electron
https://github.com/electron/electron
33,721
[Bug]: After entering and exiting Fullscreen, pressing [Esc] no longer works
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 18.0.3 ### What operating system are you using? Windows ### Operating System Version Windows 10 ### What arch are you using? x64 ### Last Known Working Electron version 18.0.0 ### Expected Behavior After entering and exiting fullscreen from an iframe and then focusing the parent page, <kbd>Escape</kbd> key events should be delivered to the parent page. ### Actual Behavior <kbd>Escape</kbd> key events seem not to be delivered to the page after exiting fullscreen. https://user-images.githubusercontent.com/172800/162848678-c067d18a-e323-49ea-a6b3-f1526149cad1.mp4 ### Testcase Gist URL https://gist.github.com/bc382eeeb368b70fbed1e177bcaacfde ### Additional Information This only reproduces on Windows, not on macOS. Also, this only reproduces when _clicking_ the "exit fullscreen" button in the YouTube embed. Pressing <kbd>Esc</kbd> to exit fullscreen allows the parent page to receive subsequent key events. 18.0.0 - not reproducible 18.0.1 - reproducible 18.0.2 - reproducible 18.0.3 - reproducible This seems likely to be related to https://github.com/electron/electron/pull/32369. cc @codebytere
https://github.com/electron/electron/issues/33721
https://github.com/electron/electron/pull/33757
7658edfa1abb0ce9713e4848d1c1af15f8cac479
233a39dbc9e07f5620798323309a2d065a27c21b
2022-04-11T23:32:00Z
c++
2022-04-14T10:35:36Z
shell/browser/api/electron_api_web_contents.cc
// Copyright (c) 2014 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/api/electron_api_web_contents.h" #include <limits> #include <memory> #include <set> #include <string> #include <unordered_set> #include <utility> #include <vector> #include "base/containers/id_map.h" #include "base/files/file_util.h" #include "base/json/json_reader.h" #include "base/no_destructor.h" #include "base/strings/utf_string_conversions.h" #include "base/task/current_thread.h" #include "base/task/post_task.h" #include "base/task/thread_pool.h" #include "base/threading/scoped_blocking_call.h" #include "base/threading/sequenced_task_runner_handle.h" #include "base/threading/thread_restrictions.h" #include "base/threading/thread_task_runner_handle.h" #include "base/values.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/ui/exclusive_access/exclusive_access_manager.h" #include "chrome/browser/ui/views/eye_dropper/eye_dropper.h" #include "chrome/common/pref_names.h" #include "components/prefs/pref_service.h" #include "components/prefs/scoped_user_pref_update.h" #include "components/security_state/content/content_utils.h" #include "components/security_state/core/security_state.h" #include "content/browser/renderer_host/frame_tree_node.h" // nogncheck #include "content/browser/renderer_host/render_frame_host_manager.h" // nogncheck #include "content/browser/renderer_host/render_widget_host_impl.h" // nogncheck #include "content/browser/renderer_host/render_widget_host_view_base.h" // nogncheck #include "content/public/browser/child_process_security_policy.h" #include "content/public/browser/context_menu_params.h" #include "content/public/browser/desktop_media_id.h" #include "content/public/browser/desktop_streams_registry.h" #include "content/public/browser/download_request_utils.h" #include "content/public/browser/favicon_status.h" #include "content/public/browser/file_select_listener.h" #include "content/public/browser/native_web_keyboard_event.h" #include "content/public/browser/navigation_details.h" #include "content/public/browser/navigation_entry.h" #include "content/public/browser/navigation_handle.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/render_widget_host.h" #include "content/public/browser/render_widget_host_view.h" #include "content/public/browser/service_worker_context.h" #include "content/public/browser/site_instance.h" #include "content/public/browser/storage_partition.h" #include "content/public/browser/web_contents.h" #include "content/public/common/referrer_type_converters.h" #include "content/public/common/webplugininfo.h" #include "electron/buildflags/buildflags.h" #include "electron/shell/common/api/api.mojom.h" #include "gin/arguments.h" #include "gin/data_object_builder.h" #include "gin/handle.h" #include "gin/object_template_builder.h" #include "gin/wrappable.h" #include "mojo/public/cpp/bindings/associated_remote.h" #include "mojo/public/cpp/bindings/pending_receiver.h" #include "mojo/public/cpp/bindings/remote.h" #include "mojo/public/cpp/system/platform_handle.h" #include "ppapi/buildflags/buildflags.h" #include "printing/buildflags/buildflags.h" #include "printing/print_job_constants.h" #include "services/resource_coordinator/public/cpp/memory_instrumentation/memory_instrumentation.h" #include "services/service_manager/public/cpp/interface_provider.h" #include "shell/browser/api/electron_api_browser_window.h" #include "shell/browser/api/electron_api_debugger.h" #include "shell/browser/api/electron_api_session.h" #include "shell/browser/api/electron_api_web_frame_main.h" #include "shell/browser/api/message_port.h" #include "shell/browser/browser.h" #include "shell/browser/child_web_contents_tracker.h" #include "shell/browser/electron_autofill_driver_factory.h" #include "shell/browser/electron_browser_client.h" #include "shell/browser/electron_browser_context.h" #include "shell/browser/electron_browser_main_parts.h" #include "shell/browser/electron_javascript_dialog_manager.h" #include "shell/browser/electron_navigation_throttle.h" #include "shell/browser/file_select_helper.h" #include "shell/browser/native_window.h" #include "shell/browser/session_preferences.h" #include "shell/browser/ui/drag_util.h" #include "shell/browser/ui/file_dialog.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/ui/inspectable_web_contents_view.h" #include "shell/browser/web_contents_permission_helper.h" #include "shell/browser/web_contents_preferences.h" #include "shell/browser/web_contents_zoom_controller.h" #include "shell/browser/web_view_guest_delegate.h" #include "shell/browser/web_view_manager.h" #include "shell/common/api/electron_api_native_image.h" #include "shell/common/api/electron_bindings.h" #include "shell/common/color_util.h" #include "shell/common/electron_constants.h" #include "shell/common/gin_converters/base_converter.h" #include "shell/common/gin_converters/blink_converter.h" #include "shell/common/gin_converters/callback_converter.h" #include "shell/common/gin_converters/content_converter.h" #include "shell/common/gin_converters/file_path_converter.h" #include "shell/common/gin_converters/frame_converter.h" #include "shell/common/gin_converters/gfx_converter.h" #include "shell/common/gin_converters/gurl_converter.h" #include "shell/common/gin_converters/image_converter.h" #include "shell/common/gin_converters/net_converter.h" #include "shell/common/gin_converters/value_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/gin_helper/object_template_builder.h" #include "shell/common/language_util.h" #include "shell/common/mouse_util.h" #include "shell/common/node_includes.h" #include "shell/common/options_switches.h" #include "shell/common/process_util.h" #include "shell/common/v8_value_serializer.h" #include "storage/browser/file_system/isolated_context.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h" #include "third_party/blink/public/common/input/web_input_event.h" #include "third_party/blink/public/common/messaging/transferable_message_mojom_traits.h" #include "third_party/blink/public/common/page/page_zoom.h" #include "third_party/blink/public/mojom/frame/find_in_page.mojom.h" #include "third_party/blink/public/mojom/frame/fullscreen.mojom.h" #include "third_party/blink/public/mojom/messaging/transferable_message.mojom.h" #include "third_party/blink/public/mojom/renderer_preferences.mojom.h" #include "ui/base/cursor/cursor.h" #include "ui/base/cursor/mojom/cursor_type.mojom-shared.h" #include "ui/display/screen.h" #include "ui/events/base_event_utils.h" #if BUILDFLAG(ENABLE_OSR) #include "shell/browser/osr/osr_render_widget_host_view.h" #include "shell/browser/osr/osr_web_contents_view.h" #endif #if !BUILDFLAG(IS_MAC) #include "ui/aura/window.h" #else #include "ui/base/cocoa/defaults_utils.h" #endif #if BUILDFLAG(IS_LINUX) #include "ui/views/linux_ui/linux_ui.h" #endif #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_WIN) #include "ui/gfx/font_render_params.h" #endif #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #include "extensions/browser/script_executor.h" #include "extensions/browser/view_type_utils.h" #include "extensions/common/mojom/view_type.mojom.h" #include "shell/browser/extensions/electron_extension_web_contents_observer.h" #endif #if BUILDFLAG(ENABLE_PRINTING) #include "components/printing/browser/print_manager_utils.h" #include "printing/backend/print_backend.h" // nogncheck #include "printing/mojom/print.mojom.h" // nogncheck #include "shell/browser/printing/print_preview_message_handler.h" #include "shell/browser/printing/print_view_manager_electron.h" #if BUILDFLAG(IS_WIN) #include "printing/backend/win_helper.h" #endif #endif #if BUILDFLAG(ENABLE_PICTURE_IN_PICTURE) #include "chrome/browser/picture_in_picture/picture_in_picture_window_manager.h" #endif #if BUILDFLAG(ENABLE_PDF_VIEWER) #include "components/pdf/browser/pdf_web_contents_helper.h" // nogncheck #include "shell/browser/electron_pdf_web_contents_helper_client.h" #endif #if BUILDFLAG(ENABLE_PLUGINS) #include "content/public/browser/plugin_service.h" #endif #ifndef MAS_BUILD #include "chrome/browser/hang_monitor/hang_crash_dump.h" // nogncheck #endif namespace gin { #if BUILDFLAG(ENABLE_PRINTING) template <> struct Converter<printing::mojom::MarginType> { static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, printing::mojom::MarginType* out) { std::string type; if (ConvertFromV8(isolate, val, &type)) { if (type == "default") { *out = printing::mojom::MarginType::kDefaultMargins; return true; } if (type == "none") { *out = printing::mojom::MarginType::kNoMargins; return true; } if (type == "printableArea") { *out = printing::mojom::MarginType::kPrintableAreaMargins; return true; } if (type == "custom") { *out = printing::mojom::MarginType::kCustomMargins; return true; } } return false; } }; template <> struct Converter<printing::mojom::DuplexMode> { static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, printing::mojom::DuplexMode* out) { std::string mode; if (ConvertFromV8(isolate, val, &mode)) { if (mode == "simplex") { *out = printing::mojom::DuplexMode::kSimplex; return true; } if (mode == "longEdge") { *out = printing::mojom::DuplexMode::kLongEdge; return true; } if (mode == "shortEdge") { *out = printing::mojom::DuplexMode::kShortEdge; return true; } } return false; } }; #endif template <> struct Converter<WindowOpenDisposition> { static v8::Local<v8::Value> ToV8(v8::Isolate* isolate, WindowOpenDisposition val) { std::string disposition = "other"; switch (val) { case WindowOpenDisposition::CURRENT_TAB: disposition = "default"; break; case WindowOpenDisposition::NEW_FOREGROUND_TAB: disposition = "foreground-tab"; break; case WindowOpenDisposition::NEW_BACKGROUND_TAB: disposition = "background-tab"; break; case WindowOpenDisposition::NEW_POPUP: case WindowOpenDisposition::NEW_WINDOW: disposition = "new-window"; break; case WindowOpenDisposition::SAVE_TO_DISK: disposition = "save-to-disk"; break; default: break; } return gin::ConvertToV8(isolate, disposition); } }; template <> struct Converter<content::SavePageType> { static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, content::SavePageType* out) { std::string save_type; if (!ConvertFromV8(isolate, val, &save_type)) return false; save_type = base::ToLowerASCII(save_type); if (save_type == "htmlonly") { *out = content::SAVE_PAGE_TYPE_AS_ONLY_HTML; } else if (save_type == "htmlcomplete") { *out = content::SAVE_PAGE_TYPE_AS_COMPLETE_HTML; } else if (save_type == "mhtml") { *out = content::SAVE_PAGE_TYPE_AS_MHTML; } else { return false; } return true; } }; template <> struct Converter<electron::api::WebContents::Type> { static v8::Local<v8::Value> ToV8(v8::Isolate* isolate, electron::api::WebContents::Type val) { using Type = electron::api::WebContents::Type; std::string type; switch (val) { case Type::kBackgroundPage: type = "backgroundPage"; break; case Type::kBrowserWindow: type = "window"; break; case Type::kBrowserView: type = "browserView"; break; case Type::kRemote: type = "remote"; break; case Type::kWebView: type = "webview"; break; case Type::kOffScreen: type = "offscreen"; break; default: break; } return gin::ConvertToV8(isolate, type); } static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, electron::api::WebContents::Type* out) { using Type = electron::api::WebContents::Type; std::string type; if (!ConvertFromV8(isolate, val, &type)) return false; if (type == "backgroundPage") { *out = Type::kBackgroundPage; } else if (type == "browserView") { *out = Type::kBrowserView; } else if (type == "webview") { *out = Type::kWebView; #if BUILDFLAG(ENABLE_OSR) } else if (type == "offscreen") { *out = Type::kOffScreen; #endif } else { return false; } return true; } }; template <> struct Converter<scoped_refptr<content::DevToolsAgentHost>> { static v8::Local<v8::Value> ToV8( v8::Isolate* isolate, const scoped_refptr<content::DevToolsAgentHost>& val) { gin_helper::Dictionary dict(isolate, v8::Object::New(isolate)); dict.Set("id", val->GetId()); dict.Set("url", val->GetURL().spec()); return dict.GetHandle(); } }; } // namespace gin namespace electron { namespace api { namespace { base::IDMap<WebContents*>& GetAllWebContents() { static base::NoDestructor<base::IDMap<WebContents*>> s_all_web_contents; return *s_all_web_contents; } // Called when CapturePage is done. void OnCapturePageDone(gin_helper::Promise<gfx::Image> promise, const SkBitmap& bitmap) { // Hack to enable transparency in captured image promise.Resolve(gfx::Image::CreateFrom1xBitmap(bitmap)); } absl::optional<base::TimeDelta> GetCursorBlinkInterval() { #if BUILDFLAG(IS_MAC) absl::optional<base::TimeDelta> system_value( ui::TextInsertionCaretBlinkPeriodFromDefaults()); if (system_value) return *system_value; #elif BUILDFLAG(IS_LINUX) if (auto* linux_ui = views::LinuxUI::instance()) return linux_ui->GetCursorBlinkInterval(); #elif BUILDFLAG(IS_WIN) const auto system_msec = ::GetCaretBlinkTime(); if (system_msec != 0) { return (system_msec == INFINITE) ? base::TimeDelta() : base::Milliseconds(system_msec); } #endif return absl::nullopt; } #if BUILDFLAG(ENABLE_PRINTING) // This will return false if no printer with the provided device_name can be // found on the network. We need to check this because Chromium does not do // sanity checking of device_name validity and so will crash on invalid names. bool IsDeviceNameValid(const std::u16string& device_name) { #if BUILDFLAG(IS_MAC) base::ScopedCFTypeRef<CFStringRef> new_printer_id( base::SysUTF16ToCFStringRef(device_name)); PMPrinter new_printer = PMPrinterCreateFromPrinterID(new_printer_id.get()); bool printer_exists = new_printer != nullptr; PMRelease(new_printer); return printer_exists; #elif BUILDFLAG(IS_WIN) printing::ScopedPrinterHandle printer; return printer.OpenPrinterWithName(base::as_wcstr(device_name)); #else return true; #endif } std::pair<std::string, std::u16string> GetDefaultPrinterAsync() { #if BUILDFLAG(IS_WIN) // Blocking is needed here because Windows printer drivers are oftentimes // not thread-safe and have to be accessed on the UI thread. base::ThreadRestrictions::ScopedAllowIO allow_io; #endif scoped_refptr<printing::PrintBackend> print_backend = printing::PrintBackend::CreateInstance( g_browser_process->GetApplicationLocale()); std::string printer_name; printing::mojom::ResultCode code = print_backend->GetDefaultPrinterName(printer_name); // We don't want to return if this fails since some devices won't have a // default printer. if (code != printing::mojom::ResultCode::kSuccess) LOG(ERROR) << "Failed to get default printer name"; // Check for existing printers and pick the first one should it exist. if (printer_name.empty()) { printing::PrinterList printers; if (print_backend->EnumeratePrinters(&printers) != printing::mojom::ResultCode::kSuccess) return std::make_pair("Failed to enumerate printers", std::u16string()); if (!printers.empty()) printer_name = printers.front().printer_name; } return std::make_pair(std::string(), base::UTF8ToUTF16(printer_name)); } // Copied from // chrome/browser/ui/webui/print_preview/local_printer_handler_default.cc:L36-L54 scoped_refptr<base::TaskRunner> CreatePrinterHandlerTaskRunner() { // USER_VISIBLE because the result is displayed in the print preview dialog. #if !BUILDFLAG(IS_WIN) static constexpr base::TaskTraits kTraits = { base::MayBlock(), base::TaskPriority::USER_VISIBLE}; #endif #if defined(USE_CUPS) // CUPS is thread safe. return base::ThreadPool::CreateTaskRunner(kTraits); #elif BUILDFLAG(IS_WIN) // Windows drivers are likely not thread-safe and need to be accessed on the // UI thread. return content::GetUIThreadTaskRunner( {base::MayBlock(), base::TaskPriority::USER_VISIBLE}); #else // Be conservative on unsupported platforms. return base::ThreadPool::CreateSingleThreadTaskRunner(kTraits); #endif } #endif struct UserDataLink : public base::SupportsUserData::Data { explicit UserDataLink(base::WeakPtr<WebContents> contents) : web_contents(contents) {} base::WeakPtr<WebContents> web_contents; }; const void* kElectronApiWebContentsKey = &kElectronApiWebContentsKey; const char kRootName[] = "<root>"; struct FileSystem { FileSystem() = default; FileSystem(const std::string& type, const std::string& file_system_name, const std::string& root_url, const std::string& file_system_path) : type(type), file_system_name(file_system_name), root_url(root_url), file_system_path(file_system_path) {} std::string type; std::string file_system_name; std::string root_url; std::string file_system_path; }; std::string RegisterFileSystem(content::WebContents* web_contents, const base::FilePath& path) { auto* isolated_context = storage::IsolatedContext::GetInstance(); std::string root_name(kRootName); storage::IsolatedContext::ScopedFSHandle file_system = isolated_context->RegisterFileSystemForPath( storage::kFileSystemTypeLocal, std::string(), path, &root_name); content::ChildProcessSecurityPolicy* policy = content::ChildProcessSecurityPolicy::GetInstance(); content::RenderViewHost* render_view_host = web_contents->GetRenderViewHost(); int renderer_id = render_view_host->GetProcess()->GetID(); policy->GrantReadFileSystem(renderer_id, file_system.id()); policy->GrantWriteFileSystem(renderer_id, file_system.id()); policy->GrantCreateFileForFileSystem(renderer_id, file_system.id()); policy->GrantDeleteFromFileSystem(renderer_id, file_system.id()); if (!policy->CanReadFile(renderer_id, path)) policy->GrantReadFile(renderer_id, path); return file_system.id(); } FileSystem CreateFileSystemStruct(content::WebContents* web_contents, const std::string& file_system_id, const std::string& file_system_path, const std::string& type) { const GURL origin = web_contents->GetURL().DeprecatedGetOriginAsURL(); std::string file_system_name = storage::GetIsolatedFileSystemName(origin, file_system_id); std::string root_url = storage::GetIsolatedFileSystemRootURIString( origin, file_system_id, kRootName); return FileSystem(type, file_system_name, root_url, file_system_path); } std::unique_ptr<base::DictionaryValue> CreateFileSystemValue( const FileSystem& file_system) { auto file_system_value = std::make_unique<base::DictionaryValue>(); file_system_value->SetString("type", file_system.type); file_system_value->SetString("fileSystemName", file_system.file_system_name); file_system_value->SetString("rootURL", file_system.root_url); file_system_value->SetString("fileSystemPath", file_system.file_system_path); return file_system_value; } void WriteToFile(const base::FilePath& path, const std::string& content) { base::ScopedBlockingCall scoped_blocking_call(FROM_HERE, base::BlockingType::WILL_BLOCK); DCHECK(!path.empty()); base::WriteFile(path, content.data(), content.size()); } void AppendToFile(const base::FilePath& path, const std::string& content) { base::ScopedBlockingCall scoped_blocking_call(FROM_HERE, base::BlockingType::WILL_BLOCK); DCHECK(!path.empty()); base::AppendToFile(path, content); } PrefService* GetPrefService(content::WebContents* web_contents) { auto* context = web_contents->GetBrowserContext(); return static_cast<electron::ElectronBrowserContext*>(context)->prefs(); } std::map<std::string, std::string> GetAddedFileSystemPaths( content::WebContents* web_contents) { auto* pref_service = GetPrefService(web_contents); const base::Value* file_system_paths_value = pref_service->GetDictionary(prefs::kDevToolsFileSystemPaths); std::map<std::string, std::string> result; if (file_system_paths_value) { const base::DictionaryValue* file_system_paths_dict; file_system_paths_value->GetAsDictionary(&file_system_paths_dict); for (auto it : file_system_paths_dict->DictItems()) { std::string type = it.second.is_string() ? it.second.GetString() : std::string(); result[it.first] = type; } } return result; } bool IsDevToolsFileSystemAdded(content::WebContents* web_contents, const std::string& file_system_path) { auto file_system_paths = GetAddedFileSystemPaths(web_contents); return file_system_paths.find(file_system_path) != file_system_paths.end(); } void SetBackgroundColor(content::RenderWidgetHostView* rwhv, SkColor color) { rwhv->SetBackgroundColor(color); static_cast<content::RenderWidgetHostViewBase*>(rwhv) ->SetContentBackgroundColor(color); } } // namespace #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) WebContents::Type GetTypeFromViewType(extensions::mojom::ViewType view_type) { switch (view_type) { case extensions::mojom::ViewType::kExtensionBackgroundPage: return WebContents::Type::kBackgroundPage; case extensions::mojom::ViewType::kAppWindow: case extensions::mojom::ViewType::kComponent: case extensions::mojom::ViewType::kExtensionDialog: case extensions::mojom::ViewType::kExtensionPopup: case extensions::mojom::ViewType::kBackgroundContents: case extensions::mojom::ViewType::kExtensionGuest: case extensions::mojom::ViewType::kTabContents: case extensions::mojom::ViewType::kInvalid: return WebContents::Type::kRemote; } } #endif WebContents::WebContents(v8::Isolate* isolate, content::WebContents* web_contents) : content::WebContentsObserver(web_contents), type_(Type::kRemote), id_(GetAllWebContents().Add(this)), devtools_file_system_indexer_( base::MakeRefCounted<DevToolsFileSystemIndexer>()), exclusive_access_manager_(std::make_unique<ExclusiveAccessManager>(this)), file_task_runner_( base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()})) #if BUILDFLAG(ENABLE_PRINTING) , print_task_runner_(CreatePrinterHandlerTaskRunner()) #endif { #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) // WebContents created by extension host will have valid ViewType set. extensions::mojom::ViewType view_type = extensions::GetViewType(web_contents); if (view_type != extensions::mojom::ViewType::kInvalid) { InitWithExtensionView(isolate, web_contents, view_type); } extensions::ElectronExtensionWebContentsObserver::CreateForWebContents( web_contents); script_executor_ = std::make_unique<extensions::ScriptExecutor>(web_contents); #endif auto session = Session::CreateFrom(isolate, GetBrowserContext()); session_.Reset(isolate, session.ToV8()); web_contents->SetUserAgentOverride(blink::UserAgentOverride::UserAgentOnly( GetBrowserContext()->GetUserAgent()), false); web_contents->SetUserData(kElectronApiWebContentsKey, std::make_unique<UserDataLink>(GetWeakPtr())); InitZoomController(web_contents, gin::Dictionary::CreateEmpty(isolate)); } WebContents::WebContents(v8::Isolate* isolate, std::unique_ptr<content::WebContents> web_contents, Type type) : content::WebContentsObserver(web_contents.get()), type_(type), id_(GetAllWebContents().Add(this)), devtools_file_system_indexer_( base::MakeRefCounted<DevToolsFileSystemIndexer>()), exclusive_access_manager_(std::make_unique<ExclusiveAccessManager>(this)), file_task_runner_( base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()})) #if BUILDFLAG(ENABLE_PRINTING) , print_task_runner_(CreatePrinterHandlerTaskRunner()) #endif { DCHECK(type != Type::kRemote) << "Can't take ownership of a remote WebContents"; auto session = Session::CreateFrom(isolate, GetBrowserContext()); session_.Reset(isolate, session.ToV8()); InitWithSessionAndOptions(isolate, std::move(web_contents), session, gin::Dictionary::CreateEmpty(isolate)); } WebContents::WebContents(v8::Isolate* isolate, const gin_helper::Dictionary& options) : id_(GetAllWebContents().Add(this)), devtools_file_system_indexer_( base::MakeRefCounted<DevToolsFileSystemIndexer>()), exclusive_access_manager_(std::make_unique<ExclusiveAccessManager>(this)), file_task_runner_( base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()})) #if BUILDFLAG(ENABLE_PRINTING) , print_task_runner_(CreatePrinterHandlerTaskRunner()) #endif { // Read options. options.Get("backgroundThrottling", &background_throttling_); // Get type options.Get("type", &type_); #if BUILDFLAG(ENABLE_OSR) bool b = false; if (options.Get(options::kOffscreen, &b) && b) type_ = Type::kOffScreen; #endif // Init embedder earlier options.Get("embedder", &embedder_); // Whether to enable DevTools. options.Get("devTools", &enable_devtools_); // BrowserViews are not attached to a window initially so they should start // off as hidden. This is also important for compositor recycling. See: // https://github.com/electron/electron/pull/21372 bool initially_shown = type_ != Type::kBrowserView; options.Get(options::kShow, &initially_shown); // Obtain the session. std::string partition; gin::Handle<api::Session> session; if (options.Get("session", &session) && !session.IsEmpty()) { } else if (options.Get("partition", &partition)) { session = Session::FromPartition(isolate, partition); } else { // Use the default session if not specified. session = Session::FromPartition(isolate, ""); } session_.Reset(isolate, session.ToV8()); std::unique_ptr<content::WebContents> web_contents; if (IsGuest()) { scoped_refptr<content::SiteInstance> site_instance = content::SiteInstance::CreateForURL(session->browser_context(), GURL("chrome-guest://fake-host")); content::WebContents::CreateParams params(session->browser_context(), site_instance); guest_delegate_ = std::make_unique<WebViewGuestDelegate>(embedder_->web_contents(), this); params.guest_delegate = guest_delegate_.get(); #if BUILDFLAG(ENABLE_OSR) if (embedder_ && embedder_->IsOffScreen()) { auto* view = new OffScreenWebContentsView( false, base::BindRepeating(&WebContents::OnPaint, base::Unretained(this))); params.view = view; params.delegate_view = view; web_contents = content::WebContents::Create(params); view->SetWebContents(web_contents.get()); } else { #endif web_contents = content::WebContents::Create(params); #if BUILDFLAG(ENABLE_OSR) } } else if (IsOffScreen()) { // webPreferences does not have a transparent option, so if the window needs // to be transparent, that will be set at electron_api_browser_window.cc#L57 // and we then need to pull it back out and check it here. std::string background_color; options.GetHidden(options::kBackgroundColor, &background_color); bool transparent = ParseCSSColor(background_color) == SK_ColorTRANSPARENT; content::WebContents::CreateParams params(session->browser_context()); auto* view = new OffScreenWebContentsView( transparent, base::BindRepeating(&WebContents::OnPaint, base::Unretained(this))); params.view = view; params.delegate_view = view; web_contents = content::WebContents::Create(params); view->SetWebContents(web_contents.get()); #endif } else { content::WebContents::CreateParams params(session->browser_context()); params.initially_hidden = !initially_shown; web_contents = content::WebContents::Create(params); } InitWithSessionAndOptions(isolate, std::move(web_contents), session, options); } void WebContents::InitZoomController(content::WebContents* web_contents, const gin_helper::Dictionary& options) { WebContentsZoomController::CreateForWebContents(web_contents); zoom_controller_ = WebContentsZoomController::FromWebContents(web_contents); double zoom_factor; if (options.Get(options::kZoomFactor, &zoom_factor)) zoom_controller_->SetDefaultZoomFactor(zoom_factor); } void WebContents::InitWithSessionAndOptions( v8::Isolate* isolate, std::unique_ptr<content::WebContents> owned_web_contents, gin::Handle<api::Session> session, const gin_helper::Dictionary& options) { Observe(owned_web_contents.get()); InitWithWebContents(std::move(owned_web_contents), session->browser_context(), IsGuest()); inspectable_web_contents_->GetView()->SetDelegate(this); auto* prefs = web_contents()->GetMutableRendererPrefs(); // Collect preferred languages from OS and browser process. accept_languages // effects HTTP header, navigator.languages, and CJK fallback font selection. // // Note that an application locale set to the browser process might be // different with the one set to the preference list. // (e.g. overridden with --lang) std::string accept_languages = g_browser_process->GetApplicationLocale() + ","; for (auto const& language : electron::GetPreferredLanguages()) { if (language == g_browser_process->GetApplicationLocale()) continue; accept_languages += language + ","; } accept_languages.pop_back(); prefs->accept_languages = accept_languages; #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_WIN) // Update font settings. static const gfx::FontRenderParams params( gfx::GetFontRenderParams(gfx::FontRenderParamsQuery(), nullptr)); prefs->should_antialias_text = params.antialiasing; prefs->use_subpixel_positioning = params.subpixel_positioning; prefs->hinting = params.hinting; prefs->use_autohinter = params.autohinter; prefs->use_bitmaps = params.use_bitmaps; prefs->subpixel_rendering = params.subpixel_rendering; #endif // Honor the system's cursor blink rate settings if (auto interval = GetCursorBlinkInterval()) prefs->caret_blink_interval = *interval; // Save the preferences in C++. // If there's already a WebContentsPreferences object, we created it as part // of the webContents.setWindowOpenHandler path, so don't overwrite it. if (!WebContentsPreferences::From(web_contents())) { new WebContentsPreferences(web_contents(), options); } // Trigger re-calculation of webkit prefs. web_contents()->NotifyPreferencesChanged(); WebContentsPermissionHelper::CreateForWebContents(web_contents()); InitZoomController(web_contents(), options); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) extensions::ElectronExtensionWebContentsObserver::CreateForWebContents( web_contents()); script_executor_ = std::make_unique<extensions::ScriptExecutor>(web_contents()); #endif AutofillDriverFactory::CreateForWebContents(web_contents()); web_contents()->SetUserAgentOverride(blink::UserAgentOverride::UserAgentOnly( GetBrowserContext()->GetUserAgent()), false); if (IsGuest()) { NativeWindow* owner_window = nullptr; if (embedder_) { // New WebContents's owner_window is the embedder's owner_window. auto* relay = NativeWindowRelay::FromWebContents(embedder_->web_contents()); if (relay) owner_window = relay->GetNativeWindow(); } if (owner_window) SetOwnerWindow(owner_window); } web_contents()->SetUserData(kElectronApiWebContentsKey, std::make_unique<UserDataLink>(GetWeakPtr())); } #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) void WebContents::InitWithExtensionView(v8::Isolate* isolate, content::WebContents* web_contents, extensions::mojom::ViewType view_type) { // Must reassign type prior to calling `Init`. type_ = GetTypeFromViewType(view_type); if (type_ == Type::kRemote) return; if (type_ == Type::kBackgroundPage) // non-background-page WebContents are retained by other classes. We need // to pin here to prevent background-page WebContents from being GC'd. // The background page api::WebContents will live until the underlying // content::WebContents is destroyed. Pin(isolate); // Allow toggling DevTools for background pages Observe(web_contents); InitWithWebContents(std::unique_ptr<content::WebContents>(web_contents), GetBrowserContext(), IsGuest()); inspectable_web_contents_->GetView()->SetDelegate(this); } #endif void WebContents::InitWithWebContents( std::unique_ptr<content::WebContents> web_contents, ElectronBrowserContext* browser_context, bool is_guest) { browser_context_ = browser_context; web_contents->SetDelegate(this); #if BUILDFLAG(ENABLE_PRINTING) PrintPreviewMessageHandler::CreateForWebContents(web_contents.get()); PrintViewManagerElectron::CreateForWebContents(web_contents.get()); printing::CreateCompositeClientIfNeeded(web_contents.get(), browser_context->GetUserAgent()); #endif #if BUILDFLAG(ENABLE_PDF_VIEWER) pdf::PDFWebContentsHelper::CreateForWebContentsWithClient( web_contents.get(), std::make_unique<ElectronPDFWebContentsHelperClient>()); #endif // Determine whether the WebContents is offscreen. auto* web_preferences = WebContentsPreferences::From(web_contents.get()); offscreen_ = web_preferences && web_preferences->IsOffscreen(); // Create InspectableWebContents. inspectable_web_contents_ = std::make_unique<InspectableWebContents>( std::move(web_contents), browser_context->prefs(), is_guest); inspectable_web_contents_->SetDelegate(this); } WebContents::~WebContents() { // clear out objects that have been granted permissions so that when // WebContents::RenderFrameDeleted is called as a result of WebContents // destruction it doesn't try to clear out a granted_devices_ // on a destructed object. granted_devices_.clear(); if (!inspectable_web_contents_) { WebContentsDestroyed(); return; } inspectable_web_contents_->GetView()->SetDelegate(nullptr); // This event is only for internal use, which is emitted when WebContents is // being destroyed. Emit("will-destroy"); // For guest view based on OOPIF, the WebContents is released by the embedder // frame, and we need to clear the reference to the memory. bool not_owned_by_this = IsGuest() && attached_; #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) // And background pages are owned by extensions::ExtensionHost. if (type_ == Type::kBackgroundPage) not_owned_by_this = true; #endif if (not_owned_by_this) { inspectable_web_contents_->ReleaseWebContents(); WebContentsDestroyed(); } // InspectableWebContents will be automatically destroyed. } void WebContents::DeleteThisIfAlive() { // It is possible that the FirstWeakCallback has been called but the // SecondWeakCallback has not, in this case the garbage collection of // WebContents has already started and we should not |delete this|. // Calling |GetWrapper| can detect this corner case. auto* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); v8::Local<v8::Object> wrapper; if (!GetWrapper(isolate).ToLocal(&wrapper)) return; delete this; } void WebContents::Destroy() { // The content::WebContents should be destroyed asyncronously when possible // as user may choose to destroy WebContents during an event of it. if (Browser::Get()->is_shutting_down() || IsGuest()) { DeleteThisIfAlive(); } else { base::PostTask(FROM_HERE, {content::BrowserThread::UI}, base::BindOnce( [](base::WeakPtr<WebContents> contents) { if (contents) contents->DeleteThisIfAlive(); }, GetWeakPtr())); } } bool WebContents::DidAddMessageToConsole( content::WebContents* source, blink::mojom::ConsoleMessageLevel level, const std::u16string& message, int32_t line_no, const std::u16string& source_id) { return Emit("console-message", static_cast<int32_t>(level), message, line_no, source_id); } void WebContents::OnCreateWindow( const GURL& target_url, const content::Referrer& referrer, const std::string& frame_name, WindowOpenDisposition disposition, const std::string& features, const scoped_refptr<network::ResourceRequestBody>& body) { Emit("-new-window", target_url, frame_name, disposition, features, referrer, body); } void WebContents::WebContentsCreatedWithFullParams( content::WebContents* source_contents, int opener_render_process_id, int opener_render_frame_id, const content::mojom::CreateNewWindowParams& params, content::WebContents* new_contents) { ChildWebContentsTracker::CreateForWebContents(new_contents); auto* tracker = ChildWebContentsTracker::FromWebContents(new_contents); tracker->url = params.target_url; tracker->frame_name = params.frame_name; tracker->referrer = params.referrer.To<content::Referrer>(); tracker->raw_features = params.raw_features; tracker->body = params.body; v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::Locker locker(isolate); v8::HandleScope handle_scope(isolate); gin_helper::Dictionary dict; gin::ConvertFromV8(isolate, pending_child_web_preferences_.Get(isolate), &dict); pending_child_web_preferences_.Reset(); // Associate the preferences passed in via `setWindowOpenHandler` with the // content::WebContents that was just created for the child window. These // preferences will be picked up by the RenderWidgetHost via its call to the // delegate's OverrideWebkitPrefs. new WebContentsPreferences(new_contents, dict); } bool WebContents::IsWebContentsCreationOverridden( content::SiteInstance* source_site_instance, content::mojom::WindowContainerType window_container_type, const GURL& opener_url, const content::mojom::CreateNewWindowParams& params) { bool default_prevented = Emit( "-will-add-new-contents", params.target_url, params.frame_name, params.raw_features, params.disposition, *params.referrer, params.body); // If the app prevented the default, redirect to CreateCustomWebContents, // which always returns nullptr, which will result in the window open being // prevented (window.open() will return null in the renderer). return default_prevented; } void WebContents::SetNextChildWebPreferences( const gin_helper::Dictionary preferences) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::Locker locker(isolate); v8::HandleScope handle_scope(isolate); // Store these prefs for when Chrome calls WebContentsCreatedWithFullParams // with the new child contents. pending_child_web_preferences_.Reset(isolate, preferences.GetHandle()); } content::WebContents* WebContents::CreateCustomWebContents( content::RenderFrameHost* opener, content::SiteInstance* source_site_instance, bool is_new_browsing_instance, const GURL& opener_url, const std::string& frame_name, const GURL& target_url, const content::StoragePartitionConfig& partition_config, content::SessionStorageNamespace* session_storage_namespace) { return nullptr; } void WebContents::AddNewContents( content::WebContents* source, std::unique_ptr<content::WebContents> new_contents, const GURL& target_url, WindowOpenDisposition disposition, const gfx::Rect& initial_rect, bool user_gesture, bool* was_blocked) { auto* tracker = ChildWebContentsTracker::FromWebContents(new_contents.get()); DCHECK(tracker); v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::Locker locker(isolate); v8::HandleScope handle_scope(isolate); auto api_web_contents = CreateAndTake(isolate, std::move(new_contents), Type::kBrowserWindow); // We call RenderFrameCreated here as at this point the empty "about:blank" // render frame has already been created. If the window never navigates again // RenderFrameCreated won't be called and certain prefs like // "kBackgroundColor" will not be applied. auto* frame = api_web_contents->MainFrame(); if (frame) { api_web_contents->HandleNewRenderFrame(frame); } if (Emit("-add-new-contents", api_web_contents, disposition, user_gesture, initial_rect.x(), initial_rect.y(), initial_rect.width(), initial_rect.height(), tracker->url, tracker->frame_name, tracker->referrer, tracker->raw_features, tracker->body)) { api_web_contents->Destroy(); } } content::WebContents* WebContents::OpenURLFromTab( content::WebContents* source, const content::OpenURLParams& params) { auto weak_this = GetWeakPtr(); if (params.disposition != WindowOpenDisposition::CURRENT_TAB) { Emit("-new-window", params.url, "", params.disposition, "", params.referrer, params.post_data); return nullptr; } if (!weak_this || !web_contents()) return nullptr; content::NavigationController::LoadURLParams load_url_params(params.url); load_url_params.referrer = params.referrer; load_url_params.transition_type = params.transition; load_url_params.extra_headers = params.extra_headers; load_url_params.should_replace_current_entry = params.should_replace_current_entry; load_url_params.is_renderer_initiated = params.is_renderer_initiated; load_url_params.started_from_context_menu = params.started_from_context_menu; load_url_params.initiator_origin = params.initiator_origin; load_url_params.source_site_instance = params.source_site_instance; load_url_params.frame_tree_node_id = params.frame_tree_node_id; load_url_params.redirect_chain = params.redirect_chain; load_url_params.has_user_gesture = params.user_gesture; load_url_params.blob_url_loader_factory = params.blob_url_loader_factory; load_url_params.href_translate = params.href_translate; load_url_params.reload_type = params.reload_type; if (params.post_data) { load_url_params.load_type = content::NavigationController::LOAD_TYPE_HTTP_POST; load_url_params.post_data = params.post_data; } source->GetController().LoadURLWithParams(load_url_params); return source; } void WebContents::BeforeUnloadFired(content::WebContents* tab, bool proceed, bool* proceed_to_fire_unload) { if (type_ == Type::kBrowserWindow || type_ == Type::kOffScreen || type_ == Type::kBrowserView) *proceed_to_fire_unload = proceed; else *proceed_to_fire_unload = true; // Note that Chromium does not emit this for navigations. Emit("before-unload-fired", proceed); } void WebContents::SetContentsBounds(content::WebContents* source, const gfx::Rect& rect) { for (ExtendedWebContentsObserver& observer : observers_) observer.OnSetContentBounds(rect); } void WebContents::CloseContents(content::WebContents* source) { Emit("close"); auto* autofill_driver_factory = AutofillDriverFactory::FromWebContents(web_contents()); if (autofill_driver_factory) { autofill_driver_factory->CloseAllPopups(); } for (ExtendedWebContentsObserver& observer : observers_) observer.OnCloseContents(); } void WebContents::ActivateContents(content::WebContents* source) { for (ExtendedWebContentsObserver& observer : observers_) observer.OnActivateContents(); } void WebContents::UpdateTargetURL(content::WebContents* source, const GURL& url) { Emit("update-target-url", url); } bool WebContents::HandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) { if (type_ == Type::kWebView && embedder_) { // Send the unhandled keyboard events back to the embedder. return embedder_->HandleKeyboardEvent(source, event); } else { return PlatformHandleKeyboardEvent(source, event); } } #if !BUILDFLAG(IS_MAC) // NOTE: The macOS version of this function is found in // electron_api_web_contents_mac.mm, as it requires calling into objective-C // code. bool WebContents::PlatformHandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) { // Escape exits tabbed fullscreen mode. if (event.windows_key_code == ui::VKEY_ESCAPE && is_html_fullscreen()) { ExitFullscreenModeForTab(source); return true; } // Check if the webContents has preferences and to ignore shortcuts auto* web_preferences = WebContentsPreferences::From(source); if (web_preferences && web_preferences->ShouldIgnoreMenuShortcuts()) return false; // Let the NativeWindow handle other parts. if (owner_window()) { owner_window()->HandleKeyboardEvent(source, event); return true; } return false; } #endif content::KeyboardEventProcessingResult WebContents::PreHandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) { if (exclusive_access_manager_->HandleUserKeyEvent(event)) return content::KeyboardEventProcessingResult::HANDLED; if (event.GetType() == blink::WebInputEvent::Type::kRawKeyDown || event.GetType() == blink::WebInputEvent::Type::kKeyUp) { bool prevent_default = Emit("before-input-event", event); if (prevent_default) { return content::KeyboardEventProcessingResult::HANDLED; } } return content::KeyboardEventProcessingResult::NOT_HANDLED; } void WebContents::ContentsZoomChange(bool zoom_in) { Emit("zoom-changed", zoom_in ? "in" : "out"); } Profile* WebContents::GetProfile() { return nullptr; } bool WebContents::IsFullscreen() const { return owner_window_ && owner_window_->IsFullscreen(); } void WebContents::EnterFullscreen(const GURL& url, ExclusiveAccessBubbleType bubble_type, const int64_t display_id) {} void WebContents::ExitFullscreen() {} void WebContents::UpdateExclusiveAccessExitBubbleContent( const GURL& url, ExclusiveAccessBubbleType bubble_type, ExclusiveAccessBubbleHideCallback bubble_first_hide_callback, bool force_update) {} void WebContents::OnExclusiveAccessUserInput() {} content::WebContents* WebContents::GetActiveWebContents() { return web_contents(); } bool WebContents::CanUserExitFullscreen() const { return true; } bool WebContents::IsExclusiveAccessBubbleDisplayed() const { return false; } void WebContents::EnterFullscreenModeForTab( content::RenderFrameHost* requesting_frame, const blink::mojom::FullscreenOptions& options) { auto* source = content::WebContents::FromRenderFrameHost(requesting_frame); auto* permission_helper = WebContentsPermissionHelper::FromWebContents(source); auto callback = base::BindRepeating(&WebContents::OnEnterFullscreenModeForTab, base::Unretained(this), requesting_frame, options); permission_helper->RequestFullscreenPermission(callback); exclusive_access_manager_->fullscreen_controller()->EnterFullscreenModeForTab( requesting_frame, options.display_id); } void WebContents::OnEnterFullscreenModeForTab( content::RenderFrameHost* requesting_frame, const blink::mojom::FullscreenOptions& options, bool allowed) { if (!allowed || !owner_window_) return; auto* source = content::WebContents::FromRenderFrameHost(requesting_frame); if (IsFullscreenForTabOrPending(source)) { DCHECK_EQ(fullscreen_frame_, source->GetFocusedFrame()); return; } SetHtmlApiFullscreen(true); if (native_fullscreen_) { // Explicitly trigger a view resize, as the size is not actually changing if // the browser is fullscreened, too. source->GetRenderViewHost()->GetWidget()->SynchronizeVisualProperties(); } } void WebContents::ExitFullscreenModeForTab(content::WebContents* source) { if (!owner_window_) return; SetHtmlApiFullscreen(false); if (native_fullscreen_) { // Explicitly trigger a view resize, as the size is not actually changing if // the browser is fullscreened, too. Chrome does this indirectly from // `chrome/browser/ui/exclusive_access/fullscreen_controller.cc`. source->GetRenderViewHost()->GetWidget()->SynchronizeVisualProperties(); } exclusive_access_manager_->fullscreen_controller()->ExitFullscreenModeForTab( source); } void WebContents::RendererUnresponsive( content::WebContents* source, content::RenderWidgetHost* render_widget_host, base::RepeatingClosure hang_monitor_restarter) { Emit("unresponsive"); } void WebContents::RendererResponsive( content::WebContents* source, content::RenderWidgetHost* render_widget_host) { Emit("responsive"); } bool WebContents::HandleContextMenu(content::RenderFrameHost& render_frame_host, const content::ContextMenuParams& params) { Emit("context-menu", std::make_pair(params, &render_frame_host)); return true; } bool WebContents::OnGoToEntryOffset(int offset) { GoToOffset(offset); return false; } void WebContents::FindReply(content::WebContents* web_contents, int request_id, int number_of_matches, const gfx::Rect& selection_rect, int active_match_ordinal, bool final_update) { if (!final_update) return; v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::Locker locker(isolate); v8::HandleScope handle_scope(isolate); gin_helper::Dictionary result = gin::Dictionary::CreateEmpty(isolate); result.Set("requestId", request_id); result.Set("matches", number_of_matches); result.Set("selectionArea", selection_rect); result.Set("activeMatchOrdinal", active_match_ordinal); result.Set("finalUpdate", final_update); // Deprecate after 2.0 Emit("found-in-page", result.GetHandle()); } void WebContents::RequestExclusivePointerAccess( content::WebContents* web_contents, bool user_gesture, bool last_unlocked_by_target, bool allowed) { if (allowed) { exclusive_access_manager_->mouse_lock_controller()->RequestToLockMouse( web_contents, user_gesture, last_unlocked_by_target); } else { web_contents->GotResponseToLockMouseRequest( blink::mojom::PointerLockResult::kPermissionDenied); } } void WebContents::RequestToLockMouse(content::WebContents* web_contents, bool user_gesture, bool last_unlocked_by_target) { auto* permission_helper = WebContentsPermissionHelper::FromWebContents(web_contents); permission_helper->RequestPointerLockPermission( user_gesture, last_unlocked_by_target, base::BindOnce(&WebContents::RequestExclusivePointerAccess, base::Unretained(this))); } void WebContents::LostMouseLock() { exclusive_access_manager_->mouse_lock_controller()->LostMouseLock(); } void WebContents::RequestKeyboardLock(content::WebContents* web_contents, bool esc_key_locked) { exclusive_access_manager_->keyboard_lock_controller()->RequestKeyboardLock( web_contents, esc_key_locked); } void WebContents::CancelKeyboardLockRequest( content::WebContents* web_contents) { exclusive_access_manager_->keyboard_lock_controller() ->CancelKeyboardLockRequest(web_contents); } bool WebContents::CheckMediaAccessPermission( content::RenderFrameHost* render_frame_host, const GURL& security_origin, blink::mojom::MediaStreamType type) { auto* web_contents = content::WebContents::FromRenderFrameHost(render_frame_host); auto* permission_helper = WebContentsPermissionHelper::FromWebContents(web_contents); return permission_helper->CheckMediaAccessPermission(security_origin, type); } void WebContents::RequestMediaAccessPermission( content::WebContents* web_contents, const content::MediaStreamRequest& request, content::MediaResponseCallback callback) { auto* permission_helper = WebContentsPermissionHelper::FromWebContents(web_contents); permission_helper->RequestMediaAccessPermission(request, std::move(callback)); } content::JavaScriptDialogManager* WebContents::GetJavaScriptDialogManager( content::WebContents* source) { if (!dialog_manager_) dialog_manager_ = std::make_unique<ElectronJavaScriptDialogManager>(); return dialog_manager_.get(); } void WebContents::OnAudioStateChanged(bool audible) { Emit("-audio-state-changed", audible); } void WebContents::BeforeUnloadFired(bool proceed, const base::TimeTicks& proceed_time) { // Do nothing, we override this method just to avoid compilation error since // there are two virtual functions named BeforeUnloadFired. } void WebContents::HandleNewRenderFrame( content::RenderFrameHost* render_frame_host) { auto* rwhv = render_frame_host->GetView(); if (!rwhv) return; // Set the background color of RenderWidgetHostView. auto* web_preferences = WebContentsPreferences::From(web_contents()); if (web_preferences) { absl::optional<SkColor> maybe_color = web_preferences->GetBackgroundColor(); web_contents()->SetPageBaseBackgroundColor(maybe_color); bool guest = IsGuest() || type_ == Type::kBrowserView; SkColor color = maybe_color.value_or(guest ? SK_ColorTRANSPARENT : SK_ColorWHITE); SetBackgroundColor(rwhv, color); } if (!background_throttling_) render_frame_host->GetRenderViewHost()->SetSchedulerThrottling(false); auto* rwh_impl = static_cast<content::RenderWidgetHostImpl*>(rwhv->GetRenderWidgetHost()); if (rwh_impl) rwh_impl->disable_hidden_ = !background_throttling_; auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host); if (web_frame) web_frame->Connect(); } void WebContents::OnBackgroundColorChanged() { absl::optional<SkColor> color = web_contents()->GetBackgroundColor(); if (color.has_value()) { auto* const view = web_contents()->GetRenderWidgetHostView(); static_cast<content::RenderWidgetHostViewBase*>(view) ->SetContentBackgroundColor(color.value()); } } void WebContents::RenderFrameCreated( content::RenderFrameHost* render_frame_host) { HandleNewRenderFrame(render_frame_host); // RenderFrameCreated is called for speculative frames which may not be // used in certain cross-origin navigations. Invoking // RenderFrameHost::GetLifecycleState currently crashes when called for // speculative frames so we need to filter it out for now. Check // https://crbug.com/1183639 for details on when this can be removed. auto* rfh_impl = static_cast<content::RenderFrameHostImpl*>(render_frame_host); if (rfh_impl->lifecycle_state() == content::RenderFrameHostImpl::LifecycleStateImpl::kSpeculative) { return; } content::RenderFrameHost::LifecycleState lifecycle_state = render_frame_host->GetLifecycleState(); if (lifecycle_state == content::RenderFrameHost::LifecycleState::kActive) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); gin_helper::Dictionary details = gin_helper::Dictionary::CreateEmpty(isolate); details.SetGetter("frame", render_frame_host); Emit("frame-created", details); } } void WebContents::RenderFrameDeleted( content::RenderFrameHost* render_frame_host) { // A RenderFrameHost can be deleted when: // - A WebContents is removed and its containing frames are disposed. // - An <iframe> is removed from the DOM. // - Cross-origin navigation creates a new RFH in a separate process which // is swapped by content::RenderFrameHostManager. // // clear out objects that have been granted permissions if (!granted_devices_.empty()) { granted_devices_.erase(render_frame_host->GetFrameTreeNodeId()); } // WebFrameMain::FromRenderFrameHost(rfh) will use the RFH's FrameTreeNode ID // to find an existing instance of WebFrameMain. During a cross-origin // navigation, the deleted RFH will be the old host which was swapped out. In // this special case, we need to also ensure that WebFrameMain's internal RFH // matches before marking it as disposed. auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host); if (web_frame && web_frame->render_frame_host() == render_frame_host) web_frame->MarkRenderFrameDisposed(); } void WebContents::RenderFrameHostChanged(content::RenderFrameHost* old_host, content::RenderFrameHost* new_host) { // During cross-origin navigation, a FrameTreeNode will swap out its RFH. // If an instance of WebFrameMain exists, it will need to have its RFH // swapped as well. // // |old_host| can be a nullptr so we use |new_host| for looking up the // WebFrameMain instance. auto* web_frame = WebFrameMain::FromFrameTreeNodeId(new_host->GetFrameTreeNodeId()); if (web_frame) { web_frame->UpdateRenderFrameHost(new_host); } } void WebContents::FrameDeleted(int frame_tree_node_id) { auto* web_frame = WebFrameMain::FromFrameTreeNodeId(frame_tree_node_id); if (web_frame) web_frame->Destroyed(); } void WebContents::RenderViewDeleted(content::RenderViewHost* render_view_host) { // This event is necessary for tracking any states with respect to // intermediate render view hosts aka speculative render view hosts. Currently // used by object-registry.js to ref count remote objects. Emit("render-view-deleted", render_view_host->GetProcess()->GetID()); if (web_contents()->GetRenderViewHost() == render_view_host) { // When the RVH that has been deleted is the current RVH it means that the // the web contents are being closed. This is communicated by this event. // Currently tracked by guest-window-manager.ts to destroy the // BrowserWindow. Emit("current-render-view-deleted", render_view_host->GetProcess()->GetID()); } } void WebContents::PrimaryMainFrameRenderProcessGone( base::TerminationStatus status) { auto weak_this = GetWeakPtr(); Emit("crashed", status == base::TERMINATION_STATUS_PROCESS_WAS_KILLED); // User might destroy WebContents in the crashed event. if (!weak_this || !web_contents()) return; v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); gin_helper::Dictionary details = gin_helper::Dictionary::CreateEmpty(isolate); details.Set("reason", status); details.Set("exitCode", web_contents()->GetCrashedErrorCode()); Emit("render-process-gone", details); } void WebContents::PluginCrashed(const base::FilePath& plugin_path, base::ProcessId plugin_pid) { #if BUILDFLAG(ENABLE_PLUGINS) content::WebPluginInfo info; auto* plugin_service = content::PluginService::GetInstance(); plugin_service->GetPluginInfoByPath(plugin_path, &info); Emit("plugin-crashed", info.name, info.version); #endif // BUILDFLAG(ENABLE_PLUGINS) } void WebContents::MediaStartedPlaying(const MediaPlayerInfo& video_type, const content::MediaPlayerId& id) { Emit("media-started-playing"); } void WebContents::MediaStoppedPlaying( const MediaPlayerInfo& video_type, const content::MediaPlayerId& id, content::WebContentsObserver::MediaStoppedReason reason) { Emit("media-paused"); } void WebContents::DidChangeThemeColor() { auto theme_color = web_contents()->GetThemeColor(); if (theme_color) { Emit("did-change-theme-color", electron::ToRGBHex(theme_color.value())); } else { Emit("did-change-theme-color", nullptr); } } void WebContents::DidAcquireFullscreen(content::RenderFrameHost* rfh) { set_fullscreen_frame(rfh); } void WebContents::OnWebContentsFocused( content::RenderWidgetHost* render_widget_host) { Emit("focus"); } void WebContents::OnWebContentsLostFocus( content::RenderWidgetHost* render_widget_host) { Emit("blur"); } void WebContents::DOMContentLoaded( content::RenderFrameHost* render_frame_host) { auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host); if (web_frame) web_frame->DOMContentLoaded(); if (!render_frame_host->GetParent()) Emit("dom-ready"); } void WebContents::DidFinishLoad(content::RenderFrameHost* render_frame_host, const GURL& validated_url) { bool is_main_frame = !render_frame_host->GetParent(); int frame_process_id = render_frame_host->GetProcess()->GetID(); int frame_routing_id = render_frame_host->GetRoutingID(); auto weak_this = GetWeakPtr(); Emit("did-frame-finish-load", is_main_frame, frame_process_id, frame_routing_id); // ⚠️WARNING!⚠️ // Emit() triggers JS which can call destroy() on |this|. It's not safe to // assume that |this| points to valid memory at this point. if (is_main_frame && weak_this && web_contents()) Emit("did-finish-load"); } void WebContents::DidFailLoad(content::RenderFrameHost* render_frame_host, const GURL& url, int error_code) { bool is_main_frame = !render_frame_host->GetParent(); int frame_process_id = render_frame_host->GetProcess()->GetID(); int frame_routing_id = render_frame_host->GetRoutingID(); Emit("did-fail-load", error_code, "", url, is_main_frame, frame_process_id, frame_routing_id); } void WebContents::DidStartLoading() { Emit("did-start-loading"); } void WebContents::DidStopLoading() { auto* web_preferences = WebContentsPreferences::From(web_contents()); if (web_preferences && web_preferences->ShouldUsePreferredSizeMode()) web_contents()->GetRenderViewHost()->EnablePreferredSizeMode(); Emit("did-stop-loading"); } bool WebContents::EmitNavigationEvent( const std::string& event, content::NavigationHandle* navigation_handle) { bool is_main_frame = navigation_handle->IsInMainFrame(); int frame_tree_node_id = navigation_handle->GetFrameTreeNodeId(); content::FrameTreeNode* frame_tree_node = content::FrameTreeNode::GloballyFindByID(frame_tree_node_id); content::RenderFrameHostManager* render_manager = frame_tree_node->render_manager(); content::RenderFrameHost* frame_host = nullptr; if (render_manager) { frame_host = render_manager->speculative_frame_host(); if (!frame_host) frame_host = render_manager->current_frame_host(); } int frame_process_id = -1, frame_routing_id = -1; if (frame_host) { frame_process_id = frame_host->GetProcess()->GetID(); frame_routing_id = frame_host->GetRoutingID(); } bool is_same_document = navigation_handle->IsSameDocument(); auto url = navigation_handle->GetURL(); return Emit(event, url, is_same_document, is_main_frame, frame_process_id, frame_routing_id); } void WebContents::Message(bool internal, const std::string& channel, blink::CloneableMessage arguments, content::RenderFrameHost* render_frame_host) { TRACE_EVENT1("electron", "WebContents::Message", "channel", channel); // webContents.emit('-ipc-message', new Event(), internal, channel, // arguments); EmitWithSender("-ipc-message", render_frame_host, electron::mojom::ElectronApiIPC::InvokeCallback(), internal, channel, std::move(arguments)); } void WebContents::Invoke( bool internal, const std::string& channel, blink::CloneableMessage arguments, electron::mojom::ElectronApiIPC::InvokeCallback callback, content::RenderFrameHost* render_frame_host) { TRACE_EVENT1("electron", "WebContents::Invoke", "channel", channel); // webContents.emit('-ipc-invoke', new Event(), internal, channel, arguments); EmitWithSender("-ipc-invoke", render_frame_host, std::move(callback), internal, channel, std::move(arguments)); } void WebContents::OnFirstNonEmptyLayout( content::RenderFrameHost* render_frame_host) { if (render_frame_host == web_contents()->GetMainFrame()) { Emit("ready-to-show"); } } void WebContents::ReceivePostMessage( const std::string& channel, blink::TransferableMessage message, content::RenderFrameHost* render_frame_host) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); auto wrapped_ports = MessagePort::EntanglePorts(isolate, std::move(message.ports)); v8::Local<v8::Value> message_value = electron::DeserializeV8Value(isolate, message); EmitWithSender("-ipc-ports", render_frame_host, electron::mojom::ElectronApiIPC::InvokeCallback(), false, channel, message_value, std::move(wrapped_ports)); } void WebContents::MessageSync( bool internal, const std::string& channel, blink::CloneableMessage arguments, electron::mojom::ElectronApiIPC::MessageSyncCallback callback, content::RenderFrameHost* render_frame_host) { TRACE_EVENT1("electron", "WebContents::MessageSync", "channel", channel); // webContents.emit('-ipc-message-sync', new Event(sender, message), internal, // channel, arguments); EmitWithSender("-ipc-message-sync", render_frame_host, std::move(callback), internal, channel, std::move(arguments)); } void WebContents::MessageTo(int32_t web_contents_id, const std::string& channel, blink::CloneableMessage arguments) { TRACE_EVENT1("electron", "WebContents::MessageTo", "channel", channel); auto* target_web_contents = FromID(web_contents_id); if (target_web_contents) { content::RenderFrameHost* frame = target_web_contents->MainFrame(); DCHECK(frame); v8::HandleScope handle_scope(JavascriptEnvironment::GetIsolate()); gin::Handle<WebFrameMain> web_frame_main = WebFrameMain::From(JavascriptEnvironment::GetIsolate(), frame); if (!web_frame_main->CheckRenderFrame()) return; int32_t sender_id = ID(); web_frame_main->GetRendererApi()->Message(false /* internal */, channel, std::move(arguments), sender_id); } } void WebContents::MessageHost(const std::string& channel, blink::CloneableMessage arguments, content::RenderFrameHost* render_frame_host) { TRACE_EVENT1("electron", "WebContents::MessageHost", "channel", channel); // webContents.emit('ipc-message-host', new Event(), channel, args); EmitWithSender("ipc-message-host", render_frame_host, electron::mojom::ElectronApiIPC::InvokeCallback(), channel, std::move(arguments)); } void WebContents::UpdateDraggableRegions( std::vector<mojom::DraggableRegionPtr> regions) { for (ExtendedWebContentsObserver& observer : observers_) observer.OnDraggableRegionsUpdated(regions); } void WebContents::DidStartNavigation( content::NavigationHandle* navigation_handle) { EmitNavigationEvent("did-start-navigation", navigation_handle); } void WebContents::DidRedirectNavigation( content::NavigationHandle* navigation_handle) { EmitNavigationEvent("did-redirect-navigation", navigation_handle); } void WebContents::ReadyToCommitNavigation( content::NavigationHandle* navigation_handle) { // Don't focus content in an inactive window. if (!owner_window()) return; #if BUILDFLAG(IS_MAC) if (!owner_window()->IsActive()) return; #else if (!owner_window()->widget()->IsActive()) return; #endif // Don't focus content after subframe navigations. if (!navigation_handle->IsInMainFrame()) return; // Only focus for top-level contents. if (type_ != Type::kBrowserWindow) return; web_contents()->SetInitialFocus(); } void WebContents::DidFinishNavigation( content::NavigationHandle* navigation_handle) { if (owner_window_) { owner_window_->NotifyLayoutWindowControlsOverlay(); } if (!navigation_handle->HasCommitted()) return; bool is_main_frame = navigation_handle->IsInMainFrame(); content::RenderFrameHost* frame_host = navigation_handle->GetRenderFrameHost(); int frame_process_id = -1, frame_routing_id = -1; if (frame_host) { frame_process_id = frame_host->GetProcess()->GetID(); frame_routing_id = frame_host->GetRoutingID(); } if (!navigation_handle->IsErrorPage()) { // FIXME: All the Emit() calls below could potentially result in |this| // being destroyed (by JS listening for the event and calling // webContents.destroy()). auto url = navigation_handle->GetURL(); bool is_same_document = navigation_handle->IsSameDocument(); if (is_same_document) { Emit("did-navigate-in-page", url, is_main_frame, frame_process_id, frame_routing_id); } else { const net::HttpResponseHeaders* http_response = navigation_handle->GetResponseHeaders(); std::string http_status_text; int http_response_code = -1; if (http_response) { http_status_text = http_response->GetStatusText(); http_response_code = http_response->response_code(); } Emit("did-frame-navigate", url, http_response_code, http_status_text, is_main_frame, frame_process_id, frame_routing_id); if (is_main_frame) { Emit("did-navigate", url, http_response_code, http_status_text); } } if (IsGuest()) Emit("load-commit", url, is_main_frame); } else { auto url = navigation_handle->GetURL(); int code = navigation_handle->GetNetErrorCode(); auto description = net::ErrorToShortString(code); Emit("did-fail-provisional-load", code, description, url, is_main_frame, frame_process_id, frame_routing_id); // Do not emit "did-fail-load" for canceled requests. if (code != net::ERR_ABORTED) { EmitWarning( node::Environment::GetCurrent(JavascriptEnvironment::GetIsolate()), "Failed to load URL: " + url.possibly_invalid_spec() + " with error: " + description, "electron"); Emit("did-fail-load", code, description, url, is_main_frame, frame_process_id, frame_routing_id); } } content::NavigationEntry* entry = navigation_handle->GetNavigationEntry(); // This check is needed due to an issue in Chromium // Check the Chromium issue to keep updated: // https://bugs.chromium.org/p/chromium/issues/detail?id=1178663 // If a history entry has been made and the forward/back call has been made, // proceed with setting the new title if (entry && (entry->GetTransitionType() & ui::PAGE_TRANSITION_FORWARD_BACK)) WebContents::TitleWasSet(entry); } void WebContents::TitleWasSet(content::NavigationEntry* entry) { std::u16string final_title; bool explicit_set = true; if (entry) { auto title = entry->GetTitle(); auto url = entry->GetURL(); if (url.SchemeIsFile() && title.empty()) { final_title = base::UTF8ToUTF16(url.ExtractFileName()); explicit_set = false; } else { final_title = title; } } else { final_title = web_contents()->GetTitle(); } for (ExtendedWebContentsObserver& observer : observers_) observer.OnPageTitleUpdated(final_title, explicit_set); Emit("page-title-updated", final_title, explicit_set); } void WebContents::DidUpdateFaviconURL( content::RenderFrameHost* render_frame_host, const std::vector<blink::mojom::FaviconURLPtr>& urls) { std::set<GURL> unique_urls; for (const auto& iter : urls) { if (iter->icon_type != blink::mojom::FaviconIconType::kFavicon) continue; const GURL& url = iter->icon_url; if (url.is_valid()) unique_urls.insert(url); } Emit("page-favicon-updated", unique_urls); } void WebContents::DevToolsReloadPage() { Emit("devtools-reload-page"); } void WebContents::DevToolsFocused() { Emit("devtools-focused"); } void WebContents::DevToolsOpened() { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::Locker locker(isolate); v8::HandleScope handle_scope(isolate); DCHECK(inspectable_web_contents_); DCHECK(inspectable_web_contents_->GetDevToolsWebContents()); auto handle = FromOrCreate( isolate, inspectable_web_contents_->GetDevToolsWebContents()); devtools_web_contents_.Reset(isolate, handle.ToV8()); // Set inspected tabID. base::Value tab_id(ID()); inspectable_web_contents_->CallClientFunction("DevToolsAPI.setInspectedTabId", &tab_id, nullptr, nullptr); // Inherit owner window in devtools when it doesn't have one. auto* devtools = inspectable_web_contents_->GetDevToolsWebContents(); bool has_window = devtools->GetUserData(NativeWindowRelay::UserDataKey()); if (owner_window() && !has_window) handle->SetOwnerWindow(devtools, owner_window()); Emit("devtools-opened"); } void WebContents::DevToolsClosed() { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::Locker locker(isolate); v8::HandleScope handle_scope(isolate); devtools_web_contents_.Reset(); Emit("devtools-closed"); } void WebContents::DevToolsResized() { for (ExtendedWebContentsObserver& observer : observers_) observer.OnDevToolsResized(); } void WebContents::SetOwnerWindow(NativeWindow* owner_window) { SetOwnerWindow(GetWebContents(), owner_window); } void WebContents::SetOwnerWindow(content::WebContents* web_contents, NativeWindow* owner_window) { if (owner_window) { owner_window_ = owner_window->GetWeakPtr(); NativeWindowRelay::CreateForWebContents(web_contents, owner_window->GetWeakPtr()); } else { owner_window_ = nullptr; web_contents->RemoveUserData(NativeWindowRelay::UserDataKey()); } #if BUILDFLAG(ENABLE_OSR) auto* osr_wcv = GetOffScreenWebContentsView(); if (osr_wcv) osr_wcv->SetNativeWindow(owner_window); #endif } content::WebContents* WebContents::GetWebContents() const { if (!inspectable_web_contents_) return nullptr; return inspectable_web_contents_->GetWebContents(); } content::WebContents* WebContents::GetDevToolsWebContents() const { if (!inspectable_web_contents_) return nullptr; return inspectable_web_contents_->GetDevToolsWebContents(); } void WebContents::WebContentsDestroyed() { // Clear the pointer stored in wrapper. if (GetAllWebContents().Lookup(id_)) GetAllWebContents().Remove(id_); v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); v8::Local<v8::Object> wrapper; if (!GetWrapper(isolate).ToLocal(&wrapper)) return; wrapper->SetAlignedPointerInInternalField(0, nullptr); // Tell WebViewGuestDelegate that the WebContents has been destroyed. if (guest_delegate_) guest_delegate_->WillDestroy(); Observe(nullptr); Emit("destroyed"); } void WebContents::NavigationEntryCommitted( const content::LoadCommittedDetails& details) { Emit("navigation-entry-committed", details.entry->GetURL(), details.is_same_document, details.did_replace_entry); } bool WebContents::GetBackgroundThrottling() const { return background_throttling_; } void WebContents::SetBackgroundThrottling(bool allowed) { background_throttling_ = allowed; auto* rfh = web_contents()->GetMainFrame(); if (!rfh) return; auto* rwhv = rfh->GetView(); if (!rwhv) return; auto* rwh_impl = static_cast<content::RenderWidgetHostImpl*>(rwhv->GetRenderWidgetHost()); if (!rwh_impl) return; rwh_impl->disable_hidden_ = !background_throttling_; web_contents()->GetRenderViewHost()->SetSchedulerThrottling(allowed); if (rwh_impl->is_hidden()) { rwh_impl->WasShown({}); } } int WebContents::GetProcessID() const { return web_contents()->GetMainFrame()->GetProcess()->GetID(); } base::ProcessId WebContents::GetOSProcessID() const { base::ProcessHandle process_handle = web_contents()->GetMainFrame()->GetProcess()->GetProcess().Handle(); return base::GetProcId(process_handle); } WebContents::Type WebContents::GetType() const { return type_; } bool WebContents::Equal(const WebContents* web_contents) const { return ID() == web_contents->ID(); } GURL WebContents::GetURL() const { return web_contents()->GetLastCommittedURL(); } void WebContents::LoadURL(const GURL& url, const gin_helper::Dictionary& options) { if (!url.is_valid() || url.spec().size() > url::kMaxURLChars) { Emit("did-fail-load", static_cast<int>(net::ERR_INVALID_URL), net::ErrorToShortString(net::ERR_INVALID_URL), url.possibly_invalid_spec(), true); return; } content::NavigationController::LoadURLParams params(url); if (!options.Get("httpReferrer", &params.referrer)) { GURL http_referrer; if (options.Get("httpReferrer", &http_referrer)) params.referrer = content::Referrer(http_referrer.GetAsReferrer(), network::mojom::ReferrerPolicy::kDefault); } std::string user_agent; if (options.Get("userAgent", &user_agent)) web_contents()->SetUserAgentOverride( blink::UserAgentOverride::UserAgentOnly(user_agent), false); std::string extra_headers; if (options.Get("extraHeaders", &extra_headers)) params.extra_headers = extra_headers; scoped_refptr<network::ResourceRequestBody> body; if (options.Get("postData", &body)) { params.post_data = body; params.load_type = content::NavigationController::LOAD_TYPE_HTTP_POST; } GURL base_url_for_data_url; if (options.Get("baseURLForDataURL", &base_url_for_data_url)) { params.base_url_for_data_url = base_url_for_data_url; params.load_type = content::NavigationController::LOAD_TYPE_DATA; } bool reload_ignoring_cache = false; if (options.Get("reloadIgnoringCache", &reload_ignoring_cache) && reload_ignoring_cache) { params.reload_type = content::ReloadType::BYPASSING_CACHE; } // Calling LoadURLWithParams() can trigger JS which destroys |this|. auto weak_this = GetWeakPtr(); params.transition_type = ui::PageTransitionFromInt( ui::PAGE_TRANSITION_TYPED | ui::PAGE_TRANSITION_FROM_ADDRESS_BAR); params.override_user_agent = content::NavigationController::UA_OVERRIDE_TRUE; // Discord non-committed entries to ensure that we don't re-use a pending // entry web_contents()->GetController().DiscardNonCommittedEntries(); web_contents()->GetController().LoadURLWithParams(params); // ⚠️WARNING!⚠️ // LoadURLWithParams() triggers JS events which can call destroy() on |this|. // It's not safe to assume that |this| points to valid memory at this point. if (!weak_this || !web_contents()) return; // Required to make beforeunload handler work. NotifyUserActivation(); } // TODO(MarshallOfSound): Figure out what we need to do with post data here, I // believe the default behavior when we pass "true" is to phone out to the // delegate and then the controller expects this method to be called again with // "false" if the user approves the reload. For now this would result in // ".reload()" calls on POST data domains failing silently. Passing false would // result in them succeeding, but reposting which although more correct could be // considering a breaking change. void WebContents::Reload() { web_contents()->GetController().Reload(content::ReloadType::NORMAL, /* check_for_repost */ true); } void WebContents::ReloadIgnoringCache() { web_contents()->GetController().Reload(content::ReloadType::BYPASSING_CACHE, /* check_for_repost */ true); } void WebContents::DownloadURL(const GURL& url) { auto* browser_context = web_contents()->GetBrowserContext(); auto* download_manager = browser_context->GetDownloadManager(); std::unique_ptr<download::DownloadUrlParameters> download_params( content::DownloadRequestUtils::CreateDownloadForWebContentsMainFrame( web_contents(), url, MISSING_TRAFFIC_ANNOTATION)); download_manager->DownloadUrl(std::move(download_params)); } std::u16string WebContents::GetTitle() const { return web_contents()->GetTitle(); } bool WebContents::IsLoading() const { return web_contents()->IsLoading(); } bool WebContents::IsLoadingMainFrame() const { return web_contents()->ShouldShowLoadingUI(); } bool WebContents::IsWaitingForResponse() const { return web_contents()->IsWaitingForResponse(); } void WebContents::Stop() { web_contents()->Stop(); } bool WebContents::CanGoBack() const { return web_contents()->GetController().CanGoBack(); } void WebContents::GoBack() { if (CanGoBack()) web_contents()->GetController().GoBack(); } bool WebContents::CanGoForward() const { return web_contents()->GetController().CanGoForward(); } void WebContents::GoForward() { if (CanGoForward()) web_contents()->GetController().GoForward(); } bool WebContents::CanGoToOffset(int offset) const { return web_contents()->GetController().CanGoToOffset(offset); } void WebContents::GoToOffset(int offset) { if (CanGoToOffset(offset)) web_contents()->GetController().GoToOffset(offset); } bool WebContents::CanGoToIndex(int index) const { return index >= 0 && index < GetHistoryLength(); } void WebContents::GoToIndex(int index) { if (CanGoToIndex(index)) web_contents()->GetController().GoToIndex(index); } int WebContents::GetActiveIndex() const { return web_contents()->GetController().GetCurrentEntryIndex(); } void WebContents::ClearHistory() { // In some rare cases (normally while there is no real history) we are in a // state where we can't prune navigation entries if (web_contents()->GetController().CanPruneAllButLastCommitted()) { web_contents()->GetController().PruneAllButLastCommitted(); } } int WebContents::GetHistoryLength() const { return web_contents()->GetController().GetEntryCount(); } const std::string WebContents::GetWebRTCIPHandlingPolicy() const { return web_contents()->GetMutableRendererPrefs()->webrtc_ip_handling_policy; } void WebContents::SetWebRTCIPHandlingPolicy( const std::string& webrtc_ip_handling_policy) { if (GetWebRTCIPHandlingPolicy() == webrtc_ip_handling_policy) return; web_contents()->GetMutableRendererPrefs()->webrtc_ip_handling_policy = webrtc_ip_handling_policy; web_contents()->SyncRendererPrefs(); } std::string WebContents::GetMediaSourceID( content::WebContents* request_web_contents) { auto* frame_host = web_contents()->GetMainFrame(); if (!frame_host) return std::string(); content::DesktopMediaID media_id( content::DesktopMediaID::TYPE_WEB_CONTENTS, content::DesktopMediaID::kNullId, content::WebContentsMediaCaptureId(frame_host->GetProcess()->GetID(), frame_host->GetRoutingID())); auto* request_frame_host = request_web_contents->GetMainFrame(); if (!request_frame_host) return std::string(); std::string id = content::DesktopStreamsRegistry::GetInstance()->RegisterStream( request_frame_host->GetProcess()->GetID(), request_frame_host->GetRoutingID(), url::Origin::Create(request_frame_host->GetLastCommittedURL() .DeprecatedGetOriginAsURL()), media_id, "", content::kRegistryStreamTypeTab); return id; } bool WebContents::IsCrashed() const { return web_contents()->IsCrashed(); } void WebContents::ForcefullyCrashRenderer() { content::RenderWidgetHostView* view = web_contents()->GetRenderWidgetHostView(); if (!view) return; content::RenderWidgetHost* rwh = view->GetRenderWidgetHost(); if (!rwh) return; content::RenderProcessHost* rph = rwh->GetProcess(); if (rph) { #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) // A generic |CrashDumpHungChildProcess()| is not implemented for Linux. // Instead we send an explicit IPC to crash on the renderer's IO thread. rph->ForceCrash(); #else // Try to generate a crash report for the hung process. #ifndef MAS_BUILD CrashDumpHungChildProcess(rph->GetProcess().Handle()); #endif rph->Shutdown(content::RESULT_CODE_HUNG); #endif } } void WebContents::SetUserAgent(const std::string& user_agent) { web_contents()->SetUserAgentOverride( blink::UserAgentOverride::UserAgentOnly(user_agent), false); } std::string WebContents::GetUserAgent() { return web_contents()->GetUserAgentOverride().ua_string_override; } v8::Local<v8::Promise> WebContents::SavePage( const base::FilePath& full_file_path, const content::SavePageType& save_type) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); gin_helper::Promise<void> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); if (!full_file_path.IsAbsolute()) { promise.RejectWithErrorMessage("Path must be absolute"); return handle; } auto* handler = new SavePageHandler(web_contents(), std::move(promise)); handler->Handle(full_file_path, save_type); return handle; } void WebContents::OpenDevTools(gin::Arguments* args) { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; std::string state; if (type_ == Type::kWebView || type_ == Type::kBackgroundPage || !owner_window()) { state = "detach"; } bool activate = true; if (args && args->Length() == 1) { gin_helper::Dictionary options; if (args->GetNext(&options)) { options.Get("mode", &state); options.Get("activate", &activate); } } DCHECK(inspectable_web_contents_); inspectable_web_contents_->SetDockState(state); inspectable_web_contents_->ShowDevTools(activate); } void WebContents::CloseDevTools() { if (type_ == Type::kRemote) return; DCHECK(inspectable_web_contents_); inspectable_web_contents_->CloseDevTools(); } bool WebContents::IsDevToolsOpened() { if (type_ == Type::kRemote) return false; DCHECK(inspectable_web_contents_); return inspectable_web_contents_->IsDevToolsViewShowing(); } bool WebContents::IsDevToolsFocused() { if (type_ == Type::kRemote) return false; DCHECK(inspectable_web_contents_); return inspectable_web_contents_->GetView()->IsDevToolsViewFocused(); } void WebContents::EnableDeviceEmulation( const blink::DeviceEmulationParams& params) { if (type_ == Type::kRemote) return; DCHECK(web_contents()); auto* frame_host = web_contents()->GetMainFrame(); if (frame_host) { auto* widget_host_impl = static_cast<content::RenderWidgetHostImpl*>( frame_host->GetView()->GetRenderWidgetHost()); if (widget_host_impl) { auto& frame_widget = widget_host_impl->GetAssociatedFrameWidget(); frame_widget->EnableDeviceEmulation(params); } } } void WebContents::DisableDeviceEmulation() { if (type_ == Type::kRemote) return; DCHECK(web_contents()); auto* frame_host = web_contents()->GetMainFrame(); if (frame_host) { auto* widget_host_impl = static_cast<content::RenderWidgetHostImpl*>( frame_host->GetView()->GetRenderWidgetHost()); if (widget_host_impl) { auto& frame_widget = widget_host_impl->GetAssociatedFrameWidget(); frame_widget->DisableDeviceEmulation(); } } } void WebContents::ToggleDevTools() { if (IsDevToolsOpened()) CloseDevTools(); else OpenDevTools(nullptr); } void WebContents::InspectElement(int x, int y) { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; DCHECK(inspectable_web_contents_); if (!inspectable_web_contents_->GetDevToolsWebContents()) OpenDevTools(nullptr); inspectable_web_contents_->InspectElement(x, y); } void WebContents::InspectSharedWorkerById(const std::string& workerId) { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) { if (agent_host->GetType() == content::DevToolsAgentHost::kTypeSharedWorker) { if (agent_host->GetId() == workerId) { OpenDevTools(nullptr); inspectable_web_contents_->AttachTo(agent_host); break; } } } } std::vector<scoped_refptr<content::DevToolsAgentHost>> WebContents::GetAllSharedWorkers() { std::vector<scoped_refptr<content::DevToolsAgentHost>> shared_workers; if (type_ == Type::kRemote) return shared_workers; if (!enable_devtools_) return shared_workers; for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) { if (agent_host->GetType() == content::DevToolsAgentHost::kTypeSharedWorker) { shared_workers.push_back(agent_host); } } return shared_workers; } void WebContents::InspectSharedWorker() { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) { if (agent_host->GetType() == content::DevToolsAgentHost::kTypeSharedWorker) { OpenDevTools(nullptr); inspectable_web_contents_->AttachTo(agent_host); break; } } } void WebContents::InspectServiceWorker() { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) { if (agent_host->GetType() == content::DevToolsAgentHost::kTypeServiceWorker) { OpenDevTools(nullptr); inspectable_web_contents_->AttachTo(agent_host); break; } } } void WebContents::SetIgnoreMenuShortcuts(bool ignore) { auto* web_preferences = WebContentsPreferences::From(web_contents()); DCHECK(web_preferences); web_preferences->SetIgnoreMenuShortcuts(ignore); } void WebContents::SetAudioMuted(bool muted) { web_contents()->SetAudioMuted(muted); } bool WebContents::IsAudioMuted() { return web_contents()->IsAudioMuted(); } bool WebContents::IsCurrentlyAudible() { return web_contents()->IsCurrentlyAudible(); } #if BUILDFLAG(ENABLE_PRINTING) void WebContents::OnGetDefaultPrinter( base::Value print_settings, printing::CompletionCallback print_callback, std::u16string device_name, bool silent, // <error, default_printer> std::pair<std::string, std::u16string> info) { // The content::WebContents might be already deleted at this point, and the // PrintViewManagerElectron class does not do null check. if (!web_contents()) { if (print_callback) std::move(print_callback).Run(false, "failed"); return; } if (!info.first.empty()) { if (print_callback) std::move(print_callback).Run(false, info.first); return; } // If the user has passed a deviceName use it, otherwise use default printer. std::u16string printer_name = device_name.empty() ? info.second : device_name; // If there are no valid printers available on the network, we bail. if (printer_name.empty() || !IsDeviceNameValid(printer_name)) { if (print_callback) std::move(print_callback).Run(false, "no valid printers available"); return; } print_settings.SetStringKey(printing::kSettingDeviceName, printer_name); auto* print_view_manager = PrintViewManagerElectron::FromWebContents(web_contents()); if (!print_view_manager) return; auto* focused_frame = web_contents()->GetFocusedFrame(); auto* rfh = focused_frame && focused_frame->HasSelection() ? focused_frame : web_contents()->GetMainFrame(); print_view_manager->PrintNow(rfh, silent, std::move(print_settings), std::move(print_callback)); } void WebContents::Print(gin::Arguments* args) { gin_helper::Dictionary options = gin::Dictionary::CreateEmpty(args->isolate()); base::Value settings(base::Value::Type::DICTIONARY); if (args->Length() >= 1 && !args->GetNext(&options)) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("webContents.print(): Invalid print settings specified."); return; } printing::CompletionCallback callback; if (args->Length() == 2 && !args->GetNext(&callback)) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("webContents.print(): Invalid optional callback provided."); return; } // Set optional silent printing bool silent = false; options.Get("silent", &silent); bool print_background = false; options.Get("printBackground", &print_background); settings.SetBoolKey(printing::kSettingShouldPrintBackgrounds, print_background); // Set custom margin settings gin_helper::Dictionary margins = gin::Dictionary::CreateEmpty(args->isolate()); if (options.Get("margins", &margins)) { printing::mojom::MarginType margin_type = printing::mojom::MarginType::kDefaultMargins; margins.Get("marginType", &margin_type); settings.SetIntKey(printing::kSettingMarginsType, static_cast<int>(margin_type)); if (margin_type == printing::mojom::MarginType::kCustomMargins) { base::Value custom_margins(base::Value::Type::DICTIONARY); int top = 0; margins.Get("top", &top); custom_margins.SetIntKey(printing::kSettingMarginTop, top); int bottom = 0; margins.Get("bottom", &bottom); custom_margins.SetIntKey(printing::kSettingMarginBottom, bottom); int left = 0; margins.Get("left", &left); custom_margins.SetIntKey(printing::kSettingMarginLeft, left); int right = 0; margins.Get("right", &right); custom_margins.SetIntKey(printing::kSettingMarginRight, right); settings.SetPath(printing::kSettingMarginsCustom, std::move(custom_margins)); } } else { settings.SetIntKey( printing::kSettingMarginsType, static_cast<int>(printing::mojom::MarginType::kDefaultMargins)); } // Set whether to print color or greyscale bool print_color = true; options.Get("color", &print_color); auto const color_model = print_color ? printing::mojom::ColorModel::kColor : printing::mojom::ColorModel::kGray; settings.SetIntKey(printing::kSettingColor, static_cast<int>(color_model)); // Is the orientation landscape or portrait. bool landscape = false; options.Get("landscape", &landscape); settings.SetBoolKey(printing::kSettingLandscape, landscape); // We set the default to the system's default printer and only update // if at the Chromium level if the user overrides. // Printer device name as opened by the OS. std::u16string device_name; options.Get("deviceName", &device_name); if (!device_name.empty() && !IsDeviceNameValid(device_name)) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("webContents.print(): Invalid deviceName provided."); return; } int scale_factor = 100; options.Get("scaleFactor", &scale_factor); settings.SetIntKey(printing::kSettingScaleFactor, scale_factor); int pages_per_sheet = 1; options.Get("pagesPerSheet", &pages_per_sheet); settings.SetIntKey(printing::kSettingPagesPerSheet, pages_per_sheet); // True if the user wants to print with collate. bool collate = true; options.Get("collate", &collate); settings.SetBoolKey(printing::kSettingCollate, collate); // The number of individual copies to print int copies = 1; options.Get("copies", &copies); settings.SetIntKey(printing::kSettingCopies, copies); // Strings to be printed as headers and footers if requested by the user. std::string header; options.Get("header", &header); std::string footer; options.Get("footer", &footer); if (!(header.empty() && footer.empty())) { settings.SetBoolKey(printing::kSettingHeaderFooterEnabled, true); settings.SetStringKey(printing::kSettingHeaderFooterTitle, header); settings.SetStringKey(printing::kSettingHeaderFooterURL, footer); } else { settings.SetBoolKey(printing::kSettingHeaderFooterEnabled, false); } // We don't want to allow the user to enable these settings // but we need to set them or a CHECK is hit. settings.SetIntKey(printing::kSettingPrinterType, static_cast<int>(printing::mojom::PrinterType::kLocal)); settings.SetBoolKey(printing::kSettingShouldPrintSelectionOnly, false); settings.SetBoolKey(printing::kSettingRasterizePdf, false); // Set custom page ranges to print std::vector<gin_helper::Dictionary> page_ranges; if (options.Get("pageRanges", &page_ranges)) { base::Value page_range_list(base::Value::Type::LIST); for (auto& range : page_ranges) { int from, to; if (range.Get("from", &from) && range.Get("to", &to)) { base::Value range(base::Value::Type::DICTIONARY); // Chromium uses 1-based page ranges, so increment each by 1. range.SetIntKey(printing::kSettingPageRangeFrom, from + 1); range.SetIntKey(printing::kSettingPageRangeTo, to + 1); page_range_list.Append(std::move(range)); } else { continue; } } if (!page_range_list.GetListDeprecated().empty()) settings.SetPath(printing::kSettingPageRange, std::move(page_range_list)); } // Duplex type user wants to use. printing::mojom::DuplexMode duplex_mode = printing::mojom::DuplexMode::kSimplex; options.Get("duplexMode", &duplex_mode); settings.SetIntKey(printing::kSettingDuplexMode, static_cast<int>(duplex_mode)); // We've already done necessary parameter sanitization at the // JS level, so we can simply pass this through. base::Value media_size(base::Value::Type::DICTIONARY); if (options.Get("mediaSize", &media_size)) settings.SetKey(printing::kSettingMediaSize, std::move(media_size)); // Set custom dots per inch (dpi) gin_helper::Dictionary dpi_settings; int dpi = 72; if (options.Get("dpi", &dpi_settings)) { int horizontal = 72; dpi_settings.Get("horizontal", &horizontal); settings.SetIntKey(printing::kSettingDpiHorizontal, horizontal); int vertical = 72; dpi_settings.Get("vertical", &vertical); settings.SetIntKey(printing::kSettingDpiVertical, vertical); } else { settings.SetIntKey(printing::kSettingDpiHorizontal, dpi); settings.SetIntKey(printing::kSettingDpiVertical, dpi); } print_task_runner_->PostTaskAndReplyWithResult( FROM_HERE, base::BindOnce(&GetDefaultPrinterAsync), base::BindOnce(&WebContents::OnGetDefaultPrinter, weak_factory_.GetWeakPtr(), std::move(settings), std::move(callback), device_name, silent)); } v8::Local<v8::Promise> WebContents::PrintToPDF(base::DictionaryValue settings) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); gin_helper::Promise<v8::Local<v8::Value>> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); PrintPreviewMessageHandler::FromWebContents(web_contents()) ->PrintToPDF(std::move(settings), std::move(promise)); return handle; } #endif void WebContents::AddWorkSpace(gin::Arguments* args, const base::FilePath& path) { if (path.empty()) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("path cannot be empty"); return; } DevToolsAddFileSystem(std::string(), path); } void WebContents::RemoveWorkSpace(gin::Arguments* args, const base::FilePath& path) { if (path.empty()) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("path cannot be empty"); return; } DevToolsRemoveFileSystem(path); } void WebContents::Undo() { web_contents()->Undo(); } void WebContents::Redo() { web_contents()->Redo(); } void WebContents::Cut() { web_contents()->Cut(); } void WebContents::Copy() { web_contents()->Copy(); } void WebContents::Paste() { web_contents()->Paste(); } void WebContents::PasteAndMatchStyle() { web_contents()->PasteAndMatchStyle(); } void WebContents::Delete() { web_contents()->Delete(); } void WebContents::SelectAll() { web_contents()->SelectAll(); } void WebContents::Unselect() { web_contents()->CollapseSelection(); } void WebContents::Replace(const std::u16string& word) { web_contents()->Replace(word); } void WebContents::ReplaceMisspelling(const std::u16string& word) { web_contents()->ReplaceMisspelling(word); } uint32_t WebContents::FindInPage(gin::Arguments* args) { std::u16string search_text; if (!args->GetNext(&search_text) || search_text.empty()) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("Must provide a non-empty search content"); return 0; } uint32_t request_id = ++find_in_page_request_id_; gin_helper::Dictionary dict; auto options = blink::mojom::FindOptions::New(); if (args->GetNext(&dict)) { dict.Get("forward", &options->forward); dict.Get("matchCase", &options->match_case); dict.Get("findNext", &options->new_session); } web_contents()->Find(request_id, search_text, std::move(options)); return request_id; } void WebContents::StopFindInPage(content::StopFindAction action) { web_contents()->StopFinding(action); } void WebContents::ShowDefinitionForSelection() { #if BUILDFLAG(IS_MAC) auto* const view = web_contents()->GetRenderWidgetHostView(); if (view) view->ShowDefinitionForSelection(); #endif } void WebContents::CopyImageAt(int x, int y) { auto* const host = web_contents()->GetMainFrame(); if (host) host->CopyImageAt(x, y); } void WebContents::Focus() { // Focusing on WebContents does not automatically focus the window on macOS // and Linux, do it manually to match the behavior on Windows. #if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX) if (owner_window()) owner_window()->Focus(true); #endif web_contents()->Focus(); } #if !BUILDFLAG(IS_MAC) bool WebContents::IsFocused() const { auto* view = web_contents()->GetRenderWidgetHostView(); if (!view) return false; if (GetType() != Type::kBackgroundPage) { auto* window = web_contents()->GetNativeView()->GetToplevelWindow(); if (window && !window->IsVisible()) return false; } return view->HasFocus(); } #endif void WebContents::SendInputEvent(v8::Isolate* isolate, v8::Local<v8::Value> input_event) { content::RenderWidgetHostView* view = web_contents()->GetRenderWidgetHostView(); if (!view) return; content::RenderWidgetHost* rwh = view->GetRenderWidgetHost(); blink::WebInputEvent::Type type = gin::GetWebInputEventType(isolate, input_event); if (blink::WebInputEvent::IsMouseEventType(type)) { blink::WebMouseEvent mouse_event; if (gin::ConvertFromV8(isolate, input_event, &mouse_event)) { if (IsOffScreen()) { #if BUILDFLAG(ENABLE_OSR) GetOffScreenRenderWidgetHostView()->SendMouseEvent(mouse_event); #endif } else { rwh->ForwardMouseEvent(mouse_event); } return; } } else if (blink::WebInputEvent::IsKeyboardEventType(type)) { content::NativeWebKeyboardEvent keyboard_event( blink::WebKeyboardEvent::Type::kRawKeyDown, blink::WebInputEvent::Modifiers::kNoModifiers, ui::EventTimeForNow()); if (gin::ConvertFromV8(isolate, input_event, &keyboard_event)) { rwh->ForwardKeyboardEvent(keyboard_event); return; } } else if (type == blink::WebInputEvent::Type::kMouseWheel) { blink::WebMouseWheelEvent mouse_wheel_event; if (gin::ConvertFromV8(isolate, input_event, &mouse_wheel_event)) { if (IsOffScreen()) { #if BUILDFLAG(ENABLE_OSR) GetOffScreenRenderWidgetHostView()->SendMouseWheelEvent( mouse_wheel_event); #endif } else { // Chromium expects phase info in wheel events (and applies a // DCHECK to verify it). See: https://crbug.com/756524. mouse_wheel_event.phase = blink::WebMouseWheelEvent::kPhaseBegan; mouse_wheel_event.dispatch_type = blink::WebInputEvent::DispatchType::kBlocking; rwh->ForwardWheelEvent(mouse_wheel_event); // Send a synthetic wheel event with phaseEnded to finish scrolling. mouse_wheel_event.has_synthetic_phase = true; mouse_wheel_event.delta_x = 0; mouse_wheel_event.delta_y = 0; mouse_wheel_event.phase = blink::WebMouseWheelEvent::kPhaseEnded; mouse_wheel_event.dispatch_type = blink::WebInputEvent::DispatchType::kEventNonBlocking; rwh->ForwardWheelEvent(mouse_wheel_event); } return; } } isolate->ThrowException( v8::Exception::Error(gin::StringToV8(isolate, "Invalid event object"))); } void WebContents::BeginFrameSubscription(gin::Arguments* args) { bool only_dirty = false; FrameSubscriber::FrameCaptureCallback callback; if (args->Length() > 1) { if (!args->GetNext(&only_dirty)) { args->ThrowError(); return; } } if (!args->GetNext(&callback)) { args->ThrowError(); return; } frame_subscriber_ = std::make_unique<FrameSubscriber>(web_contents(), callback, only_dirty); } void WebContents::EndFrameSubscription() { frame_subscriber_.reset(); } void WebContents::StartDrag(const gin_helper::Dictionary& item, gin::Arguments* args) { base::FilePath file; std::vector<base::FilePath> files; if (!item.Get("files", &files) && item.Get("file", &file)) { files.push_back(file); } v8::Local<v8::Value> icon_value; if (!item.Get("icon", &icon_value)) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("'icon' parameter is required"); return; } NativeImage* icon = nullptr; if (!NativeImage::TryConvertNativeImage(args->isolate(), icon_value, &icon) || icon->image().IsEmpty()) { return; } // Start dragging. if (!files.empty()) { base::CurrentThread::ScopedNestableTaskAllower allow; DragFileItems(files, icon->image(), web_contents()->GetNativeView()); } else { gin_helper::ErrorThrower(args->isolate()) .ThrowError("Must specify either 'file' or 'files' option"); } } v8::Local<v8::Promise> WebContents::CapturePage(gin::Arguments* args) { gfx::Rect rect; gin_helper::Promise<gfx::Image> promise(args->isolate()); v8::Local<v8::Promise> handle = promise.GetHandle(); // get rect arguments if they exist args->GetNext(&rect); auto* const view = web_contents()->GetRenderWidgetHostView(); if (!view) { promise.Resolve(gfx::Image()); return handle; } #if !BUILDFLAG(IS_MAC) // If the view's renderer is suspended this may fail on Windows/Linux - // bail if so. See CopyFromSurface in // content/public/browser/render_widget_host_view.h. auto* rfh = web_contents()->GetMainFrame(); if (rfh && rfh->GetVisibilityState() == blink::mojom::PageVisibilityState::kHidden) { promise.Resolve(gfx::Image()); return handle; } #endif // BUILDFLAG(IS_MAC) // Capture full page if user doesn't specify a |rect|. const gfx::Size view_size = rect.IsEmpty() ? view->GetViewBounds().size() : rect.size(); // By default, the requested bitmap size is the view size in screen // coordinates. However, if there's more pixel detail available on the // current system, increase the requested bitmap size to capture it all. gfx::Size bitmap_size = view_size; const gfx::NativeView native_view = view->GetNativeView(); const float scale = display::Screen::GetScreen() ->GetDisplayNearestView(native_view) .device_scale_factor(); if (scale > 1.0f) bitmap_size = gfx::ScaleToCeiledSize(view_size, scale); view->CopyFromSurface(gfx::Rect(rect.origin(), view_size), bitmap_size, base::BindOnce(&OnCapturePageDone, std::move(promise))); return handle; } void WebContents::IncrementCapturerCount(gin::Arguments* args) { gfx::Size size; bool stay_hidden = false; bool stay_awake = false; // get size arguments if they exist args->GetNext(&size); // get stayHidden arguments if they exist args->GetNext(&stay_hidden); // get stayAwake arguments if they exist args->GetNext(&stay_awake); std::ignore = web_contents() ->IncrementCapturerCount(size, stay_hidden, stay_awake) .Release(); } void WebContents::DecrementCapturerCount(gin::Arguments* args) { bool stay_hidden = false; bool stay_awake = false; // get stayHidden arguments if they exist args->GetNext(&stay_hidden); // get stayAwake arguments if they exist args->GetNext(&stay_awake); web_contents()->DecrementCapturerCount(stay_hidden, stay_awake); } bool WebContents::IsBeingCaptured() { return web_contents()->IsBeingCaptured(); } void WebContents::OnCursorChanged(const content::WebCursor& webcursor) { const ui::Cursor& cursor = webcursor.cursor(); if (cursor.type() == ui::mojom::CursorType::kCustom) { Emit("cursor-changed", CursorTypeToString(cursor), gfx::Image::CreateFrom1xBitmap(cursor.custom_bitmap()), cursor.image_scale_factor(), gfx::Size(cursor.custom_bitmap().width(), cursor.custom_bitmap().height()), cursor.custom_hotspot()); } else { Emit("cursor-changed", CursorTypeToString(cursor)); } } bool WebContents::IsGuest() const { return type_ == Type::kWebView; } void WebContents::AttachToIframe(content::WebContents* embedder_web_contents, int embedder_frame_id) { attached_ = true; if (guest_delegate_) guest_delegate_->AttachToIframe(embedder_web_contents, embedder_frame_id); } bool WebContents::IsOffScreen() const { #if BUILDFLAG(ENABLE_OSR) return type_ == Type::kOffScreen; #else return false; #endif } #if BUILDFLAG(ENABLE_OSR) void WebContents::OnPaint(const gfx::Rect& dirty_rect, const SkBitmap& bitmap) { Emit("paint", dirty_rect, gfx::Image::CreateFrom1xBitmap(bitmap)); } void WebContents::StartPainting() { auto* osr_wcv = GetOffScreenWebContentsView(); if (osr_wcv) osr_wcv->SetPainting(true); } void WebContents::StopPainting() { auto* osr_wcv = GetOffScreenWebContentsView(); if (osr_wcv) osr_wcv->SetPainting(false); } bool WebContents::IsPainting() const { auto* osr_wcv = GetOffScreenWebContentsView(); return osr_wcv && osr_wcv->IsPainting(); } void WebContents::SetFrameRate(int frame_rate) { auto* osr_wcv = GetOffScreenWebContentsView(); if (osr_wcv) osr_wcv->SetFrameRate(frame_rate); } int WebContents::GetFrameRate() const { auto* osr_wcv = GetOffScreenWebContentsView(); return osr_wcv ? osr_wcv->GetFrameRate() : 0; } #endif void WebContents::Invalidate() { if (IsOffScreen()) { #if BUILDFLAG(ENABLE_OSR) auto* osr_rwhv = GetOffScreenRenderWidgetHostView(); if (osr_rwhv) osr_rwhv->Invalidate(); #endif } else { auto* const window = owner_window(); if (window) window->Invalidate(); } } gfx::Size WebContents::GetSizeForNewRenderView(content::WebContents* wc) { if (IsOffScreen() && wc == web_contents()) { auto* relay = NativeWindowRelay::FromWebContents(web_contents()); if (relay) { auto* owner_window = relay->GetNativeWindow(); return owner_window ? owner_window->GetSize() : gfx::Size(); } } return gfx::Size(); } void WebContents::SetZoomLevel(double level) { zoom_controller_->SetZoomLevel(level); } double WebContents::GetZoomLevel() const { return zoom_controller_->GetZoomLevel(); } void WebContents::SetZoomFactor(gin_helper::ErrorThrower thrower, double factor) { if (factor < std::numeric_limits<double>::epsilon()) { thrower.ThrowError("'zoomFactor' must be a double greater than 0.0"); return; } auto level = blink::PageZoomFactorToZoomLevel(factor); SetZoomLevel(level); } double WebContents::GetZoomFactor() const { auto level = GetZoomLevel(); return blink::PageZoomLevelToZoomFactor(level); } void WebContents::SetTemporaryZoomLevel(double level) { zoom_controller_->SetTemporaryZoomLevel(level); } void WebContents::DoGetZoomLevel( electron::mojom::ElectronWebContentsUtility::DoGetZoomLevelCallback callback) { std::move(callback).Run(GetZoomLevel()); } std::vector<base::FilePath> WebContents::GetPreloadPaths() const { auto result = SessionPreferences::GetValidPreloads(GetBrowserContext()); if (auto* web_preferences = WebContentsPreferences::From(web_contents())) { base::FilePath preload; if (web_preferences->GetPreloadPath(&preload)) { result.emplace_back(preload); } } return result; } v8::Local<v8::Value> WebContents::GetLastWebPreferences( v8::Isolate* isolate) const { auto* web_preferences = WebContentsPreferences::From(web_contents()); if (!web_preferences) return v8::Null(isolate); return gin::ConvertToV8(isolate, *web_preferences->last_preference()); } v8::Local<v8::Value> WebContents::GetOwnerBrowserWindow( v8::Isolate* isolate) const { if (owner_window()) return BrowserWindow::From(isolate, owner_window()); else return v8::Null(isolate); } v8::Local<v8::Value> WebContents::Session(v8::Isolate* isolate) { return v8::Local<v8::Value>::New(isolate, session_); } content::WebContents* WebContents::HostWebContents() const { if (!embedder_) return nullptr; return embedder_->web_contents(); } void WebContents::SetEmbedder(const WebContents* embedder) { if (embedder) { NativeWindow* owner_window = nullptr; auto* relay = NativeWindowRelay::FromWebContents(embedder->web_contents()); if (relay) { owner_window = relay->GetNativeWindow(); } if (owner_window) SetOwnerWindow(owner_window); content::RenderWidgetHostView* rwhv = web_contents()->GetRenderWidgetHostView(); if (rwhv) { rwhv->Hide(); rwhv->Show(); } } } void WebContents::SetDevToolsWebContents(const WebContents* devtools) { if (inspectable_web_contents_) inspectable_web_contents_->SetDevToolsWebContents(devtools->web_contents()); } v8::Local<v8::Value> WebContents::GetNativeView(v8::Isolate* isolate) const { gfx::NativeView ptr = web_contents()->GetNativeView(); auto buffer = node::Buffer::Copy(isolate, reinterpret_cast<char*>(&ptr), sizeof(gfx::NativeView)); if (buffer.IsEmpty()) return v8::Null(isolate); else return buffer.ToLocalChecked(); } v8::Local<v8::Value> WebContents::DevToolsWebContents(v8::Isolate* isolate) { if (devtools_web_contents_.IsEmpty()) return v8::Null(isolate); else return v8::Local<v8::Value>::New(isolate, devtools_web_contents_); } v8::Local<v8::Value> WebContents::Debugger(v8::Isolate* isolate) { if (debugger_.IsEmpty()) { auto handle = electron::api::Debugger::Create(isolate, web_contents()); debugger_.Reset(isolate, handle.ToV8()); } return v8::Local<v8::Value>::New(isolate, debugger_); } content::RenderFrameHost* WebContents::MainFrame() { return web_contents()->GetMainFrame(); } void WebContents::NotifyUserActivation() { content::RenderFrameHost* frame = web_contents()->GetMainFrame(); if (frame) frame->NotifyUserActivation( blink::mojom::UserActivationNotificationType::kInteraction); } void WebContents::SetImageAnimationPolicy(const std::string& new_policy) { auto* web_preferences = WebContentsPreferences::From(web_contents()); web_preferences->SetImageAnimationPolicy(new_policy); web_contents()->OnWebPreferencesChanged(); } v8::Local<v8::Promise> WebContents::GetProcessMemoryInfo(v8::Isolate* isolate) { gin_helper::Promise<gin_helper::Dictionary> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); auto* frame_host = web_contents()->GetMainFrame(); if (!frame_host) { promise.RejectWithErrorMessage("Failed to create memory dump"); return handle; } auto pid = frame_host->GetProcess()->GetProcess().Pid(); v8::Global<v8::Context> context(isolate, isolate->GetCurrentContext()); memory_instrumentation::MemoryInstrumentation::GetInstance() ->RequestGlobalDumpForPid( pid, std::vector<std::string>(), base::BindOnce(&ElectronBindings::DidReceiveMemoryDump, std::move(context), std::move(promise), pid)); return handle; } v8::Local<v8::Promise> WebContents::TakeHeapSnapshot( v8::Isolate* isolate, const base::FilePath& file_path) { gin_helper::Promise<void> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); base::ThreadRestrictions::ScopedAllowIO allow_io; base::File file(file_path, base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE); if (!file.IsValid()) { promise.RejectWithErrorMessage("takeHeapSnapshot failed"); return handle; } auto* frame_host = web_contents()->GetMainFrame(); if (!frame_host) { promise.RejectWithErrorMessage("takeHeapSnapshot failed"); return handle; } if (!frame_host->IsRenderFrameCreated()) { promise.RejectWithErrorMessage("takeHeapSnapshot failed"); return handle; } // This dance with `base::Owned` is to ensure that the interface stays alive // until the callback is called. Otherwise it would be closed at the end of // this function. auto electron_renderer = std::make_unique<mojo::Remote<mojom::ElectronRenderer>>(); frame_host->GetRemoteInterfaces()->GetInterface( electron_renderer->BindNewPipeAndPassReceiver()); auto* raw_ptr = electron_renderer.get(); (*raw_ptr)->TakeHeapSnapshot( mojo::WrapPlatformFile(base::ScopedPlatformFile(file.TakePlatformFile())), base::BindOnce( [](mojo::Remote<mojom::ElectronRenderer>* ep, gin_helper::Promise<void> promise, bool success) { if (success) { promise.Resolve(); } else { promise.RejectWithErrorMessage("takeHeapSnapshot failed"); } }, base::Owned(std::move(electron_renderer)), std::move(promise))); return handle; } void WebContents::GrantDevicePermission( const url::Origin& origin, const base::Value* device, content::PermissionType permissionType, content::RenderFrameHost* render_frame_host) { granted_devices_[render_frame_host->GetFrameTreeNodeId()][permissionType] [origin] .push_back( std::make_unique<base::Value>(device->Clone())); } std::vector<base::Value> WebContents::GetGrantedDevices( const url::Origin& origin, content::PermissionType permissionType, content::RenderFrameHost* render_frame_host) { const auto& devices_for_frame_host_it = granted_devices_.find(render_frame_host->GetFrameTreeNodeId()); if (devices_for_frame_host_it == granted_devices_.end()) return {}; const auto& current_devices_it = devices_for_frame_host_it->second.find(permissionType); if (current_devices_it == devices_for_frame_host_it->second.end()) return {}; const auto& origin_devices_it = current_devices_it->second.find(origin); if (origin_devices_it == current_devices_it->second.end()) return {}; std::vector<base::Value> results; for (const auto& object : origin_devices_it->second) results.push_back(object->Clone()); return results; } void WebContents::UpdatePreferredSize(content::WebContents* web_contents, const gfx::Size& pref_size) { Emit("preferred-size-changed", pref_size); } bool WebContents::CanOverscrollContent() { return false; } std::unique_ptr<content::EyeDropper> WebContents::OpenEyeDropper( content::RenderFrameHost* frame, content::EyeDropperListener* listener) { return ShowEyeDropper(frame, listener); } void WebContents::RunFileChooser( content::RenderFrameHost* render_frame_host, scoped_refptr<content::FileSelectListener> listener, const blink::mojom::FileChooserParams& params) { FileSelectHelper::RunFileChooser(render_frame_host, std::move(listener), params); } void WebContents::EnumerateDirectory( content::WebContents* web_contents, scoped_refptr<content::FileSelectListener> listener, const base::FilePath& path) { FileSelectHelper::EnumerateDirectory(web_contents, std::move(listener), path); } bool WebContents::IsFullscreenForTabOrPending( const content::WebContents* source) { return html_fullscreen_; } bool WebContents::TakeFocus(content::WebContents* source, bool reverse) { if (source && source->GetOutermostWebContents() == source) { // If this is the outermost web contents and the user has tabbed or // shift + tabbed through all the elements, reset the focus back to // the first or last element so that it doesn't stay in the body. source->FocusThroughTabTraversal(reverse); return true; } return false; } content::PictureInPictureResult WebContents::EnterPictureInPicture( content::WebContents* web_contents) { #if BUILDFLAG(ENABLE_PICTURE_IN_PICTURE) return PictureInPictureWindowManager::GetInstance() ->EnterVideoPictureInPicture(web_contents); #else return content::PictureInPictureResult::kNotSupported; #endif } void WebContents::ExitPictureInPicture() { #if BUILDFLAG(ENABLE_PICTURE_IN_PICTURE) PictureInPictureWindowManager::GetInstance()->ExitPictureInPicture(); #endif } void WebContents::DevToolsSaveToFile(const std::string& url, const std::string& content, bool save_as) { base::FilePath path; auto it = saved_files_.find(url); if (it != saved_files_.end() && !save_as) { path = it->second; } else { file_dialog::DialogSettings settings; settings.parent_window = owner_window(); settings.force_detached = offscreen_; settings.title = url; settings.default_path = base::FilePath::FromUTF8Unsafe(url); if (!file_dialog::ShowSaveDialogSync(settings, &path)) { base::Value url_value(url); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.canceledSaveURL", &url_value, nullptr, nullptr); return; } } saved_files_[url] = path; // Notify DevTools. base::Value url_value(url); base::Value file_system_path_value(path.AsUTF8Unsafe()); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.savedURL", &url_value, &file_system_path_value, nullptr); file_task_runner_->PostTask(FROM_HERE, base::BindOnce(&WriteToFile, path, content)); } void WebContents::DevToolsAppendToFile(const std::string& url, const std::string& content) { auto it = saved_files_.find(url); if (it == saved_files_.end()) return; // Notify DevTools. base::Value url_value(url); inspectable_web_contents_->CallClientFunction("DevToolsAPI.appendedToURL", &url_value, nullptr, nullptr); file_task_runner_->PostTask( FROM_HERE, base::BindOnce(&AppendToFile, it->second, content)); } void WebContents::DevToolsRequestFileSystems() { auto file_system_paths = GetAddedFileSystemPaths(GetDevToolsWebContents()); if (file_system_paths.empty()) { base::ListValue empty_file_system_value; inspectable_web_contents_->CallClientFunction( "DevToolsAPI.fileSystemsLoaded", &empty_file_system_value, nullptr, nullptr); return; } std::vector<FileSystem> file_systems; for (const auto& file_system_path : file_system_paths) { base::FilePath path = base::FilePath::FromUTF8Unsafe(file_system_path.first); std::string file_system_id = RegisterFileSystem(GetDevToolsWebContents(), path); FileSystem file_system = CreateFileSystemStruct(GetDevToolsWebContents(), file_system_id, file_system_path.first, file_system_path.second); file_systems.push_back(file_system); } base::ListValue file_system_value; for (const auto& file_system : file_systems) file_system_value.Append(CreateFileSystemValue(file_system)); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.fileSystemsLoaded", &file_system_value, nullptr, nullptr); } void WebContents::DevToolsAddFileSystem( const std::string& type, const base::FilePath& file_system_path) { base::FilePath path = file_system_path; if (path.empty()) { std::vector<base::FilePath> paths; file_dialog::DialogSettings settings; settings.parent_window = owner_window(); settings.force_detached = offscreen_; settings.properties = file_dialog::OPEN_DIALOG_OPEN_DIRECTORY; if (!file_dialog::ShowOpenDialogSync(settings, &paths)) return; path = paths[0]; } std::string file_system_id = RegisterFileSystem(GetDevToolsWebContents(), path); if (IsDevToolsFileSystemAdded(GetDevToolsWebContents(), path.AsUTF8Unsafe())) return; FileSystem file_system = CreateFileSystemStruct( GetDevToolsWebContents(), file_system_id, path.AsUTF8Unsafe(), type); std::unique_ptr<base::DictionaryValue> file_system_value( CreateFileSystemValue(file_system)); auto* pref_service = GetPrefService(GetDevToolsWebContents()); DictionaryPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths); update.Get()->SetKey(path.AsUTF8Unsafe(), base::Value(type)); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.fileSystemAdded", nullptr, file_system_value.get(), nullptr); } void WebContents::DevToolsRemoveFileSystem( const base::FilePath& file_system_path) { if (!inspectable_web_contents_) return; std::string path = file_system_path.AsUTF8Unsafe(); storage::IsolatedContext::GetInstance()->RevokeFileSystemByPath( file_system_path); auto* pref_service = GetPrefService(GetDevToolsWebContents()); DictionaryPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths); update.Get()->RemoveKey(path); base::Value file_system_path_value(path); inspectable_web_contents_->CallClientFunction("DevToolsAPI.fileSystemRemoved", &file_system_path_value, nullptr, nullptr); } void WebContents::DevToolsIndexPath( int request_id, const std::string& file_system_path, const std::string& excluded_folders_message) { if (!IsDevToolsFileSystemAdded(GetDevToolsWebContents(), file_system_path)) { OnDevToolsIndexingDone(request_id, file_system_path); return; } if (devtools_indexing_jobs_.count(request_id) != 0) return; std::vector<std::string> excluded_folders; std::unique_ptr<base::Value> parsed_excluded_folders = base::JSONReader::ReadDeprecated(excluded_folders_message); if (parsed_excluded_folders && parsed_excluded_folders->is_list()) { for (const base::Value& folder_path : parsed_excluded_folders->GetListDeprecated()) { if (folder_path.is_string()) excluded_folders.push_back(folder_path.GetString()); } } devtools_indexing_jobs_[request_id] = scoped_refptr<DevToolsFileSystemIndexer::FileSystemIndexingJob>( devtools_file_system_indexer_->IndexPath( file_system_path, excluded_folders, base::BindRepeating( &WebContents::OnDevToolsIndexingWorkCalculated, weak_factory_.GetWeakPtr(), request_id, file_system_path), base::BindRepeating(&WebContents::OnDevToolsIndexingWorked, weak_factory_.GetWeakPtr(), request_id, file_system_path), base::BindRepeating(&WebContents::OnDevToolsIndexingDone, weak_factory_.GetWeakPtr(), request_id, file_system_path))); } void WebContents::DevToolsStopIndexing(int request_id) { auto it = devtools_indexing_jobs_.find(request_id); if (it == devtools_indexing_jobs_.end()) return; it->second->Stop(); devtools_indexing_jobs_.erase(it); } void WebContents::DevToolsSearchInPath(int request_id, const std::string& file_system_path, const std::string& query) { if (!IsDevToolsFileSystemAdded(GetDevToolsWebContents(), file_system_path)) { OnDevToolsSearchCompleted(request_id, file_system_path, std::vector<std::string>()); return; } devtools_file_system_indexer_->SearchInPath( file_system_path, query, base::BindRepeating(&WebContents::OnDevToolsSearchCompleted, weak_factory_.GetWeakPtr(), request_id, file_system_path)); } void WebContents::DevToolsSetEyeDropperActive(bool active) { auto* web_contents = GetWebContents(); if (!web_contents) return; if (active) { eye_dropper_ = std::make_unique<DevToolsEyeDropper>( web_contents, base::BindRepeating(&WebContents::ColorPickedInEyeDropper, base::Unretained(this))); } else { eye_dropper_.reset(); } } void WebContents::ColorPickedInEyeDropper(int r, int g, int b, int a) { base::DictionaryValue color; color.SetInteger("r", r); color.SetInteger("g", g); color.SetInteger("b", b); color.SetInteger("a", a); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.eyeDropperPickedColor", &color, nullptr, nullptr); } #if defined(TOOLKIT_VIEWS) && !BUILDFLAG(IS_MAC) ui::ImageModel WebContents::GetDevToolsWindowIcon() { return owner_window() ? owner_window()->GetWindowAppIcon() : ui::ImageModel{}; } #endif #if BUILDFLAG(IS_LINUX) void WebContents::GetDevToolsWindowWMClass(std::string* name, std::string* class_name) { *class_name = Browser::Get()->GetName(); *name = base::ToLowerASCII(*class_name); } #endif void WebContents::OnDevToolsIndexingWorkCalculated( int request_id, const std::string& file_system_path, int total_work) { base::Value request_id_value(request_id); base::Value file_system_path_value(file_system_path); base::Value total_work_value(total_work); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.indexingTotalWorkCalculated", &request_id_value, &file_system_path_value, &total_work_value); } void WebContents::OnDevToolsIndexingWorked(int request_id, const std::string& file_system_path, int worked) { base::Value request_id_value(request_id); base::Value file_system_path_value(file_system_path); base::Value worked_value(worked); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.indexingWorked", &request_id_value, &file_system_path_value, &worked_value); } void WebContents::OnDevToolsIndexingDone(int request_id, const std::string& file_system_path) { devtools_indexing_jobs_.erase(request_id); base::Value request_id_value(request_id); base::Value file_system_path_value(file_system_path); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.indexingDone", &request_id_value, &file_system_path_value, nullptr); } void WebContents::OnDevToolsSearchCompleted( int request_id, const std::string& file_system_path, const std::vector<std::string>& file_paths) { base::ListValue file_paths_value; for (const auto& file_path : file_paths) { file_paths_value.Append(file_path); } base::Value request_id_value(request_id); base::Value file_system_path_value(file_system_path); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.searchCompleted", &request_id_value, &file_system_path_value, &file_paths_value); } void WebContents::SetHtmlApiFullscreen(bool enter_fullscreen) { // Window is already in fullscreen mode, save the state. if (enter_fullscreen && owner_window_->IsFullscreen()) { native_fullscreen_ = true; UpdateHtmlApiFullscreen(true); return; } // Exit html fullscreen state but not window's fullscreen mode. if (!enter_fullscreen && native_fullscreen_) { UpdateHtmlApiFullscreen(false); return; } // Set fullscreen on window if allowed. auto* web_preferences = WebContentsPreferences::From(GetWebContents()); bool html_fullscreenable = web_preferences ? !web_preferences->ShouldDisableHtmlFullscreenWindowResize() : true; if (html_fullscreenable) { owner_window_->SetFullScreen(enter_fullscreen); } UpdateHtmlApiFullscreen(enter_fullscreen); native_fullscreen_ = false; } void WebContents::UpdateHtmlApiFullscreen(bool fullscreen) { if (fullscreen == is_html_fullscreen()) return; html_fullscreen_ = fullscreen; // Notify renderer of the html fullscreen change. web_contents() ->GetRenderViewHost() ->GetWidget() ->SynchronizeVisualProperties(); // The embedder WebContents is separated from the frame tree of webview, so // we must manually sync their fullscreen states. if (embedder_) embedder_->SetHtmlApiFullscreen(fullscreen); if (fullscreen) { Emit("enter-html-full-screen"); owner_window_->NotifyWindowEnterHtmlFullScreen(); } else { Emit("leave-html-full-screen"); owner_window_->NotifyWindowLeaveHtmlFullScreen(); } // Make sure all child webviews quit html fullscreen. if (!fullscreen && !IsGuest()) { auto* manager = WebViewManager::GetWebViewManager(web_contents()); manager->ForEachGuest( web_contents(), base::BindRepeating([](content::WebContents* guest) { WebContents* api_web_contents = WebContents::From(guest); api_web_contents->SetHtmlApiFullscreen(false); return false; })); } } // static v8::Local<v8::ObjectTemplate> WebContents::FillObjectTemplate( v8::Isolate* isolate, v8::Local<v8::ObjectTemplate> templ) { gin::InvokerOptions options; options.holder_is_first_argument = true; options.holder_type = "WebContents"; templ->Set( gin::StringToSymbol(isolate, "isDestroyed"), gin::CreateFunctionTemplate( isolate, base::BindRepeating(&gin_helper::Destroyable::IsDestroyed), options)); // We use gin_helper::ObjectTemplateBuilder instead of // gin::ObjectTemplateBuilder here to handle the fact that WebContents is // destroyable. return gin_helper::ObjectTemplateBuilder(isolate, templ) .SetMethod("destroy", &WebContents::Destroy) .SetMethod("getBackgroundThrottling", &WebContents::GetBackgroundThrottling) .SetMethod("setBackgroundThrottling", &WebContents::SetBackgroundThrottling) .SetMethod("getProcessId", &WebContents::GetProcessID) .SetMethod("getOSProcessId", &WebContents::GetOSProcessID) .SetMethod("equal", &WebContents::Equal) .SetMethod("_loadURL", &WebContents::LoadURL) .SetMethod("reload", &WebContents::Reload) .SetMethod("reloadIgnoringCache", &WebContents::ReloadIgnoringCache) .SetMethod("downloadURL", &WebContents::DownloadURL) .SetMethod("getURL", &WebContents::GetURL) .SetMethod("getTitle", &WebContents::GetTitle) .SetMethod("isLoading", &WebContents::IsLoading) .SetMethod("isLoadingMainFrame", &WebContents::IsLoadingMainFrame) .SetMethod("isWaitingForResponse", &WebContents::IsWaitingForResponse) .SetMethod("stop", &WebContents::Stop) .SetMethod("canGoBack", &WebContents::CanGoBack) .SetMethod("goBack", &WebContents::GoBack) .SetMethod("canGoForward", &WebContents::CanGoForward) .SetMethod("goForward", &WebContents::GoForward) .SetMethod("canGoToOffset", &WebContents::CanGoToOffset) .SetMethod("goToOffset", &WebContents::GoToOffset) .SetMethod("canGoToIndex", &WebContents::CanGoToIndex) .SetMethod("goToIndex", &WebContents::GoToIndex) .SetMethod("getActiveIndex", &WebContents::GetActiveIndex) .SetMethod("clearHistory", &WebContents::ClearHistory) .SetMethod("length", &WebContents::GetHistoryLength) .SetMethod("isCrashed", &WebContents::IsCrashed) .SetMethod("forcefullyCrashRenderer", &WebContents::ForcefullyCrashRenderer) .SetMethod("setUserAgent", &WebContents::SetUserAgent) .SetMethod("getUserAgent", &WebContents::GetUserAgent) .SetMethod("savePage", &WebContents::SavePage) .SetMethod("openDevTools", &WebContents::OpenDevTools) .SetMethod("closeDevTools", &WebContents::CloseDevTools) .SetMethod("isDevToolsOpened", &WebContents::IsDevToolsOpened) .SetMethod("isDevToolsFocused", &WebContents::IsDevToolsFocused) .SetMethod("enableDeviceEmulation", &WebContents::EnableDeviceEmulation) .SetMethod("disableDeviceEmulation", &WebContents::DisableDeviceEmulation) .SetMethod("toggleDevTools", &WebContents::ToggleDevTools) .SetMethod("inspectElement", &WebContents::InspectElement) .SetMethod("setIgnoreMenuShortcuts", &WebContents::SetIgnoreMenuShortcuts) .SetMethod("setAudioMuted", &WebContents::SetAudioMuted) .SetMethod("isAudioMuted", &WebContents::IsAudioMuted) .SetMethod("isCurrentlyAudible", &WebContents::IsCurrentlyAudible) .SetMethod("undo", &WebContents::Undo) .SetMethod("redo", &WebContents::Redo) .SetMethod("cut", &WebContents::Cut) .SetMethod("copy", &WebContents::Copy) .SetMethod("paste", &WebContents::Paste) .SetMethod("pasteAndMatchStyle", &WebContents::PasteAndMatchStyle) .SetMethod("delete", &WebContents::Delete) .SetMethod("selectAll", &WebContents::SelectAll) .SetMethod("unselect", &WebContents::Unselect) .SetMethod("replace", &WebContents::Replace) .SetMethod("replaceMisspelling", &WebContents::ReplaceMisspelling) .SetMethod("findInPage", &WebContents::FindInPage) .SetMethod("stopFindInPage", &WebContents::StopFindInPage) .SetMethod("focus", &WebContents::Focus) .SetMethod("isFocused", &WebContents::IsFocused) .SetMethod("sendInputEvent", &WebContents::SendInputEvent) .SetMethod("beginFrameSubscription", &WebContents::BeginFrameSubscription) .SetMethod("endFrameSubscription", &WebContents::EndFrameSubscription) .SetMethod("startDrag", &WebContents::StartDrag) .SetMethod("attachToIframe", &WebContents::AttachToIframe) .SetMethod("detachFromOuterFrame", &WebContents::DetachFromOuterFrame) .SetMethod("isOffscreen", &WebContents::IsOffScreen) #if BUILDFLAG(ENABLE_OSR) .SetMethod("startPainting", &WebContents::StartPainting) .SetMethod("stopPainting", &WebContents::StopPainting) .SetMethod("isPainting", &WebContents::IsPainting) .SetMethod("setFrameRate", &WebContents::SetFrameRate) .SetMethod("getFrameRate", &WebContents::GetFrameRate) #endif .SetMethod("invalidate", &WebContents::Invalidate) .SetMethod("setZoomLevel", &WebContents::SetZoomLevel) .SetMethod("getZoomLevel", &WebContents::GetZoomLevel) .SetMethod("setZoomFactor", &WebContents::SetZoomFactor) .SetMethod("getZoomFactor", &WebContents::GetZoomFactor) .SetMethod("getType", &WebContents::GetType) .SetMethod("_getPreloadPaths", &WebContents::GetPreloadPaths) .SetMethod("getLastWebPreferences", &WebContents::GetLastWebPreferences) .SetMethod("getOwnerBrowserWindow", &WebContents::GetOwnerBrowserWindow) .SetMethod("inspectServiceWorker", &WebContents::InspectServiceWorker) .SetMethod("inspectSharedWorker", &WebContents::InspectSharedWorker) .SetMethod("inspectSharedWorkerById", &WebContents::InspectSharedWorkerById) .SetMethod("getAllSharedWorkers", &WebContents::GetAllSharedWorkers) #if BUILDFLAG(ENABLE_PRINTING) .SetMethod("_print", &WebContents::Print) .SetMethod("_printToPDF", &WebContents::PrintToPDF) #endif .SetMethod("_setNextChildWebPreferences", &WebContents::SetNextChildWebPreferences) .SetMethod("addWorkSpace", &WebContents::AddWorkSpace) .SetMethod("removeWorkSpace", &WebContents::RemoveWorkSpace) .SetMethod("showDefinitionForSelection", &WebContents::ShowDefinitionForSelection) .SetMethod("copyImageAt", &WebContents::CopyImageAt) .SetMethod("capturePage", &WebContents::CapturePage) .SetMethod("setEmbedder", &WebContents::SetEmbedder) .SetMethod("setDevToolsWebContents", &WebContents::SetDevToolsWebContents) .SetMethod("getNativeView", &WebContents::GetNativeView) .SetMethod("incrementCapturerCount", &WebContents::IncrementCapturerCount) .SetMethod("decrementCapturerCount", &WebContents::DecrementCapturerCount) .SetMethod("isBeingCaptured", &WebContents::IsBeingCaptured) .SetMethod("setWebRTCIPHandlingPolicy", &WebContents::SetWebRTCIPHandlingPolicy) .SetMethod("getMediaSourceId", &WebContents::GetMediaSourceID) .SetMethod("getWebRTCIPHandlingPolicy", &WebContents::GetWebRTCIPHandlingPolicy) .SetMethod("takeHeapSnapshot", &WebContents::TakeHeapSnapshot) .SetMethod("setImageAnimationPolicy", &WebContents::SetImageAnimationPolicy) .SetMethod("_getProcessMemoryInfo", &WebContents::GetProcessMemoryInfo) .SetProperty("id", &WebContents::ID) .SetProperty("session", &WebContents::Session) .SetProperty("hostWebContents", &WebContents::HostWebContents) .SetProperty("devToolsWebContents", &WebContents::DevToolsWebContents) .SetProperty("debugger", &WebContents::Debugger) .SetProperty("mainFrame", &WebContents::MainFrame) .Build(); } const char* WebContents::GetTypeName() { return "WebContents"; } ElectronBrowserContext* WebContents::GetBrowserContext() const { return static_cast<ElectronBrowserContext*>( web_contents()->GetBrowserContext()); } // static gin::Handle<WebContents> WebContents::New( v8::Isolate* isolate, const gin_helper::Dictionary& options) { gin::Handle<WebContents> handle = gin::CreateHandle(isolate, new WebContents(isolate, options)); v8::TryCatch try_catch(isolate); gin_helper::CallMethod(isolate, handle.get(), "_init"); if (try_catch.HasCaught()) { node::errors::TriggerUncaughtException(isolate, try_catch); } return handle; } // static gin::Handle<WebContents> WebContents::CreateAndTake( v8::Isolate* isolate, std::unique_ptr<content::WebContents> web_contents, Type type) { gin::Handle<WebContents> handle = gin::CreateHandle( isolate, new WebContents(isolate, std::move(web_contents), type)); v8::TryCatch try_catch(isolate); gin_helper::CallMethod(isolate, handle.get(), "_init"); if (try_catch.HasCaught()) { node::errors::TriggerUncaughtException(isolate, try_catch); } return handle; } // static WebContents* WebContents::From(content::WebContents* web_contents) { if (!web_contents) return nullptr; auto* data = static_cast<UserDataLink*>( web_contents->GetUserData(kElectronApiWebContentsKey)); return data ? data->web_contents.get() : nullptr; } // static gin::Handle<WebContents> WebContents::FromOrCreate( v8::Isolate* isolate, content::WebContents* web_contents) { WebContents* api_web_contents = From(web_contents); if (!api_web_contents) { api_web_contents = new WebContents(isolate, web_contents); v8::TryCatch try_catch(isolate); gin_helper::CallMethod(isolate, api_web_contents, "_init"); if (try_catch.HasCaught()) { node::errors::TriggerUncaughtException(isolate, try_catch); } } return gin::CreateHandle(isolate, api_web_contents); } // static gin::Handle<WebContents> WebContents::CreateFromWebPreferences( v8::Isolate* isolate, const gin_helper::Dictionary& web_preferences) { // Check if webPreferences has |webContents| option. gin::Handle<WebContents> web_contents; if (web_preferences.GetHidden("webContents", &web_contents) && !web_contents.IsEmpty()) { // Set webPreferences from options if using an existing webContents. // These preferences will be used when the webContent launches new // render processes. auto* existing_preferences = WebContentsPreferences::From(web_contents->web_contents()); gin_helper::Dictionary web_preferences_dict; if (gin::ConvertFromV8(isolate, web_preferences.GetHandle(), &web_preferences_dict)) { existing_preferences->SetFromDictionary(web_preferences_dict); absl::optional<SkColor> color = existing_preferences->GetBackgroundColor(); web_contents->web_contents()->SetPageBaseBackgroundColor(color); // Because web preferences don't recognize transparency, // only set rwhv background color if a color exists auto* rwhv = web_contents->web_contents()->GetRenderWidgetHostView(); if (rwhv && color.has_value()) SetBackgroundColor(rwhv, color.value()); } } else { // Create one if not. web_contents = WebContents::New(isolate, web_preferences); } return web_contents; } // static WebContents* WebContents::FromID(int32_t id) { return GetAllWebContents().Lookup(id); } // static gin::WrapperInfo WebContents::kWrapperInfo = {gin::kEmbedderNativeGin}; } // namespace api } // namespace electron namespace { using electron::api::GetAllWebContents; using electron::api::WebContents; gin::Handle<WebContents> WebContentsFromID(v8::Isolate* isolate, int32_t id) { WebContents* contents = WebContents::FromID(id); return contents ? gin::CreateHandle(isolate, contents) : gin::Handle<WebContents>(); } gin::Handle<WebContents> WebContentsFromDevToolsTargetID( v8::Isolate* isolate, std::string target_id) { auto agent_host = content::DevToolsAgentHost::GetForId(target_id); WebContents* contents = agent_host ? WebContents::From(agent_host->GetWebContents()) : nullptr; return contents ? gin::CreateHandle(isolate, contents) : gin::Handle<WebContents>(); } std::vector<gin::Handle<WebContents>> GetAllWebContentsAsV8( v8::Isolate* isolate) { std::vector<gin::Handle<WebContents>> list; for (auto iter = base::IDMap<WebContents*>::iterator(&GetAllWebContents()); !iter.IsAtEnd(); iter.Advance()) { list.push_back(gin::CreateHandle(isolate, iter.GetCurrentValue())); } return list; } void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused, v8::Local<v8::Context> context, void* priv) { v8::Isolate* isolate = context->GetIsolate(); gin_helper::Dictionary dict(isolate, exports); dict.Set("WebContents", WebContents::GetConstructor(context)); dict.SetMethod("fromId", &WebContentsFromID); dict.SetMethod("fromDevToolsTargetId", &WebContentsFromDevToolsTargetID); dict.SetMethod("getAllWebContents", &GetAllWebContentsAsV8); } } // namespace NODE_LINKED_MODULE_CONTEXT_AWARE(electron_browser_web_contents, Initialize)
closed
electron/electron
https://github.com/electron/electron
33,721
[Bug]: After entering and exiting Fullscreen, pressing [Esc] no longer works
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 18.0.3 ### What operating system are you using? Windows ### Operating System Version Windows 10 ### What arch are you using? x64 ### Last Known Working Electron version 18.0.0 ### Expected Behavior After entering and exiting fullscreen from an iframe and then focusing the parent page, <kbd>Escape</kbd> key events should be delivered to the parent page. ### Actual Behavior <kbd>Escape</kbd> key events seem not to be delivered to the page after exiting fullscreen. https://user-images.githubusercontent.com/172800/162848678-c067d18a-e323-49ea-a6b3-f1526149cad1.mp4 ### Testcase Gist URL https://gist.github.com/bc382eeeb368b70fbed1e177bcaacfde ### Additional Information This only reproduces on Windows, not on macOS. Also, this only reproduces when _clicking_ the "exit fullscreen" button in the YouTube embed. Pressing <kbd>Esc</kbd> to exit fullscreen allows the parent page to receive subsequent key events. 18.0.0 - not reproducible 18.0.1 - reproducible 18.0.2 - reproducible 18.0.3 - reproducible This seems likely to be related to https://github.com/electron/electron/pull/32369. cc @codebytere
https://github.com/electron/electron/issues/33721
https://github.com/electron/electron/pull/33757
7658edfa1abb0ce9713e4848d1c1af15f8cac479
233a39dbc9e07f5620798323309a2d065a27c21b
2022-04-11T23:32:00Z
c++
2022-04-14T10:35:36Z
shell/browser/api/electron_api_web_contents.cc
// Copyright (c) 2014 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/api/electron_api_web_contents.h" #include <limits> #include <memory> #include <set> #include <string> #include <unordered_set> #include <utility> #include <vector> #include "base/containers/id_map.h" #include "base/files/file_util.h" #include "base/json/json_reader.h" #include "base/no_destructor.h" #include "base/strings/utf_string_conversions.h" #include "base/task/current_thread.h" #include "base/task/post_task.h" #include "base/task/thread_pool.h" #include "base/threading/scoped_blocking_call.h" #include "base/threading/sequenced_task_runner_handle.h" #include "base/threading/thread_restrictions.h" #include "base/threading/thread_task_runner_handle.h" #include "base/values.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/ui/exclusive_access/exclusive_access_manager.h" #include "chrome/browser/ui/views/eye_dropper/eye_dropper.h" #include "chrome/common/pref_names.h" #include "components/prefs/pref_service.h" #include "components/prefs/scoped_user_pref_update.h" #include "components/security_state/content/content_utils.h" #include "components/security_state/core/security_state.h" #include "content/browser/renderer_host/frame_tree_node.h" // nogncheck #include "content/browser/renderer_host/render_frame_host_manager.h" // nogncheck #include "content/browser/renderer_host/render_widget_host_impl.h" // nogncheck #include "content/browser/renderer_host/render_widget_host_view_base.h" // nogncheck #include "content/public/browser/child_process_security_policy.h" #include "content/public/browser/context_menu_params.h" #include "content/public/browser/desktop_media_id.h" #include "content/public/browser/desktop_streams_registry.h" #include "content/public/browser/download_request_utils.h" #include "content/public/browser/favicon_status.h" #include "content/public/browser/file_select_listener.h" #include "content/public/browser/native_web_keyboard_event.h" #include "content/public/browser/navigation_details.h" #include "content/public/browser/navigation_entry.h" #include "content/public/browser/navigation_handle.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/render_widget_host.h" #include "content/public/browser/render_widget_host_view.h" #include "content/public/browser/service_worker_context.h" #include "content/public/browser/site_instance.h" #include "content/public/browser/storage_partition.h" #include "content/public/browser/web_contents.h" #include "content/public/common/referrer_type_converters.h" #include "content/public/common/webplugininfo.h" #include "electron/buildflags/buildflags.h" #include "electron/shell/common/api/api.mojom.h" #include "gin/arguments.h" #include "gin/data_object_builder.h" #include "gin/handle.h" #include "gin/object_template_builder.h" #include "gin/wrappable.h" #include "mojo/public/cpp/bindings/associated_remote.h" #include "mojo/public/cpp/bindings/pending_receiver.h" #include "mojo/public/cpp/bindings/remote.h" #include "mojo/public/cpp/system/platform_handle.h" #include "ppapi/buildflags/buildflags.h" #include "printing/buildflags/buildflags.h" #include "printing/print_job_constants.h" #include "services/resource_coordinator/public/cpp/memory_instrumentation/memory_instrumentation.h" #include "services/service_manager/public/cpp/interface_provider.h" #include "shell/browser/api/electron_api_browser_window.h" #include "shell/browser/api/electron_api_debugger.h" #include "shell/browser/api/electron_api_session.h" #include "shell/browser/api/electron_api_web_frame_main.h" #include "shell/browser/api/message_port.h" #include "shell/browser/browser.h" #include "shell/browser/child_web_contents_tracker.h" #include "shell/browser/electron_autofill_driver_factory.h" #include "shell/browser/electron_browser_client.h" #include "shell/browser/electron_browser_context.h" #include "shell/browser/electron_browser_main_parts.h" #include "shell/browser/electron_javascript_dialog_manager.h" #include "shell/browser/electron_navigation_throttle.h" #include "shell/browser/file_select_helper.h" #include "shell/browser/native_window.h" #include "shell/browser/session_preferences.h" #include "shell/browser/ui/drag_util.h" #include "shell/browser/ui/file_dialog.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/ui/inspectable_web_contents_view.h" #include "shell/browser/web_contents_permission_helper.h" #include "shell/browser/web_contents_preferences.h" #include "shell/browser/web_contents_zoom_controller.h" #include "shell/browser/web_view_guest_delegate.h" #include "shell/browser/web_view_manager.h" #include "shell/common/api/electron_api_native_image.h" #include "shell/common/api/electron_bindings.h" #include "shell/common/color_util.h" #include "shell/common/electron_constants.h" #include "shell/common/gin_converters/base_converter.h" #include "shell/common/gin_converters/blink_converter.h" #include "shell/common/gin_converters/callback_converter.h" #include "shell/common/gin_converters/content_converter.h" #include "shell/common/gin_converters/file_path_converter.h" #include "shell/common/gin_converters/frame_converter.h" #include "shell/common/gin_converters/gfx_converter.h" #include "shell/common/gin_converters/gurl_converter.h" #include "shell/common/gin_converters/image_converter.h" #include "shell/common/gin_converters/net_converter.h" #include "shell/common/gin_converters/value_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/gin_helper/object_template_builder.h" #include "shell/common/language_util.h" #include "shell/common/mouse_util.h" #include "shell/common/node_includes.h" #include "shell/common/options_switches.h" #include "shell/common/process_util.h" #include "shell/common/v8_value_serializer.h" #include "storage/browser/file_system/isolated_context.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h" #include "third_party/blink/public/common/input/web_input_event.h" #include "third_party/blink/public/common/messaging/transferable_message_mojom_traits.h" #include "third_party/blink/public/common/page/page_zoom.h" #include "third_party/blink/public/mojom/frame/find_in_page.mojom.h" #include "third_party/blink/public/mojom/frame/fullscreen.mojom.h" #include "third_party/blink/public/mojom/messaging/transferable_message.mojom.h" #include "third_party/blink/public/mojom/renderer_preferences.mojom.h" #include "ui/base/cursor/cursor.h" #include "ui/base/cursor/mojom/cursor_type.mojom-shared.h" #include "ui/display/screen.h" #include "ui/events/base_event_utils.h" #if BUILDFLAG(ENABLE_OSR) #include "shell/browser/osr/osr_render_widget_host_view.h" #include "shell/browser/osr/osr_web_contents_view.h" #endif #if !BUILDFLAG(IS_MAC) #include "ui/aura/window.h" #else #include "ui/base/cocoa/defaults_utils.h" #endif #if BUILDFLAG(IS_LINUX) #include "ui/views/linux_ui/linux_ui.h" #endif #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_WIN) #include "ui/gfx/font_render_params.h" #endif #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #include "extensions/browser/script_executor.h" #include "extensions/browser/view_type_utils.h" #include "extensions/common/mojom/view_type.mojom.h" #include "shell/browser/extensions/electron_extension_web_contents_observer.h" #endif #if BUILDFLAG(ENABLE_PRINTING) #include "components/printing/browser/print_manager_utils.h" #include "printing/backend/print_backend.h" // nogncheck #include "printing/mojom/print.mojom.h" // nogncheck #include "shell/browser/printing/print_preview_message_handler.h" #include "shell/browser/printing/print_view_manager_electron.h" #if BUILDFLAG(IS_WIN) #include "printing/backend/win_helper.h" #endif #endif #if BUILDFLAG(ENABLE_PICTURE_IN_PICTURE) #include "chrome/browser/picture_in_picture/picture_in_picture_window_manager.h" #endif #if BUILDFLAG(ENABLE_PDF_VIEWER) #include "components/pdf/browser/pdf_web_contents_helper.h" // nogncheck #include "shell/browser/electron_pdf_web_contents_helper_client.h" #endif #if BUILDFLAG(ENABLE_PLUGINS) #include "content/public/browser/plugin_service.h" #endif #ifndef MAS_BUILD #include "chrome/browser/hang_monitor/hang_crash_dump.h" // nogncheck #endif namespace gin { #if BUILDFLAG(ENABLE_PRINTING) template <> struct Converter<printing::mojom::MarginType> { static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, printing::mojom::MarginType* out) { std::string type; if (ConvertFromV8(isolate, val, &type)) { if (type == "default") { *out = printing::mojom::MarginType::kDefaultMargins; return true; } if (type == "none") { *out = printing::mojom::MarginType::kNoMargins; return true; } if (type == "printableArea") { *out = printing::mojom::MarginType::kPrintableAreaMargins; return true; } if (type == "custom") { *out = printing::mojom::MarginType::kCustomMargins; return true; } } return false; } }; template <> struct Converter<printing::mojom::DuplexMode> { static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, printing::mojom::DuplexMode* out) { std::string mode; if (ConvertFromV8(isolate, val, &mode)) { if (mode == "simplex") { *out = printing::mojom::DuplexMode::kSimplex; return true; } if (mode == "longEdge") { *out = printing::mojom::DuplexMode::kLongEdge; return true; } if (mode == "shortEdge") { *out = printing::mojom::DuplexMode::kShortEdge; return true; } } return false; } }; #endif template <> struct Converter<WindowOpenDisposition> { static v8::Local<v8::Value> ToV8(v8::Isolate* isolate, WindowOpenDisposition val) { std::string disposition = "other"; switch (val) { case WindowOpenDisposition::CURRENT_TAB: disposition = "default"; break; case WindowOpenDisposition::NEW_FOREGROUND_TAB: disposition = "foreground-tab"; break; case WindowOpenDisposition::NEW_BACKGROUND_TAB: disposition = "background-tab"; break; case WindowOpenDisposition::NEW_POPUP: case WindowOpenDisposition::NEW_WINDOW: disposition = "new-window"; break; case WindowOpenDisposition::SAVE_TO_DISK: disposition = "save-to-disk"; break; default: break; } return gin::ConvertToV8(isolate, disposition); } }; template <> struct Converter<content::SavePageType> { static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, content::SavePageType* out) { std::string save_type; if (!ConvertFromV8(isolate, val, &save_type)) return false; save_type = base::ToLowerASCII(save_type); if (save_type == "htmlonly") { *out = content::SAVE_PAGE_TYPE_AS_ONLY_HTML; } else if (save_type == "htmlcomplete") { *out = content::SAVE_PAGE_TYPE_AS_COMPLETE_HTML; } else if (save_type == "mhtml") { *out = content::SAVE_PAGE_TYPE_AS_MHTML; } else { return false; } return true; } }; template <> struct Converter<electron::api::WebContents::Type> { static v8::Local<v8::Value> ToV8(v8::Isolate* isolate, electron::api::WebContents::Type val) { using Type = electron::api::WebContents::Type; std::string type; switch (val) { case Type::kBackgroundPage: type = "backgroundPage"; break; case Type::kBrowserWindow: type = "window"; break; case Type::kBrowserView: type = "browserView"; break; case Type::kRemote: type = "remote"; break; case Type::kWebView: type = "webview"; break; case Type::kOffScreen: type = "offscreen"; break; default: break; } return gin::ConvertToV8(isolate, type); } static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, electron::api::WebContents::Type* out) { using Type = electron::api::WebContents::Type; std::string type; if (!ConvertFromV8(isolate, val, &type)) return false; if (type == "backgroundPage") { *out = Type::kBackgroundPage; } else if (type == "browserView") { *out = Type::kBrowserView; } else if (type == "webview") { *out = Type::kWebView; #if BUILDFLAG(ENABLE_OSR) } else if (type == "offscreen") { *out = Type::kOffScreen; #endif } else { return false; } return true; } }; template <> struct Converter<scoped_refptr<content::DevToolsAgentHost>> { static v8::Local<v8::Value> ToV8( v8::Isolate* isolate, const scoped_refptr<content::DevToolsAgentHost>& val) { gin_helper::Dictionary dict(isolate, v8::Object::New(isolate)); dict.Set("id", val->GetId()); dict.Set("url", val->GetURL().spec()); return dict.GetHandle(); } }; } // namespace gin namespace electron { namespace api { namespace { base::IDMap<WebContents*>& GetAllWebContents() { static base::NoDestructor<base::IDMap<WebContents*>> s_all_web_contents; return *s_all_web_contents; } // Called when CapturePage is done. void OnCapturePageDone(gin_helper::Promise<gfx::Image> promise, const SkBitmap& bitmap) { // Hack to enable transparency in captured image promise.Resolve(gfx::Image::CreateFrom1xBitmap(bitmap)); } absl::optional<base::TimeDelta> GetCursorBlinkInterval() { #if BUILDFLAG(IS_MAC) absl::optional<base::TimeDelta> system_value( ui::TextInsertionCaretBlinkPeriodFromDefaults()); if (system_value) return *system_value; #elif BUILDFLAG(IS_LINUX) if (auto* linux_ui = views::LinuxUI::instance()) return linux_ui->GetCursorBlinkInterval(); #elif BUILDFLAG(IS_WIN) const auto system_msec = ::GetCaretBlinkTime(); if (system_msec != 0) { return (system_msec == INFINITE) ? base::TimeDelta() : base::Milliseconds(system_msec); } #endif return absl::nullopt; } #if BUILDFLAG(ENABLE_PRINTING) // This will return false if no printer with the provided device_name can be // found on the network. We need to check this because Chromium does not do // sanity checking of device_name validity and so will crash on invalid names. bool IsDeviceNameValid(const std::u16string& device_name) { #if BUILDFLAG(IS_MAC) base::ScopedCFTypeRef<CFStringRef> new_printer_id( base::SysUTF16ToCFStringRef(device_name)); PMPrinter new_printer = PMPrinterCreateFromPrinterID(new_printer_id.get()); bool printer_exists = new_printer != nullptr; PMRelease(new_printer); return printer_exists; #elif BUILDFLAG(IS_WIN) printing::ScopedPrinterHandle printer; return printer.OpenPrinterWithName(base::as_wcstr(device_name)); #else return true; #endif } std::pair<std::string, std::u16string> GetDefaultPrinterAsync() { #if BUILDFLAG(IS_WIN) // Blocking is needed here because Windows printer drivers are oftentimes // not thread-safe and have to be accessed on the UI thread. base::ThreadRestrictions::ScopedAllowIO allow_io; #endif scoped_refptr<printing::PrintBackend> print_backend = printing::PrintBackend::CreateInstance( g_browser_process->GetApplicationLocale()); std::string printer_name; printing::mojom::ResultCode code = print_backend->GetDefaultPrinterName(printer_name); // We don't want to return if this fails since some devices won't have a // default printer. if (code != printing::mojom::ResultCode::kSuccess) LOG(ERROR) << "Failed to get default printer name"; // Check for existing printers and pick the first one should it exist. if (printer_name.empty()) { printing::PrinterList printers; if (print_backend->EnumeratePrinters(&printers) != printing::mojom::ResultCode::kSuccess) return std::make_pair("Failed to enumerate printers", std::u16string()); if (!printers.empty()) printer_name = printers.front().printer_name; } return std::make_pair(std::string(), base::UTF8ToUTF16(printer_name)); } // Copied from // chrome/browser/ui/webui/print_preview/local_printer_handler_default.cc:L36-L54 scoped_refptr<base::TaskRunner> CreatePrinterHandlerTaskRunner() { // USER_VISIBLE because the result is displayed in the print preview dialog. #if !BUILDFLAG(IS_WIN) static constexpr base::TaskTraits kTraits = { base::MayBlock(), base::TaskPriority::USER_VISIBLE}; #endif #if defined(USE_CUPS) // CUPS is thread safe. return base::ThreadPool::CreateTaskRunner(kTraits); #elif BUILDFLAG(IS_WIN) // Windows drivers are likely not thread-safe and need to be accessed on the // UI thread. return content::GetUIThreadTaskRunner( {base::MayBlock(), base::TaskPriority::USER_VISIBLE}); #else // Be conservative on unsupported platforms. return base::ThreadPool::CreateSingleThreadTaskRunner(kTraits); #endif } #endif struct UserDataLink : public base::SupportsUserData::Data { explicit UserDataLink(base::WeakPtr<WebContents> contents) : web_contents(contents) {} base::WeakPtr<WebContents> web_contents; }; const void* kElectronApiWebContentsKey = &kElectronApiWebContentsKey; const char kRootName[] = "<root>"; struct FileSystem { FileSystem() = default; FileSystem(const std::string& type, const std::string& file_system_name, const std::string& root_url, const std::string& file_system_path) : type(type), file_system_name(file_system_name), root_url(root_url), file_system_path(file_system_path) {} std::string type; std::string file_system_name; std::string root_url; std::string file_system_path; }; std::string RegisterFileSystem(content::WebContents* web_contents, const base::FilePath& path) { auto* isolated_context = storage::IsolatedContext::GetInstance(); std::string root_name(kRootName); storage::IsolatedContext::ScopedFSHandle file_system = isolated_context->RegisterFileSystemForPath( storage::kFileSystemTypeLocal, std::string(), path, &root_name); content::ChildProcessSecurityPolicy* policy = content::ChildProcessSecurityPolicy::GetInstance(); content::RenderViewHost* render_view_host = web_contents->GetRenderViewHost(); int renderer_id = render_view_host->GetProcess()->GetID(); policy->GrantReadFileSystem(renderer_id, file_system.id()); policy->GrantWriteFileSystem(renderer_id, file_system.id()); policy->GrantCreateFileForFileSystem(renderer_id, file_system.id()); policy->GrantDeleteFromFileSystem(renderer_id, file_system.id()); if (!policy->CanReadFile(renderer_id, path)) policy->GrantReadFile(renderer_id, path); return file_system.id(); } FileSystem CreateFileSystemStruct(content::WebContents* web_contents, const std::string& file_system_id, const std::string& file_system_path, const std::string& type) { const GURL origin = web_contents->GetURL().DeprecatedGetOriginAsURL(); std::string file_system_name = storage::GetIsolatedFileSystemName(origin, file_system_id); std::string root_url = storage::GetIsolatedFileSystemRootURIString( origin, file_system_id, kRootName); return FileSystem(type, file_system_name, root_url, file_system_path); } std::unique_ptr<base::DictionaryValue> CreateFileSystemValue( const FileSystem& file_system) { auto file_system_value = std::make_unique<base::DictionaryValue>(); file_system_value->SetString("type", file_system.type); file_system_value->SetString("fileSystemName", file_system.file_system_name); file_system_value->SetString("rootURL", file_system.root_url); file_system_value->SetString("fileSystemPath", file_system.file_system_path); return file_system_value; } void WriteToFile(const base::FilePath& path, const std::string& content) { base::ScopedBlockingCall scoped_blocking_call(FROM_HERE, base::BlockingType::WILL_BLOCK); DCHECK(!path.empty()); base::WriteFile(path, content.data(), content.size()); } void AppendToFile(const base::FilePath& path, const std::string& content) { base::ScopedBlockingCall scoped_blocking_call(FROM_HERE, base::BlockingType::WILL_BLOCK); DCHECK(!path.empty()); base::AppendToFile(path, content); } PrefService* GetPrefService(content::WebContents* web_contents) { auto* context = web_contents->GetBrowserContext(); return static_cast<electron::ElectronBrowserContext*>(context)->prefs(); } std::map<std::string, std::string> GetAddedFileSystemPaths( content::WebContents* web_contents) { auto* pref_service = GetPrefService(web_contents); const base::Value* file_system_paths_value = pref_service->GetDictionary(prefs::kDevToolsFileSystemPaths); std::map<std::string, std::string> result; if (file_system_paths_value) { const base::DictionaryValue* file_system_paths_dict; file_system_paths_value->GetAsDictionary(&file_system_paths_dict); for (auto it : file_system_paths_dict->DictItems()) { std::string type = it.second.is_string() ? it.second.GetString() : std::string(); result[it.first] = type; } } return result; } bool IsDevToolsFileSystemAdded(content::WebContents* web_contents, const std::string& file_system_path) { auto file_system_paths = GetAddedFileSystemPaths(web_contents); return file_system_paths.find(file_system_path) != file_system_paths.end(); } void SetBackgroundColor(content::RenderWidgetHostView* rwhv, SkColor color) { rwhv->SetBackgroundColor(color); static_cast<content::RenderWidgetHostViewBase*>(rwhv) ->SetContentBackgroundColor(color); } } // namespace #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) WebContents::Type GetTypeFromViewType(extensions::mojom::ViewType view_type) { switch (view_type) { case extensions::mojom::ViewType::kExtensionBackgroundPage: return WebContents::Type::kBackgroundPage; case extensions::mojom::ViewType::kAppWindow: case extensions::mojom::ViewType::kComponent: case extensions::mojom::ViewType::kExtensionDialog: case extensions::mojom::ViewType::kExtensionPopup: case extensions::mojom::ViewType::kBackgroundContents: case extensions::mojom::ViewType::kExtensionGuest: case extensions::mojom::ViewType::kTabContents: case extensions::mojom::ViewType::kInvalid: return WebContents::Type::kRemote; } } #endif WebContents::WebContents(v8::Isolate* isolate, content::WebContents* web_contents) : content::WebContentsObserver(web_contents), type_(Type::kRemote), id_(GetAllWebContents().Add(this)), devtools_file_system_indexer_( base::MakeRefCounted<DevToolsFileSystemIndexer>()), exclusive_access_manager_(std::make_unique<ExclusiveAccessManager>(this)), file_task_runner_( base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()})) #if BUILDFLAG(ENABLE_PRINTING) , print_task_runner_(CreatePrinterHandlerTaskRunner()) #endif { #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) // WebContents created by extension host will have valid ViewType set. extensions::mojom::ViewType view_type = extensions::GetViewType(web_contents); if (view_type != extensions::mojom::ViewType::kInvalid) { InitWithExtensionView(isolate, web_contents, view_type); } extensions::ElectronExtensionWebContentsObserver::CreateForWebContents( web_contents); script_executor_ = std::make_unique<extensions::ScriptExecutor>(web_contents); #endif auto session = Session::CreateFrom(isolate, GetBrowserContext()); session_.Reset(isolate, session.ToV8()); web_contents->SetUserAgentOverride(blink::UserAgentOverride::UserAgentOnly( GetBrowserContext()->GetUserAgent()), false); web_contents->SetUserData(kElectronApiWebContentsKey, std::make_unique<UserDataLink>(GetWeakPtr())); InitZoomController(web_contents, gin::Dictionary::CreateEmpty(isolate)); } WebContents::WebContents(v8::Isolate* isolate, std::unique_ptr<content::WebContents> web_contents, Type type) : content::WebContentsObserver(web_contents.get()), type_(type), id_(GetAllWebContents().Add(this)), devtools_file_system_indexer_( base::MakeRefCounted<DevToolsFileSystemIndexer>()), exclusive_access_manager_(std::make_unique<ExclusiveAccessManager>(this)), file_task_runner_( base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()})) #if BUILDFLAG(ENABLE_PRINTING) , print_task_runner_(CreatePrinterHandlerTaskRunner()) #endif { DCHECK(type != Type::kRemote) << "Can't take ownership of a remote WebContents"; auto session = Session::CreateFrom(isolate, GetBrowserContext()); session_.Reset(isolate, session.ToV8()); InitWithSessionAndOptions(isolate, std::move(web_contents), session, gin::Dictionary::CreateEmpty(isolate)); } WebContents::WebContents(v8::Isolate* isolate, const gin_helper::Dictionary& options) : id_(GetAllWebContents().Add(this)), devtools_file_system_indexer_( base::MakeRefCounted<DevToolsFileSystemIndexer>()), exclusive_access_manager_(std::make_unique<ExclusiveAccessManager>(this)), file_task_runner_( base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()})) #if BUILDFLAG(ENABLE_PRINTING) , print_task_runner_(CreatePrinterHandlerTaskRunner()) #endif { // Read options. options.Get("backgroundThrottling", &background_throttling_); // Get type options.Get("type", &type_); #if BUILDFLAG(ENABLE_OSR) bool b = false; if (options.Get(options::kOffscreen, &b) && b) type_ = Type::kOffScreen; #endif // Init embedder earlier options.Get("embedder", &embedder_); // Whether to enable DevTools. options.Get("devTools", &enable_devtools_); // BrowserViews are not attached to a window initially so they should start // off as hidden. This is also important for compositor recycling. See: // https://github.com/electron/electron/pull/21372 bool initially_shown = type_ != Type::kBrowserView; options.Get(options::kShow, &initially_shown); // Obtain the session. std::string partition; gin::Handle<api::Session> session; if (options.Get("session", &session) && !session.IsEmpty()) { } else if (options.Get("partition", &partition)) { session = Session::FromPartition(isolate, partition); } else { // Use the default session if not specified. session = Session::FromPartition(isolate, ""); } session_.Reset(isolate, session.ToV8()); std::unique_ptr<content::WebContents> web_contents; if (IsGuest()) { scoped_refptr<content::SiteInstance> site_instance = content::SiteInstance::CreateForURL(session->browser_context(), GURL("chrome-guest://fake-host")); content::WebContents::CreateParams params(session->browser_context(), site_instance); guest_delegate_ = std::make_unique<WebViewGuestDelegate>(embedder_->web_contents(), this); params.guest_delegate = guest_delegate_.get(); #if BUILDFLAG(ENABLE_OSR) if (embedder_ && embedder_->IsOffScreen()) { auto* view = new OffScreenWebContentsView( false, base::BindRepeating(&WebContents::OnPaint, base::Unretained(this))); params.view = view; params.delegate_view = view; web_contents = content::WebContents::Create(params); view->SetWebContents(web_contents.get()); } else { #endif web_contents = content::WebContents::Create(params); #if BUILDFLAG(ENABLE_OSR) } } else if (IsOffScreen()) { // webPreferences does not have a transparent option, so if the window needs // to be transparent, that will be set at electron_api_browser_window.cc#L57 // and we then need to pull it back out and check it here. std::string background_color; options.GetHidden(options::kBackgroundColor, &background_color); bool transparent = ParseCSSColor(background_color) == SK_ColorTRANSPARENT; content::WebContents::CreateParams params(session->browser_context()); auto* view = new OffScreenWebContentsView( transparent, base::BindRepeating(&WebContents::OnPaint, base::Unretained(this))); params.view = view; params.delegate_view = view; web_contents = content::WebContents::Create(params); view->SetWebContents(web_contents.get()); #endif } else { content::WebContents::CreateParams params(session->browser_context()); params.initially_hidden = !initially_shown; web_contents = content::WebContents::Create(params); } InitWithSessionAndOptions(isolate, std::move(web_contents), session, options); } void WebContents::InitZoomController(content::WebContents* web_contents, const gin_helper::Dictionary& options) { WebContentsZoomController::CreateForWebContents(web_contents); zoom_controller_ = WebContentsZoomController::FromWebContents(web_contents); double zoom_factor; if (options.Get(options::kZoomFactor, &zoom_factor)) zoom_controller_->SetDefaultZoomFactor(zoom_factor); } void WebContents::InitWithSessionAndOptions( v8::Isolate* isolate, std::unique_ptr<content::WebContents> owned_web_contents, gin::Handle<api::Session> session, const gin_helper::Dictionary& options) { Observe(owned_web_contents.get()); InitWithWebContents(std::move(owned_web_contents), session->browser_context(), IsGuest()); inspectable_web_contents_->GetView()->SetDelegate(this); auto* prefs = web_contents()->GetMutableRendererPrefs(); // Collect preferred languages from OS and browser process. accept_languages // effects HTTP header, navigator.languages, and CJK fallback font selection. // // Note that an application locale set to the browser process might be // different with the one set to the preference list. // (e.g. overridden with --lang) std::string accept_languages = g_browser_process->GetApplicationLocale() + ","; for (auto const& language : electron::GetPreferredLanguages()) { if (language == g_browser_process->GetApplicationLocale()) continue; accept_languages += language + ","; } accept_languages.pop_back(); prefs->accept_languages = accept_languages; #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_WIN) // Update font settings. static const gfx::FontRenderParams params( gfx::GetFontRenderParams(gfx::FontRenderParamsQuery(), nullptr)); prefs->should_antialias_text = params.antialiasing; prefs->use_subpixel_positioning = params.subpixel_positioning; prefs->hinting = params.hinting; prefs->use_autohinter = params.autohinter; prefs->use_bitmaps = params.use_bitmaps; prefs->subpixel_rendering = params.subpixel_rendering; #endif // Honor the system's cursor blink rate settings if (auto interval = GetCursorBlinkInterval()) prefs->caret_blink_interval = *interval; // Save the preferences in C++. // If there's already a WebContentsPreferences object, we created it as part // of the webContents.setWindowOpenHandler path, so don't overwrite it. if (!WebContentsPreferences::From(web_contents())) { new WebContentsPreferences(web_contents(), options); } // Trigger re-calculation of webkit prefs. web_contents()->NotifyPreferencesChanged(); WebContentsPermissionHelper::CreateForWebContents(web_contents()); InitZoomController(web_contents(), options); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) extensions::ElectronExtensionWebContentsObserver::CreateForWebContents( web_contents()); script_executor_ = std::make_unique<extensions::ScriptExecutor>(web_contents()); #endif AutofillDriverFactory::CreateForWebContents(web_contents()); web_contents()->SetUserAgentOverride(blink::UserAgentOverride::UserAgentOnly( GetBrowserContext()->GetUserAgent()), false); if (IsGuest()) { NativeWindow* owner_window = nullptr; if (embedder_) { // New WebContents's owner_window is the embedder's owner_window. auto* relay = NativeWindowRelay::FromWebContents(embedder_->web_contents()); if (relay) owner_window = relay->GetNativeWindow(); } if (owner_window) SetOwnerWindow(owner_window); } web_contents()->SetUserData(kElectronApiWebContentsKey, std::make_unique<UserDataLink>(GetWeakPtr())); } #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) void WebContents::InitWithExtensionView(v8::Isolate* isolate, content::WebContents* web_contents, extensions::mojom::ViewType view_type) { // Must reassign type prior to calling `Init`. type_ = GetTypeFromViewType(view_type); if (type_ == Type::kRemote) return; if (type_ == Type::kBackgroundPage) // non-background-page WebContents are retained by other classes. We need // to pin here to prevent background-page WebContents from being GC'd. // The background page api::WebContents will live until the underlying // content::WebContents is destroyed. Pin(isolate); // Allow toggling DevTools for background pages Observe(web_contents); InitWithWebContents(std::unique_ptr<content::WebContents>(web_contents), GetBrowserContext(), IsGuest()); inspectable_web_contents_->GetView()->SetDelegate(this); } #endif void WebContents::InitWithWebContents( std::unique_ptr<content::WebContents> web_contents, ElectronBrowserContext* browser_context, bool is_guest) { browser_context_ = browser_context; web_contents->SetDelegate(this); #if BUILDFLAG(ENABLE_PRINTING) PrintPreviewMessageHandler::CreateForWebContents(web_contents.get()); PrintViewManagerElectron::CreateForWebContents(web_contents.get()); printing::CreateCompositeClientIfNeeded(web_contents.get(), browser_context->GetUserAgent()); #endif #if BUILDFLAG(ENABLE_PDF_VIEWER) pdf::PDFWebContentsHelper::CreateForWebContentsWithClient( web_contents.get(), std::make_unique<ElectronPDFWebContentsHelperClient>()); #endif // Determine whether the WebContents is offscreen. auto* web_preferences = WebContentsPreferences::From(web_contents.get()); offscreen_ = web_preferences && web_preferences->IsOffscreen(); // Create InspectableWebContents. inspectable_web_contents_ = std::make_unique<InspectableWebContents>( std::move(web_contents), browser_context->prefs(), is_guest); inspectable_web_contents_->SetDelegate(this); } WebContents::~WebContents() { // clear out objects that have been granted permissions so that when // WebContents::RenderFrameDeleted is called as a result of WebContents // destruction it doesn't try to clear out a granted_devices_ // on a destructed object. granted_devices_.clear(); if (!inspectable_web_contents_) { WebContentsDestroyed(); return; } inspectable_web_contents_->GetView()->SetDelegate(nullptr); // This event is only for internal use, which is emitted when WebContents is // being destroyed. Emit("will-destroy"); // For guest view based on OOPIF, the WebContents is released by the embedder // frame, and we need to clear the reference to the memory. bool not_owned_by_this = IsGuest() && attached_; #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) // And background pages are owned by extensions::ExtensionHost. if (type_ == Type::kBackgroundPage) not_owned_by_this = true; #endif if (not_owned_by_this) { inspectable_web_contents_->ReleaseWebContents(); WebContentsDestroyed(); } // InspectableWebContents will be automatically destroyed. } void WebContents::DeleteThisIfAlive() { // It is possible that the FirstWeakCallback has been called but the // SecondWeakCallback has not, in this case the garbage collection of // WebContents has already started and we should not |delete this|. // Calling |GetWrapper| can detect this corner case. auto* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); v8::Local<v8::Object> wrapper; if (!GetWrapper(isolate).ToLocal(&wrapper)) return; delete this; } void WebContents::Destroy() { // The content::WebContents should be destroyed asyncronously when possible // as user may choose to destroy WebContents during an event of it. if (Browser::Get()->is_shutting_down() || IsGuest()) { DeleteThisIfAlive(); } else { base::PostTask(FROM_HERE, {content::BrowserThread::UI}, base::BindOnce( [](base::WeakPtr<WebContents> contents) { if (contents) contents->DeleteThisIfAlive(); }, GetWeakPtr())); } } bool WebContents::DidAddMessageToConsole( content::WebContents* source, blink::mojom::ConsoleMessageLevel level, const std::u16string& message, int32_t line_no, const std::u16string& source_id) { return Emit("console-message", static_cast<int32_t>(level), message, line_no, source_id); } void WebContents::OnCreateWindow( const GURL& target_url, const content::Referrer& referrer, const std::string& frame_name, WindowOpenDisposition disposition, const std::string& features, const scoped_refptr<network::ResourceRequestBody>& body) { Emit("-new-window", target_url, frame_name, disposition, features, referrer, body); } void WebContents::WebContentsCreatedWithFullParams( content::WebContents* source_contents, int opener_render_process_id, int opener_render_frame_id, const content::mojom::CreateNewWindowParams& params, content::WebContents* new_contents) { ChildWebContentsTracker::CreateForWebContents(new_contents); auto* tracker = ChildWebContentsTracker::FromWebContents(new_contents); tracker->url = params.target_url; tracker->frame_name = params.frame_name; tracker->referrer = params.referrer.To<content::Referrer>(); tracker->raw_features = params.raw_features; tracker->body = params.body; v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::Locker locker(isolate); v8::HandleScope handle_scope(isolate); gin_helper::Dictionary dict; gin::ConvertFromV8(isolate, pending_child_web_preferences_.Get(isolate), &dict); pending_child_web_preferences_.Reset(); // Associate the preferences passed in via `setWindowOpenHandler` with the // content::WebContents that was just created for the child window. These // preferences will be picked up by the RenderWidgetHost via its call to the // delegate's OverrideWebkitPrefs. new WebContentsPreferences(new_contents, dict); } bool WebContents::IsWebContentsCreationOverridden( content::SiteInstance* source_site_instance, content::mojom::WindowContainerType window_container_type, const GURL& opener_url, const content::mojom::CreateNewWindowParams& params) { bool default_prevented = Emit( "-will-add-new-contents", params.target_url, params.frame_name, params.raw_features, params.disposition, *params.referrer, params.body); // If the app prevented the default, redirect to CreateCustomWebContents, // which always returns nullptr, which will result in the window open being // prevented (window.open() will return null in the renderer). return default_prevented; } void WebContents::SetNextChildWebPreferences( const gin_helper::Dictionary preferences) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::Locker locker(isolate); v8::HandleScope handle_scope(isolate); // Store these prefs for when Chrome calls WebContentsCreatedWithFullParams // with the new child contents. pending_child_web_preferences_.Reset(isolate, preferences.GetHandle()); } content::WebContents* WebContents::CreateCustomWebContents( content::RenderFrameHost* opener, content::SiteInstance* source_site_instance, bool is_new_browsing_instance, const GURL& opener_url, const std::string& frame_name, const GURL& target_url, const content::StoragePartitionConfig& partition_config, content::SessionStorageNamespace* session_storage_namespace) { return nullptr; } void WebContents::AddNewContents( content::WebContents* source, std::unique_ptr<content::WebContents> new_contents, const GURL& target_url, WindowOpenDisposition disposition, const gfx::Rect& initial_rect, bool user_gesture, bool* was_blocked) { auto* tracker = ChildWebContentsTracker::FromWebContents(new_contents.get()); DCHECK(tracker); v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::Locker locker(isolate); v8::HandleScope handle_scope(isolate); auto api_web_contents = CreateAndTake(isolate, std::move(new_contents), Type::kBrowserWindow); // We call RenderFrameCreated here as at this point the empty "about:blank" // render frame has already been created. If the window never navigates again // RenderFrameCreated won't be called and certain prefs like // "kBackgroundColor" will not be applied. auto* frame = api_web_contents->MainFrame(); if (frame) { api_web_contents->HandleNewRenderFrame(frame); } if (Emit("-add-new-contents", api_web_contents, disposition, user_gesture, initial_rect.x(), initial_rect.y(), initial_rect.width(), initial_rect.height(), tracker->url, tracker->frame_name, tracker->referrer, tracker->raw_features, tracker->body)) { api_web_contents->Destroy(); } } content::WebContents* WebContents::OpenURLFromTab( content::WebContents* source, const content::OpenURLParams& params) { auto weak_this = GetWeakPtr(); if (params.disposition != WindowOpenDisposition::CURRENT_TAB) { Emit("-new-window", params.url, "", params.disposition, "", params.referrer, params.post_data); return nullptr; } if (!weak_this || !web_contents()) return nullptr; content::NavigationController::LoadURLParams load_url_params(params.url); load_url_params.referrer = params.referrer; load_url_params.transition_type = params.transition; load_url_params.extra_headers = params.extra_headers; load_url_params.should_replace_current_entry = params.should_replace_current_entry; load_url_params.is_renderer_initiated = params.is_renderer_initiated; load_url_params.started_from_context_menu = params.started_from_context_menu; load_url_params.initiator_origin = params.initiator_origin; load_url_params.source_site_instance = params.source_site_instance; load_url_params.frame_tree_node_id = params.frame_tree_node_id; load_url_params.redirect_chain = params.redirect_chain; load_url_params.has_user_gesture = params.user_gesture; load_url_params.blob_url_loader_factory = params.blob_url_loader_factory; load_url_params.href_translate = params.href_translate; load_url_params.reload_type = params.reload_type; if (params.post_data) { load_url_params.load_type = content::NavigationController::LOAD_TYPE_HTTP_POST; load_url_params.post_data = params.post_data; } source->GetController().LoadURLWithParams(load_url_params); return source; } void WebContents::BeforeUnloadFired(content::WebContents* tab, bool proceed, bool* proceed_to_fire_unload) { if (type_ == Type::kBrowserWindow || type_ == Type::kOffScreen || type_ == Type::kBrowserView) *proceed_to_fire_unload = proceed; else *proceed_to_fire_unload = true; // Note that Chromium does not emit this for navigations. Emit("before-unload-fired", proceed); } void WebContents::SetContentsBounds(content::WebContents* source, const gfx::Rect& rect) { for (ExtendedWebContentsObserver& observer : observers_) observer.OnSetContentBounds(rect); } void WebContents::CloseContents(content::WebContents* source) { Emit("close"); auto* autofill_driver_factory = AutofillDriverFactory::FromWebContents(web_contents()); if (autofill_driver_factory) { autofill_driver_factory->CloseAllPopups(); } for (ExtendedWebContentsObserver& observer : observers_) observer.OnCloseContents(); } void WebContents::ActivateContents(content::WebContents* source) { for (ExtendedWebContentsObserver& observer : observers_) observer.OnActivateContents(); } void WebContents::UpdateTargetURL(content::WebContents* source, const GURL& url) { Emit("update-target-url", url); } bool WebContents::HandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) { if (type_ == Type::kWebView && embedder_) { // Send the unhandled keyboard events back to the embedder. return embedder_->HandleKeyboardEvent(source, event); } else { return PlatformHandleKeyboardEvent(source, event); } } #if !BUILDFLAG(IS_MAC) // NOTE: The macOS version of this function is found in // electron_api_web_contents_mac.mm, as it requires calling into objective-C // code. bool WebContents::PlatformHandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) { // Escape exits tabbed fullscreen mode. if (event.windows_key_code == ui::VKEY_ESCAPE && is_html_fullscreen()) { ExitFullscreenModeForTab(source); return true; } // Check if the webContents has preferences and to ignore shortcuts auto* web_preferences = WebContentsPreferences::From(source); if (web_preferences && web_preferences->ShouldIgnoreMenuShortcuts()) return false; // Let the NativeWindow handle other parts. if (owner_window()) { owner_window()->HandleKeyboardEvent(source, event); return true; } return false; } #endif content::KeyboardEventProcessingResult WebContents::PreHandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) { if (exclusive_access_manager_->HandleUserKeyEvent(event)) return content::KeyboardEventProcessingResult::HANDLED; if (event.GetType() == blink::WebInputEvent::Type::kRawKeyDown || event.GetType() == blink::WebInputEvent::Type::kKeyUp) { bool prevent_default = Emit("before-input-event", event); if (prevent_default) { return content::KeyboardEventProcessingResult::HANDLED; } } return content::KeyboardEventProcessingResult::NOT_HANDLED; } void WebContents::ContentsZoomChange(bool zoom_in) { Emit("zoom-changed", zoom_in ? "in" : "out"); } Profile* WebContents::GetProfile() { return nullptr; } bool WebContents::IsFullscreen() const { return owner_window_ && owner_window_->IsFullscreen(); } void WebContents::EnterFullscreen(const GURL& url, ExclusiveAccessBubbleType bubble_type, const int64_t display_id) {} void WebContents::ExitFullscreen() {} void WebContents::UpdateExclusiveAccessExitBubbleContent( const GURL& url, ExclusiveAccessBubbleType bubble_type, ExclusiveAccessBubbleHideCallback bubble_first_hide_callback, bool force_update) {} void WebContents::OnExclusiveAccessUserInput() {} content::WebContents* WebContents::GetActiveWebContents() { return web_contents(); } bool WebContents::CanUserExitFullscreen() const { return true; } bool WebContents::IsExclusiveAccessBubbleDisplayed() const { return false; } void WebContents::EnterFullscreenModeForTab( content::RenderFrameHost* requesting_frame, const blink::mojom::FullscreenOptions& options) { auto* source = content::WebContents::FromRenderFrameHost(requesting_frame); auto* permission_helper = WebContentsPermissionHelper::FromWebContents(source); auto callback = base::BindRepeating(&WebContents::OnEnterFullscreenModeForTab, base::Unretained(this), requesting_frame, options); permission_helper->RequestFullscreenPermission(callback); exclusive_access_manager_->fullscreen_controller()->EnterFullscreenModeForTab( requesting_frame, options.display_id); } void WebContents::OnEnterFullscreenModeForTab( content::RenderFrameHost* requesting_frame, const blink::mojom::FullscreenOptions& options, bool allowed) { if (!allowed || !owner_window_) return; auto* source = content::WebContents::FromRenderFrameHost(requesting_frame); if (IsFullscreenForTabOrPending(source)) { DCHECK_EQ(fullscreen_frame_, source->GetFocusedFrame()); return; } SetHtmlApiFullscreen(true); if (native_fullscreen_) { // Explicitly trigger a view resize, as the size is not actually changing if // the browser is fullscreened, too. source->GetRenderViewHost()->GetWidget()->SynchronizeVisualProperties(); } } void WebContents::ExitFullscreenModeForTab(content::WebContents* source) { if (!owner_window_) return; SetHtmlApiFullscreen(false); if (native_fullscreen_) { // Explicitly trigger a view resize, as the size is not actually changing if // the browser is fullscreened, too. Chrome does this indirectly from // `chrome/browser/ui/exclusive_access/fullscreen_controller.cc`. source->GetRenderViewHost()->GetWidget()->SynchronizeVisualProperties(); } exclusive_access_manager_->fullscreen_controller()->ExitFullscreenModeForTab( source); } void WebContents::RendererUnresponsive( content::WebContents* source, content::RenderWidgetHost* render_widget_host, base::RepeatingClosure hang_monitor_restarter) { Emit("unresponsive"); } void WebContents::RendererResponsive( content::WebContents* source, content::RenderWidgetHost* render_widget_host) { Emit("responsive"); } bool WebContents::HandleContextMenu(content::RenderFrameHost& render_frame_host, const content::ContextMenuParams& params) { Emit("context-menu", std::make_pair(params, &render_frame_host)); return true; } bool WebContents::OnGoToEntryOffset(int offset) { GoToOffset(offset); return false; } void WebContents::FindReply(content::WebContents* web_contents, int request_id, int number_of_matches, const gfx::Rect& selection_rect, int active_match_ordinal, bool final_update) { if (!final_update) return; v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::Locker locker(isolate); v8::HandleScope handle_scope(isolate); gin_helper::Dictionary result = gin::Dictionary::CreateEmpty(isolate); result.Set("requestId", request_id); result.Set("matches", number_of_matches); result.Set("selectionArea", selection_rect); result.Set("activeMatchOrdinal", active_match_ordinal); result.Set("finalUpdate", final_update); // Deprecate after 2.0 Emit("found-in-page", result.GetHandle()); } void WebContents::RequestExclusivePointerAccess( content::WebContents* web_contents, bool user_gesture, bool last_unlocked_by_target, bool allowed) { if (allowed) { exclusive_access_manager_->mouse_lock_controller()->RequestToLockMouse( web_contents, user_gesture, last_unlocked_by_target); } else { web_contents->GotResponseToLockMouseRequest( blink::mojom::PointerLockResult::kPermissionDenied); } } void WebContents::RequestToLockMouse(content::WebContents* web_contents, bool user_gesture, bool last_unlocked_by_target) { auto* permission_helper = WebContentsPermissionHelper::FromWebContents(web_contents); permission_helper->RequestPointerLockPermission( user_gesture, last_unlocked_by_target, base::BindOnce(&WebContents::RequestExclusivePointerAccess, base::Unretained(this))); } void WebContents::LostMouseLock() { exclusive_access_manager_->mouse_lock_controller()->LostMouseLock(); } void WebContents::RequestKeyboardLock(content::WebContents* web_contents, bool esc_key_locked) { exclusive_access_manager_->keyboard_lock_controller()->RequestKeyboardLock( web_contents, esc_key_locked); } void WebContents::CancelKeyboardLockRequest( content::WebContents* web_contents) { exclusive_access_manager_->keyboard_lock_controller() ->CancelKeyboardLockRequest(web_contents); } bool WebContents::CheckMediaAccessPermission( content::RenderFrameHost* render_frame_host, const GURL& security_origin, blink::mojom::MediaStreamType type) { auto* web_contents = content::WebContents::FromRenderFrameHost(render_frame_host); auto* permission_helper = WebContentsPermissionHelper::FromWebContents(web_contents); return permission_helper->CheckMediaAccessPermission(security_origin, type); } void WebContents::RequestMediaAccessPermission( content::WebContents* web_contents, const content::MediaStreamRequest& request, content::MediaResponseCallback callback) { auto* permission_helper = WebContentsPermissionHelper::FromWebContents(web_contents); permission_helper->RequestMediaAccessPermission(request, std::move(callback)); } content::JavaScriptDialogManager* WebContents::GetJavaScriptDialogManager( content::WebContents* source) { if (!dialog_manager_) dialog_manager_ = std::make_unique<ElectronJavaScriptDialogManager>(); return dialog_manager_.get(); } void WebContents::OnAudioStateChanged(bool audible) { Emit("-audio-state-changed", audible); } void WebContents::BeforeUnloadFired(bool proceed, const base::TimeTicks& proceed_time) { // Do nothing, we override this method just to avoid compilation error since // there are two virtual functions named BeforeUnloadFired. } void WebContents::HandleNewRenderFrame( content::RenderFrameHost* render_frame_host) { auto* rwhv = render_frame_host->GetView(); if (!rwhv) return; // Set the background color of RenderWidgetHostView. auto* web_preferences = WebContentsPreferences::From(web_contents()); if (web_preferences) { absl::optional<SkColor> maybe_color = web_preferences->GetBackgroundColor(); web_contents()->SetPageBaseBackgroundColor(maybe_color); bool guest = IsGuest() || type_ == Type::kBrowserView; SkColor color = maybe_color.value_or(guest ? SK_ColorTRANSPARENT : SK_ColorWHITE); SetBackgroundColor(rwhv, color); } if (!background_throttling_) render_frame_host->GetRenderViewHost()->SetSchedulerThrottling(false); auto* rwh_impl = static_cast<content::RenderWidgetHostImpl*>(rwhv->GetRenderWidgetHost()); if (rwh_impl) rwh_impl->disable_hidden_ = !background_throttling_; auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host); if (web_frame) web_frame->Connect(); } void WebContents::OnBackgroundColorChanged() { absl::optional<SkColor> color = web_contents()->GetBackgroundColor(); if (color.has_value()) { auto* const view = web_contents()->GetRenderWidgetHostView(); static_cast<content::RenderWidgetHostViewBase*>(view) ->SetContentBackgroundColor(color.value()); } } void WebContents::RenderFrameCreated( content::RenderFrameHost* render_frame_host) { HandleNewRenderFrame(render_frame_host); // RenderFrameCreated is called for speculative frames which may not be // used in certain cross-origin navigations. Invoking // RenderFrameHost::GetLifecycleState currently crashes when called for // speculative frames so we need to filter it out for now. Check // https://crbug.com/1183639 for details on when this can be removed. auto* rfh_impl = static_cast<content::RenderFrameHostImpl*>(render_frame_host); if (rfh_impl->lifecycle_state() == content::RenderFrameHostImpl::LifecycleStateImpl::kSpeculative) { return; } content::RenderFrameHost::LifecycleState lifecycle_state = render_frame_host->GetLifecycleState(); if (lifecycle_state == content::RenderFrameHost::LifecycleState::kActive) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); gin_helper::Dictionary details = gin_helper::Dictionary::CreateEmpty(isolate); details.SetGetter("frame", render_frame_host); Emit("frame-created", details); } } void WebContents::RenderFrameDeleted( content::RenderFrameHost* render_frame_host) { // A RenderFrameHost can be deleted when: // - A WebContents is removed and its containing frames are disposed. // - An <iframe> is removed from the DOM. // - Cross-origin navigation creates a new RFH in a separate process which // is swapped by content::RenderFrameHostManager. // // clear out objects that have been granted permissions if (!granted_devices_.empty()) { granted_devices_.erase(render_frame_host->GetFrameTreeNodeId()); } // WebFrameMain::FromRenderFrameHost(rfh) will use the RFH's FrameTreeNode ID // to find an existing instance of WebFrameMain. During a cross-origin // navigation, the deleted RFH will be the old host which was swapped out. In // this special case, we need to also ensure that WebFrameMain's internal RFH // matches before marking it as disposed. auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host); if (web_frame && web_frame->render_frame_host() == render_frame_host) web_frame->MarkRenderFrameDisposed(); } void WebContents::RenderFrameHostChanged(content::RenderFrameHost* old_host, content::RenderFrameHost* new_host) { // During cross-origin navigation, a FrameTreeNode will swap out its RFH. // If an instance of WebFrameMain exists, it will need to have its RFH // swapped as well. // // |old_host| can be a nullptr so we use |new_host| for looking up the // WebFrameMain instance. auto* web_frame = WebFrameMain::FromFrameTreeNodeId(new_host->GetFrameTreeNodeId()); if (web_frame) { web_frame->UpdateRenderFrameHost(new_host); } } void WebContents::FrameDeleted(int frame_tree_node_id) { auto* web_frame = WebFrameMain::FromFrameTreeNodeId(frame_tree_node_id); if (web_frame) web_frame->Destroyed(); } void WebContents::RenderViewDeleted(content::RenderViewHost* render_view_host) { // This event is necessary for tracking any states with respect to // intermediate render view hosts aka speculative render view hosts. Currently // used by object-registry.js to ref count remote objects. Emit("render-view-deleted", render_view_host->GetProcess()->GetID()); if (web_contents()->GetRenderViewHost() == render_view_host) { // When the RVH that has been deleted is the current RVH it means that the // the web contents are being closed. This is communicated by this event. // Currently tracked by guest-window-manager.ts to destroy the // BrowserWindow. Emit("current-render-view-deleted", render_view_host->GetProcess()->GetID()); } } void WebContents::PrimaryMainFrameRenderProcessGone( base::TerminationStatus status) { auto weak_this = GetWeakPtr(); Emit("crashed", status == base::TERMINATION_STATUS_PROCESS_WAS_KILLED); // User might destroy WebContents in the crashed event. if (!weak_this || !web_contents()) return; v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); gin_helper::Dictionary details = gin_helper::Dictionary::CreateEmpty(isolate); details.Set("reason", status); details.Set("exitCode", web_contents()->GetCrashedErrorCode()); Emit("render-process-gone", details); } void WebContents::PluginCrashed(const base::FilePath& plugin_path, base::ProcessId plugin_pid) { #if BUILDFLAG(ENABLE_PLUGINS) content::WebPluginInfo info; auto* plugin_service = content::PluginService::GetInstance(); plugin_service->GetPluginInfoByPath(plugin_path, &info); Emit("plugin-crashed", info.name, info.version); #endif // BUILDFLAG(ENABLE_PLUGINS) } void WebContents::MediaStartedPlaying(const MediaPlayerInfo& video_type, const content::MediaPlayerId& id) { Emit("media-started-playing"); } void WebContents::MediaStoppedPlaying( const MediaPlayerInfo& video_type, const content::MediaPlayerId& id, content::WebContentsObserver::MediaStoppedReason reason) { Emit("media-paused"); } void WebContents::DidChangeThemeColor() { auto theme_color = web_contents()->GetThemeColor(); if (theme_color) { Emit("did-change-theme-color", electron::ToRGBHex(theme_color.value())); } else { Emit("did-change-theme-color", nullptr); } } void WebContents::DidAcquireFullscreen(content::RenderFrameHost* rfh) { set_fullscreen_frame(rfh); } void WebContents::OnWebContentsFocused( content::RenderWidgetHost* render_widget_host) { Emit("focus"); } void WebContents::OnWebContentsLostFocus( content::RenderWidgetHost* render_widget_host) { Emit("blur"); } void WebContents::DOMContentLoaded( content::RenderFrameHost* render_frame_host) { auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host); if (web_frame) web_frame->DOMContentLoaded(); if (!render_frame_host->GetParent()) Emit("dom-ready"); } void WebContents::DidFinishLoad(content::RenderFrameHost* render_frame_host, const GURL& validated_url) { bool is_main_frame = !render_frame_host->GetParent(); int frame_process_id = render_frame_host->GetProcess()->GetID(); int frame_routing_id = render_frame_host->GetRoutingID(); auto weak_this = GetWeakPtr(); Emit("did-frame-finish-load", is_main_frame, frame_process_id, frame_routing_id); // ⚠️WARNING!⚠️ // Emit() triggers JS which can call destroy() on |this|. It's not safe to // assume that |this| points to valid memory at this point. if (is_main_frame && weak_this && web_contents()) Emit("did-finish-load"); } void WebContents::DidFailLoad(content::RenderFrameHost* render_frame_host, const GURL& url, int error_code) { bool is_main_frame = !render_frame_host->GetParent(); int frame_process_id = render_frame_host->GetProcess()->GetID(); int frame_routing_id = render_frame_host->GetRoutingID(); Emit("did-fail-load", error_code, "", url, is_main_frame, frame_process_id, frame_routing_id); } void WebContents::DidStartLoading() { Emit("did-start-loading"); } void WebContents::DidStopLoading() { auto* web_preferences = WebContentsPreferences::From(web_contents()); if (web_preferences && web_preferences->ShouldUsePreferredSizeMode()) web_contents()->GetRenderViewHost()->EnablePreferredSizeMode(); Emit("did-stop-loading"); } bool WebContents::EmitNavigationEvent( const std::string& event, content::NavigationHandle* navigation_handle) { bool is_main_frame = navigation_handle->IsInMainFrame(); int frame_tree_node_id = navigation_handle->GetFrameTreeNodeId(); content::FrameTreeNode* frame_tree_node = content::FrameTreeNode::GloballyFindByID(frame_tree_node_id); content::RenderFrameHostManager* render_manager = frame_tree_node->render_manager(); content::RenderFrameHost* frame_host = nullptr; if (render_manager) { frame_host = render_manager->speculative_frame_host(); if (!frame_host) frame_host = render_manager->current_frame_host(); } int frame_process_id = -1, frame_routing_id = -1; if (frame_host) { frame_process_id = frame_host->GetProcess()->GetID(); frame_routing_id = frame_host->GetRoutingID(); } bool is_same_document = navigation_handle->IsSameDocument(); auto url = navigation_handle->GetURL(); return Emit(event, url, is_same_document, is_main_frame, frame_process_id, frame_routing_id); } void WebContents::Message(bool internal, const std::string& channel, blink::CloneableMessage arguments, content::RenderFrameHost* render_frame_host) { TRACE_EVENT1("electron", "WebContents::Message", "channel", channel); // webContents.emit('-ipc-message', new Event(), internal, channel, // arguments); EmitWithSender("-ipc-message", render_frame_host, electron::mojom::ElectronApiIPC::InvokeCallback(), internal, channel, std::move(arguments)); } void WebContents::Invoke( bool internal, const std::string& channel, blink::CloneableMessage arguments, electron::mojom::ElectronApiIPC::InvokeCallback callback, content::RenderFrameHost* render_frame_host) { TRACE_EVENT1("electron", "WebContents::Invoke", "channel", channel); // webContents.emit('-ipc-invoke', new Event(), internal, channel, arguments); EmitWithSender("-ipc-invoke", render_frame_host, std::move(callback), internal, channel, std::move(arguments)); } void WebContents::OnFirstNonEmptyLayout( content::RenderFrameHost* render_frame_host) { if (render_frame_host == web_contents()->GetMainFrame()) { Emit("ready-to-show"); } } void WebContents::ReceivePostMessage( const std::string& channel, blink::TransferableMessage message, content::RenderFrameHost* render_frame_host) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); auto wrapped_ports = MessagePort::EntanglePorts(isolate, std::move(message.ports)); v8::Local<v8::Value> message_value = electron::DeserializeV8Value(isolate, message); EmitWithSender("-ipc-ports", render_frame_host, electron::mojom::ElectronApiIPC::InvokeCallback(), false, channel, message_value, std::move(wrapped_ports)); } void WebContents::MessageSync( bool internal, const std::string& channel, blink::CloneableMessage arguments, electron::mojom::ElectronApiIPC::MessageSyncCallback callback, content::RenderFrameHost* render_frame_host) { TRACE_EVENT1("electron", "WebContents::MessageSync", "channel", channel); // webContents.emit('-ipc-message-sync', new Event(sender, message), internal, // channel, arguments); EmitWithSender("-ipc-message-sync", render_frame_host, std::move(callback), internal, channel, std::move(arguments)); } void WebContents::MessageTo(int32_t web_contents_id, const std::string& channel, blink::CloneableMessage arguments) { TRACE_EVENT1("electron", "WebContents::MessageTo", "channel", channel); auto* target_web_contents = FromID(web_contents_id); if (target_web_contents) { content::RenderFrameHost* frame = target_web_contents->MainFrame(); DCHECK(frame); v8::HandleScope handle_scope(JavascriptEnvironment::GetIsolate()); gin::Handle<WebFrameMain> web_frame_main = WebFrameMain::From(JavascriptEnvironment::GetIsolate(), frame); if (!web_frame_main->CheckRenderFrame()) return; int32_t sender_id = ID(); web_frame_main->GetRendererApi()->Message(false /* internal */, channel, std::move(arguments), sender_id); } } void WebContents::MessageHost(const std::string& channel, blink::CloneableMessage arguments, content::RenderFrameHost* render_frame_host) { TRACE_EVENT1("electron", "WebContents::MessageHost", "channel", channel); // webContents.emit('ipc-message-host', new Event(), channel, args); EmitWithSender("ipc-message-host", render_frame_host, electron::mojom::ElectronApiIPC::InvokeCallback(), channel, std::move(arguments)); } void WebContents::UpdateDraggableRegions( std::vector<mojom::DraggableRegionPtr> regions) { for (ExtendedWebContentsObserver& observer : observers_) observer.OnDraggableRegionsUpdated(regions); } void WebContents::DidStartNavigation( content::NavigationHandle* navigation_handle) { EmitNavigationEvent("did-start-navigation", navigation_handle); } void WebContents::DidRedirectNavigation( content::NavigationHandle* navigation_handle) { EmitNavigationEvent("did-redirect-navigation", navigation_handle); } void WebContents::ReadyToCommitNavigation( content::NavigationHandle* navigation_handle) { // Don't focus content in an inactive window. if (!owner_window()) return; #if BUILDFLAG(IS_MAC) if (!owner_window()->IsActive()) return; #else if (!owner_window()->widget()->IsActive()) return; #endif // Don't focus content after subframe navigations. if (!navigation_handle->IsInMainFrame()) return; // Only focus for top-level contents. if (type_ != Type::kBrowserWindow) return; web_contents()->SetInitialFocus(); } void WebContents::DidFinishNavigation( content::NavigationHandle* navigation_handle) { if (owner_window_) { owner_window_->NotifyLayoutWindowControlsOverlay(); } if (!navigation_handle->HasCommitted()) return; bool is_main_frame = navigation_handle->IsInMainFrame(); content::RenderFrameHost* frame_host = navigation_handle->GetRenderFrameHost(); int frame_process_id = -1, frame_routing_id = -1; if (frame_host) { frame_process_id = frame_host->GetProcess()->GetID(); frame_routing_id = frame_host->GetRoutingID(); } if (!navigation_handle->IsErrorPage()) { // FIXME: All the Emit() calls below could potentially result in |this| // being destroyed (by JS listening for the event and calling // webContents.destroy()). auto url = navigation_handle->GetURL(); bool is_same_document = navigation_handle->IsSameDocument(); if (is_same_document) { Emit("did-navigate-in-page", url, is_main_frame, frame_process_id, frame_routing_id); } else { const net::HttpResponseHeaders* http_response = navigation_handle->GetResponseHeaders(); std::string http_status_text; int http_response_code = -1; if (http_response) { http_status_text = http_response->GetStatusText(); http_response_code = http_response->response_code(); } Emit("did-frame-navigate", url, http_response_code, http_status_text, is_main_frame, frame_process_id, frame_routing_id); if (is_main_frame) { Emit("did-navigate", url, http_response_code, http_status_text); } } if (IsGuest()) Emit("load-commit", url, is_main_frame); } else { auto url = navigation_handle->GetURL(); int code = navigation_handle->GetNetErrorCode(); auto description = net::ErrorToShortString(code); Emit("did-fail-provisional-load", code, description, url, is_main_frame, frame_process_id, frame_routing_id); // Do not emit "did-fail-load" for canceled requests. if (code != net::ERR_ABORTED) { EmitWarning( node::Environment::GetCurrent(JavascriptEnvironment::GetIsolate()), "Failed to load URL: " + url.possibly_invalid_spec() + " with error: " + description, "electron"); Emit("did-fail-load", code, description, url, is_main_frame, frame_process_id, frame_routing_id); } } content::NavigationEntry* entry = navigation_handle->GetNavigationEntry(); // This check is needed due to an issue in Chromium // Check the Chromium issue to keep updated: // https://bugs.chromium.org/p/chromium/issues/detail?id=1178663 // If a history entry has been made and the forward/back call has been made, // proceed with setting the new title if (entry && (entry->GetTransitionType() & ui::PAGE_TRANSITION_FORWARD_BACK)) WebContents::TitleWasSet(entry); } void WebContents::TitleWasSet(content::NavigationEntry* entry) { std::u16string final_title; bool explicit_set = true; if (entry) { auto title = entry->GetTitle(); auto url = entry->GetURL(); if (url.SchemeIsFile() && title.empty()) { final_title = base::UTF8ToUTF16(url.ExtractFileName()); explicit_set = false; } else { final_title = title; } } else { final_title = web_contents()->GetTitle(); } for (ExtendedWebContentsObserver& observer : observers_) observer.OnPageTitleUpdated(final_title, explicit_set); Emit("page-title-updated", final_title, explicit_set); } void WebContents::DidUpdateFaviconURL( content::RenderFrameHost* render_frame_host, const std::vector<blink::mojom::FaviconURLPtr>& urls) { std::set<GURL> unique_urls; for (const auto& iter : urls) { if (iter->icon_type != blink::mojom::FaviconIconType::kFavicon) continue; const GURL& url = iter->icon_url; if (url.is_valid()) unique_urls.insert(url); } Emit("page-favicon-updated", unique_urls); } void WebContents::DevToolsReloadPage() { Emit("devtools-reload-page"); } void WebContents::DevToolsFocused() { Emit("devtools-focused"); } void WebContents::DevToolsOpened() { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::Locker locker(isolate); v8::HandleScope handle_scope(isolate); DCHECK(inspectable_web_contents_); DCHECK(inspectable_web_contents_->GetDevToolsWebContents()); auto handle = FromOrCreate( isolate, inspectable_web_contents_->GetDevToolsWebContents()); devtools_web_contents_.Reset(isolate, handle.ToV8()); // Set inspected tabID. base::Value tab_id(ID()); inspectable_web_contents_->CallClientFunction("DevToolsAPI.setInspectedTabId", &tab_id, nullptr, nullptr); // Inherit owner window in devtools when it doesn't have one. auto* devtools = inspectable_web_contents_->GetDevToolsWebContents(); bool has_window = devtools->GetUserData(NativeWindowRelay::UserDataKey()); if (owner_window() && !has_window) handle->SetOwnerWindow(devtools, owner_window()); Emit("devtools-opened"); } void WebContents::DevToolsClosed() { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::Locker locker(isolate); v8::HandleScope handle_scope(isolate); devtools_web_contents_.Reset(); Emit("devtools-closed"); } void WebContents::DevToolsResized() { for (ExtendedWebContentsObserver& observer : observers_) observer.OnDevToolsResized(); } void WebContents::SetOwnerWindow(NativeWindow* owner_window) { SetOwnerWindow(GetWebContents(), owner_window); } void WebContents::SetOwnerWindow(content::WebContents* web_contents, NativeWindow* owner_window) { if (owner_window) { owner_window_ = owner_window->GetWeakPtr(); NativeWindowRelay::CreateForWebContents(web_contents, owner_window->GetWeakPtr()); } else { owner_window_ = nullptr; web_contents->RemoveUserData(NativeWindowRelay::UserDataKey()); } #if BUILDFLAG(ENABLE_OSR) auto* osr_wcv = GetOffScreenWebContentsView(); if (osr_wcv) osr_wcv->SetNativeWindow(owner_window); #endif } content::WebContents* WebContents::GetWebContents() const { if (!inspectable_web_contents_) return nullptr; return inspectable_web_contents_->GetWebContents(); } content::WebContents* WebContents::GetDevToolsWebContents() const { if (!inspectable_web_contents_) return nullptr; return inspectable_web_contents_->GetDevToolsWebContents(); } void WebContents::WebContentsDestroyed() { // Clear the pointer stored in wrapper. if (GetAllWebContents().Lookup(id_)) GetAllWebContents().Remove(id_); v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); v8::Local<v8::Object> wrapper; if (!GetWrapper(isolate).ToLocal(&wrapper)) return; wrapper->SetAlignedPointerInInternalField(0, nullptr); // Tell WebViewGuestDelegate that the WebContents has been destroyed. if (guest_delegate_) guest_delegate_->WillDestroy(); Observe(nullptr); Emit("destroyed"); } void WebContents::NavigationEntryCommitted( const content::LoadCommittedDetails& details) { Emit("navigation-entry-committed", details.entry->GetURL(), details.is_same_document, details.did_replace_entry); } bool WebContents::GetBackgroundThrottling() const { return background_throttling_; } void WebContents::SetBackgroundThrottling(bool allowed) { background_throttling_ = allowed; auto* rfh = web_contents()->GetMainFrame(); if (!rfh) return; auto* rwhv = rfh->GetView(); if (!rwhv) return; auto* rwh_impl = static_cast<content::RenderWidgetHostImpl*>(rwhv->GetRenderWidgetHost()); if (!rwh_impl) return; rwh_impl->disable_hidden_ = !background_throttling_; web_contents()->GetRenderViewHost()->SetSchedulerThrottling(allowed); if (rwh_impl->is_hidden()) { rwh_impl->WasShown({}); } } int WebContents::GetProcessID() const { return web_contents()->GetMainFrame()->GetProcess()->GetID(); } base::ProcessId WebContents::GetOSProcessID() const { base::ProcessHandle process_handle = web_contents()->GetMainFrame()->GetProcess()->GetProcess().Handle(); return base::GetProcId(process_handle); } WebContents::Type WebContents::GetType() const { return type_; } bool WebContents::Equal(const WebContents* web_contents) const { return ID() == web_contents->ID(); } GURL WebContents::GetURL() const { return web_contents()->GetLastCommittedURL(); } void WebContents::LoadURL(const GURL& url, const gin_helper::Dictionary& options) { if (!url.is_valid() || url.spec().size() > url::kMaxURLChars) { Emit("did-fail-load", static_cast<int>(net::ERR_INVALID_URL), net::ErrorToShortString(net::ERR_INVALID_URL), url.possibly_invalid_spec(), true); return; } content::NavigationController::LoadURLParams params(url); if (!options.Get("httpReferrer", &params.referrer)) { GURL http_referrer; if (options.Get("httpReferrer", &http_referrer)) params.referrer = content::Referrer(http_referrer.GetAsReferrer(), network::mojom::ReferrerPolicy::kDefault); } std::string user_agent; if (options.Get("userAgent", &user_agent)) web_contents()->SetUserAgentOverride( blink::UserAgentOverride::UserAgentOnly(user_agent), false); std::string extra_headers; if (options.Get("extraHeaders", &extra_headers)) params.extra_headers = extra_headers; scoped_refptr<network::ResourceRequestBody> body; if (options.Get("postData", &body)) { params.post_data = body; params.load_type = content::NavigationController::LOAD_TYPE_HTTP_POST; } GURL base_url_for_data_url; if (options.Get("baseURLForDataURL", &base_url_for_data_url)) { params.base_url_for_data_url = base_url_for_data_url; params.load_type = content::NavigationController::LOAD_TYPE_DATA; } bool reload_ignoring_cache = false; if (options.Get("reloadIgnoringCache", &reload_ignoring_cache) && reload_ignoring_cache) { params.reload_type = content::ReloadType::BYPASSING_CACHE; } // Calling LoadURLWithParams() can trigger JS which destroys |this|. auto weak_this = GetWeakPtr(); params.transition_type = ui::PageTransitionFromInt( ui::PAGE_TRANSITION_TYPED | ui::PAGE_TRANSITION_FROM_ADDRESS_BAR); params.override_user_agent = content::NavigationController::UA_OVERRIDE_TRUE; // Discord non-committed entries to ensure that we don't re-use a pending // entry web_contents()->GetController().DiscardNonCommittedEntries(); web_contents()->GetController().LoadURLWithParams(params); // ⚠️WARNING!⚠️ // LoadURLWithParams() triggers JS events which can call destroy() on |this|. // It's not safe to assume that |this| points to valid memory at this point. if (!weak_this || !web_contents()) return; // Required to make beforeunload handler work. NotifyUserActivation(); } // TODO(MarshallOfSound): Figure out what we need to do with post data here, I // believe the default behavior when we pass "true" is to phone out to the // delegate and then the controller expects this method to be called again with // "false" if the user approves the reload. For now this would result in // ".reload()" calls on POST data domains failing silently. Passing false would // result in them succeeding, but reposting which although more correct could be // considering a breaking change. void WebContents::Reload() { web_contents()->GetController().Reload(content::ReloadType::NORMAL, /* check_for_repost */ true); } void WebContents::ReloadIgnoringCache() { web_contents()->GetController().Reload(content::ReloadType::BYPASSING_CACHE, /* check_for_repost */ true); } void WebContents::DownloadURL(const GURL& url) { auto* browser_context = web_contents()->GetBrowserContext(); auto* download_manager = browser_context->GetDownloadManager(); std::unique_ptr<download::DownloadUrlParameters> download_params( content::DownloadRequestUtils::CreateDownloadForWebContentsMainFrame( web_contents(), url, MISSING_TRAFFIC_ANNOTATION)); download_manager->DownloadUrl(std::move(download_params)); } std::u16string WebContents::GetTitle() const { return web_contents()->GetTitle(); } bool WebContents::IsLoading() const { return web_contents()->IsLoading(); } bool WebContents::IsLoadingMainFrame() const { return web_contents()->ShouldShowLoadingUI(); } bool WebContents::IsWaitingForResponse() const { return web_contents()->IsWaitingForResponse(); } void WebContents::Stop() { web_contents()->Stop(); } bool WebContents::CanGoBack() const { return web_contents()->GetController().CanGoBack(); } void WebContents::GoBack() { if (CanGoBack()) web_contents()->GetController().GoBack(); } bool WebContents::CanGoForward() const { return web_contents()->GetController().CanGoForward(); } void WebContents::GoForward() { if (CanGoForward()) web_contents()->GetController().GoForward(); } bool WebContents::CanGoToOffset(int offset) const { return web_contents()->GetController().CanGoToOffset(offset); } void WebContents::GoToOffset(int offset) { if (CanGoToOffset(offset)) web_contents()->GetController().GoToOffset(offset); } bool WebContents::CanGoToIndex(int index) const { return index >= 0 && index < GetHistoryLength(); } void WebContents::GoToIndex(int index) { if (CanGoToIndex(index)) web_contents()->GetController().GoToIndex(index); } int WebContents::GetActiveIndex() const { return web_contents()->GetController().GetCurrentEntryIndex(); } void WebContents::ClearHistory() { // In some rare cases (normally while there is no real history) we are in a // state where we can't prune navigation entries if (web_contents()->GetController().CanPruneAllButLastCommitted()) { web_contents()->GetController().PruneAllButLastCommitted(); } } int WebContents::GetHistoryLength() const { return web_contents()->GetController().GetEntryCount(); } const std::string WebContents::GetWebRTCIPHandlingPolicy() const { return web_contents()->GetMutableRendererPrefs()->webrtc_ip_handling_policy; } void WebContents::SetWebRTCIPHandlingPolicy( const std::string& webrtc_ip_handling_policy) { if (GetWebRTCIPHandlingPolicy() == webrtc_ip_handling_policy) return; web_contents()->GetMutableRendererPrefs()->webrtc_ip_handling_policy = webrtc_ip_handling_policy; web_contents()->SyncRendererPrefs(); } std::string WebContents::GetMediaSourceID( content::WebContents* request_web_contents) { auto* frame_host = web_contents()->GetMainFrame(); if (!frame_host) return std::string(); content::DesktopMediaID media_id( content::DesktopMediaID::TYPE_WEB_CONTENTS, content::DesktopMediaID::kNullId, content::WebContentsMediaCaptureId(frame_host->GetProcess()->GetID(), frame_host->GetRoutingID())); auto* request_frame_host = request_web_contents->GetMainFrame(); if (!request_frame_host) return std::string(); std::string id = content::DesktopStreamsRegistry::GetInstance()->RegisterStream( request_frame_host->GetProcess()->GetID(), request_frame_host->GetRoutingID(), url::Origin::Create(request_frame_host->GetLastCommittedURL() .DeprecatedGetOriginAsURL()), media_id, "", content::kRegistryStreamTypeTab); return id; } bool WebContents::IsCrashed() const { return web_contents()->IsCrashed(); } void WebContents::ForcefullyCrashRenderer() { content::RenderWidgetHostView* view = web_contents()->GetRenderWidgetHostView(); if (!view) return; content::RenderWidgetHost* rwh = view->GetRenderWidgetHost(); if (!rwh) return; content::RenderProcessHost* rph = rwh->GetProcess(); if (rph) { #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) // A generic |CrashDumpHungChildProcess()| is not implemented for Linux. // Instead we send an explicit IPC to crash on the renderer's IO thread. rph->ForceCrash(); #else // Try to generate a crash report for the hung process. #ifndef MAS_BUILD CrashDumpHungChildProcess(rph->GetProcess().Handle()); #endif rph->Shutdown(content::RESULT_CODE_HUNG); #endif } } void WebContents::SetUserAgent(const std::string& user_agent) { web_contents()->SetUserAgentOverride( blink::UserAgentOverride::UserAgentOnly(user_agent), false); } std::string WebContents::GetUserAgent() { return web_contents()->GetUserAgentOverride().ua_string_override; } v8::Local<v8::Promise> WebContents::SavePage( const base::FilePath& full_file_path, const content::SavePageType& save_type) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); gin_helper::Promise<void> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); if (!full_file_path.IsAbsolute()) { promise.RejectWithErrorMessage("Path must be absolute"); return handle; } auto* handler = new SavePageHandler(web_contents(), std::move(promise)); handler->Handle(full_file_path, save_type); return handle; } void WebContents::OpenDevTools(gin::Arguments* args) { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; std::string state; if (type_ == Type::kWebView || type_ == Type::kBackgroundPage || !owner_window()) { state = "detach"; } bool activate = true; if (args && args->Length() == 1) { gin_helper::Dictionary options; if (args->GetNext(&options)) { options.Get("mode", &state); options.Get("activate", &activate); } } DCHECK(inspectable_web_contents_); inspectable_web_contents_->SetDockState(state); inspectable_web_contents_->ShowDevTools(activate); } void WebContents::CloseDevTools() { if (type_ == Type::kRemote) return; DCHECK(inspectable_web_contents_); inspectable_web_contents_->CloseDevTools(); } bool WebContents::IsDevToolsOpened() { if (type_ == Type::kRemote) return false; DCHECK(inspectable_web_contents_); return inspectable_web_contents_->IsDevToolsViewShowing(); } bool WebContents::IsDevToolsFocused() { if (type_ == Type::kRemote) return false; DCHECK(inspectable_web_contents_); return inspectable_web_contents_->GetView()->IsDevToolsViewFocused(); } void WebContents::EnableDeviceEmulation( const blink::DeviceEmulationParams& params) { if (type_ == Type::kRemote) return; DCHECK(web_contents()); auto* frame_host = web_contents()->GetMainFrame(); if (frame_host) { auto* widget_host_impl = static_cast<content::RenderWidgetHostImpl*>( frame_host->GetView()->GetRenderWidgetHost()); if (widget_host_impl) { auto& frame_widget = widget_host_impl->GetAssociatedFrameWidget(); frame_widget->EnableDeviceEmulation(params); } } } void WebContents::DisableDeviceEmulation() { if (type_ == Type::kRemote) return; DCHECK(web_contents()); auto* frame_host = web_contents()->GetMainFrame(); if (frame_host) { auto* widget_host_impl = static_cast<content::RenderWidgetHostImpl*>( frame_host->GetView()->GetRenderWidgetHost()); if (widget_host_impl) { auto& frame_widget = widget_host_impl->GetAssociatedFrameWidget(); frame_widget->DisableDeviceEmulation(); } } } void WebContents::ToggleDevTools() { if (IsDevToolsOpened()) CloseDevTools(); else OpenDevTools(nullptr); } void WebContents::InspectElement(int x, int y) { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; DCHECK(inspectable_web_contents_); if (!inspectable_web_contents_->GetDevToolsWebContents()) OpenDevTools(nullptr); inspectable_web_contents_->InspectElement(x, y); } void WebContents::InspectSharedWorkerById(const std::string& workerId) { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) { if (agent_host->GetType() == content::DevToolsAgentHost::kTypeSharedWorker) { if (agent_host->GetId() == workerId) { OpenDevTools(nullptr); inspectable_web_contents_->AttachTo(agent_host); break; } } } } std::vector<scoped_refptr<content::DevToolsAgentHost>> WebContents::GetAllSharedWorkers() { std::vector<scoped_refptr<content::DevToolsAgentHost>> shared_workers; if (type_ == Type::kRemote) return shared_workers; if (!enable_devtools_) return shared_workers; for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) { if (agent_host->GetType() == content::DevToolsAgentHost::kTypeSharedWorker) { shared_workers.push_back(agent_host); } } return shared_workers; } void WebContents::InspectSharedWorker() { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) { if (agent_host->GetType() == content::DevToolsAgentHost::kTypeSharedWorker) { OpenDevTools(nullptr); inspectable_web_contents_->AttachTo(agent_host); break; } } } void WebContents::InspectServiceWorker() { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) { if (agent_host->GetType() == content::DevToolsAgentHost::kTypeServiceWorker) { OpenDevTools(nullptr); inspectable_web_contents_->AttachTo(agent_host); break; } } } void WebContents::SetIgnoreMenuShortcuts(bool ignore) { auto* web_preferences = WebContentsPreferences::From(web_contents()); DCHECK(web_preferences); web_preferences->SetIgnoreMenuShortcuts(ignore); } void WebContents::SetAudioMuted(bool muted) { web_contents()->SetAudioMuted(muted); } bool WebContents::IsAudioMuted() { return web_contents()->IsAudioMuted(); } bool WebContents::IsCurrentlyAudible() { return web_contents()->IsCurrentlyAudible(); } #if BUILDFLAG(ENABLE_PRINTING) void WebContents::OnGetDefaultPrinter( base::Value print_settings, printing::CompletionCallback print_callback, std::u16string device_name, bool silent, // <error, default_printer> std::pair<std::string, std::u16string> info) { // The content::WebContents might be already deleted at this point, and the // PrintViewManagerElectron class does not do null check. if (!web_contents()) { if (print_callback) std::move(print_callback).Run(false, "failed"); return; } if (!info.first.empty()) { if (print_callback) std::move(print_callback).Run(false, info.first); return; } // If the user has passed a deviceName use it, otherwise use default printer. std::u16string printer_name = device_name.empty() ? info.second : device_name; // If there are no valid printers available on the network, we bail. if (printer_name.empty() || !IsDeviceNameValid(printer_name)) { if (print_callback) std::move(print_callback).Run(false, "no valid printers available"); return; } print_settings.SetStringKey(printing::kSettingDeviceName, printer_name); auto* print_view_manager = PrintViewManagerElectron::FromWebContents(web_contents()); if (!print_view_manager) return; auto* focused_frame = web_contents()->GetFocusedFrame(); auto* rfh = focused_frame && focused_frame->HasSelection() ? focused_frame : web_contents()->GetMainFrame(); print_view_manager->PrintNow(rfh, silent, std::move(print_settings), std::move(print_callback)); } void WebContents::Print(gin::Arguments* args) { gin_helper::Dictionary options = gin::Dictionary::CreateEmpty(args->isolate()); base::Value settings(base::Value::Type::DICTIONARY); if (args->Length() >= 1 && !args->GetNext(&options)) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("webContents.print(): Invalid print settings specified."); return; } printing::CompletionCallback callback; if (args->Length() == 2 && !args->GetNext(&callback)) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("webContents.print(): Invalid optional callback provided."); return; } // Set optional silent printing bool silent = false; options.Get("silent", &silent); bool print_background = false; options.Get("printBackground", &print_background); settings.SetBoolKey(printing::kSettingShouldPrintBackgrounds, print_background); // Set custom margin settings gin_helper::Dictionary margins = gin::Dictionary::CreateEmpty(args->isolate()); if (options.Get("margins", &margins)) { printing::mojom::MarginType margin_type = printing::mojom::MarginType::kDefaultMargins; margins.Get("marginType", &margin_type); settings.SetIntKey(printing::kSettingMarginsType, static_cast<int>(margin_type)); if (margin_type == printing::mojom::MarginType::kCustomMargins) { base::Value custom_margins(base::Value::Type::DICTIONARY); int top = 0; margins.Get("top", &top); custom_margins.SetIntKey(printing::kSettingMarginTop, top); int bottom = 0; margins.Get("bottom", &bottom); custom_margins.SetIntKey(printing::kSettingMarginBottom, bottom); int left = 0; margins.Get("left", &left); custom_margins.SetIntKey(printing::kSettingMarginLeft, left); int right = 0; margins.Get("right", &right); custom_margins.SetIntKey(printing::kSettingMarginRight, right); settings.SetPath(printing::kSettingMarginsCustom, std::move(custom_margins)); } } else { settings.SetIntKey( printing::kSettingMarginsType, static_cast<int>(printing::mojom::MarginType::kDefaultMargins)); } // Set whether to print color or greyscale bool print_color = true; options.Get("color", &print_color); auto const color_model = print_color ? printing::mojom::ColorModel::kColor : printing::mojom::ColorModel::kGray; settings.SetIntKey(printing::kSettingColor, static_cast<int>(color_model)); // Is the orientation landscape or portrait. bool landscape = false; options.Get("landscape", &landscape); settings.SetBoolKey(printing::kSettingLandscape, landscape); // We set the default to the system's default printer and only update // if at the Chromium level if the user overrides. // Printer device name as opened by the OS. std::u16string device_name; options.Get("deviceName", &device_name); if (!device_name.empty() && !IsDeviceNameValid(device_name)) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("webContents.print(): Invalid deviceName provided."); return; } int scale_factor = 100; options.Get("scaleFactor", &scale_factor); settings.SetIntKey(printing::kSettingScaleFactor, scale_factor); int pages_per_sheet = 1; options.Get("pagesPerSheet", &pages_per_sheet); settings.SetIntKey(printing::kSettingPagesPerSheet, pages_per_sheet); // True if the user wants to print with collate. bool collate = true; options.Get("collate", &collate); settings.SetBoolKey(printing::kSettingCollate, collate); // The number of individual copies to print int copies = 1; options.Get("copies", &copies); settings.SetIntKey(printing::kSettingCopies, copies); // Strings to be printed as headers and footers if requested by the user. std::string header; options.Get("header", &header); std::string footer; options.Get("footer", &footer); if (!(header.empty() && footer.empty())) { settings.SetBoolKey(printing::kSettingHeaderFooterEnabled, true); settings.SetStringKey(printing::kSettingHeaderFooterTitle, header); settings.SetStringKey(printing::kSettingHeaderFooterURL, footer); } else { settings.SetBoolKey(printing::kSettingHeaderFooterEnabled, false); } // We don't want to allow the user to enable these settings // but we need to set them or a CHECK is hit. settings.SetIntKey(printing::kSettingPrinterType, static_cast<int>(printing::mojom::PrinterType::kLocal)); settings.SetBoolKey(printing::kSettingShouldPrintSelectionOnly, false); settings.SetBoolKey(printing::kSettingRasterizePdf, false); // Set custom page ranges to print std::vector<gin_helper::Dictionary> page_ranges; if (options.Get("pageRanges", &page_ranges)) { base::Value page_range_list(base::Value::Type::LIST); for (auto& range : page_ranges) { int from, to; if (range.Get("from", &from) && range.Get("to", &to)) { base::Value range(base::Value::Type::DICTIONARY); // Chromium uses 1-based page ranges, so increment each by 1. range.SetIntKey(printing::kSettingPageRangeFrom, from + 1); range.SetIntKey(printing::kSettingPageRangeTo, to + 1); page_range_list.Append(std::move(range)); } else { continue; } } if (!page_range_list.GetListDeprecated().empty()) settings.SetPath(printing::kSettingPageRange, std::move(page_range_list)); } // Duplex type user wants to use. printing::mojom::DuplexMode duplex_mode = printing::mojom::DuplexMode::kSimplex; options.Get("duplexMode", &duplex_mode); settings.SetIntKey(printing::kSettingDuplexMode, static_cast<int>(duplex_mode)); // We've already done necessary parameter sanitization at the // JS level, so we can simply pass this through. base::Value media_size(base::Value::Type::DICTIONARY); if (options.Get("mediaSize", &media_size)) settings.SetKey(printing::kSettingMediaSize, std::move(media_size)); // Set custom dots per inch (dpi) gin_helper::Dictionary dpi_settings; int dpi = 72; if (options.Get("dpi", &dpi_settings)) { int horizontal = 72; dpi_settings.Get("horizontal", &horizontal); settings.SetIntKey(printing::kSettingDpiHorizontal, horizontal); int vertical = 72; dpi_settings.Get("vertical", &vertical); settings.SetIntKey(printing::kSettingDpiVertical, vertical); } else { settings.SetIntKey(printing::kSettingDpiHorizontal, dpi); settings.SetIntKey(printing::kSettingDpiVertical, dpi); } print_task_runner_->PostTaskAndReplyWithResult( FROM_HERE, base::BindOnce(&GetDefaultPrinterAsync), base::BindOnce(&WebContents::OnGetDefaultPrinter, weak_factory_.GetWeakPtr(), std::move(settings), std::move(callback), device_name, silent)); } v8::Local<v8::Promise> WebContents::PrintToPDF(base::DictionaryValue settings) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); gin_helper::Promise<v8::Local<v8::Value>> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); PrintPreviewMessageHandler::FromWebContents(web_contents()) ->PrintToPDF(std::move(settings), std::move(promise)); return handle; } #endif void WebContents::AddWorkSpace(gin::Arguments* args, const base::FilePath& path) { if (path.empty()) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("path cannot be empty"); return; } DevToolsAddFileSystem(std::string(), path); } void WebContents::RemoveWorkSpace(gin::Arguments* args, const base::FilePath& path) { if (path.empty()) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("path cannot be empty"); return; } DevToolsRemoveFileSystem(path); } void WebContents::Undo() { web_contents()->Undo(); } void WebContents::Redo() { web_contents()->Redo(); } void WebContents::Cut() { web_contents()->Cut(); } void WebContents::Copy() { web_contents()->Copy(); } void WebContents::Paste() { web_contents()->Paste(); } void WebContents::PasteAndMatchStyle() { web_contents()->PasteAndMatchStyle(); } void WebContents::Delete() { web_contents()->Delete(); } void WebContents::SelectAll() { web_contents()->SelectAll(); } void WebContents::Unselect() { web_contents()->CollapseSelection(); } void WebContents::Replace(const std::u16string& word) { web_contents()->Replace(word); } void WebContents::ReplaceMisspelling(const std::u16string& word) { web_contents()->ReplaceMisspelling(word); } uint32_t WebContents::FindInPage(gin::Arguments* args) { std::u16string search_text; if (!args->GetNext(&search_text) || search_text.empty()) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("Must provide a non-empty search content"); return 0; } uint32_t request_id = ++find_in_page_request_id_; gin_helper::Dictionary dict; auto options = blink::mojom::FindOptions::New(); if (args->GetNext(&dict)) { dict.Get("forward", &options->forward); dict.Get("matchCase", &options->match_case); dict.Get("findNext", &options->new_session); } web_contents()->Find(request_id, search_text, std::move(options)); return request_id; } void WebContents::StopFindInPage(content::StopFindAction action) { web_contents()->StopFinding(action); } void WebContents::ShowDefinitionForSelection() { #if BUILDFLAG(IS_MAC) auto* const view = web_contents()->GetRenderWidgetHostView(); if (view) view->ShowDefinitionForSelection(); #endif } void WebContents::CopyImageAt(int x, int y) { auto* const host = web_contents()->GetMainFrame(); if (host) host->CopyImageAt(x, y); } void WebContents::Focus() { // Focusing on WebContents does not automatically focus the window on macOS // and Linux, do it manually to match the behavior on Windows. #if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX) if (owner_window()) owner_window()->Focus(true); #endif web_contents()->Focus(); } #if !BUILDFLAG(IS_MAC) bool WebContents::IsFocused() const { auto* view = web_contents()->GetRenderWidgetHostView(); if (!view) return false; if (GetType() != Type::kBackgroundPage) { auto* window = web_contents()->GetNativeView()->GetToplevelWindow(); if (window && !window->IsVisible()) return false; } return view->HasFocus(); } #endif void WebContents::SendInputEvent(v8::Isolate* isolate, v8::Local<v8::Value> input_event) { content::RenderWidgetHostView* view = web_contents()->GetRenderWidgetHostView(); if (!view) return; content::RenderWidgetHost* rwh = view->GetRenderWidgetHost(); blink::WebInputEvent::Type type = gin::GetWebInputEventType(isolate, input_event); if (blink::WebInputEvent::IsMouseEventType(type)) { blink::WebMouseEvent mouse_event; if (gin::ConvertFromV8(isolate, input_event, &mouse_event)) { if (IsOffScreen()) { #if BUILDFLAG(ENABLE_OSR) GetOffScreenRenderWidgetHostView()->SendMouseEvent(mouse_event); #endif } else { rwh->ForwardMouseEvent(mouse_event); } return; } } else if (blink::WebInputEvent::IsKeyboardEventType(type)) { content::NativeWebKeyboardEvent keyboard_event( blink::WebKeyboardEvent::Type::kRawKeyDown, blink::WebInputEvent::Modifiers::kNoModifiers, ui::EventTimeForNow()); if (gin::ConvertFromV8(isolate, input_event, &keyboard_event)) { rwh->ForwardKeyboardEvent(keyboard_event); return; } } else if (type == blink::WebInputEvent::Type::kMouseWheel) { blink::WebMouseWheelEvent mouse_wheel_event; if (gin::ConvertFromV8(isolate, input_event, &mouse_wheel_event)) { if (IsOffScreen()) { #if BUILDFLAG(ENABLE_OSR) GetOffScreenRenderWidgetHostView()->SendMouseWheelEvent( mouse_wheel_event); #endif } else { // Chromium expects phase info in wheel events (and applies a // DCHECK to verify it). See: https://crbug.com/756524. mouse_wheel_event.phase = blink::WebMouseWheelEvent::kPhaseBegan; mouse_wheel_event.dispatch_type = blink::WebInputEvent::DispatchType::kBlocking; rwh->ForwardWheelEvent(mouse_wheel_event); // Send a synthetic wheel event with phaseEnded to finish scrolling. mouse_wheel_event.has_synthetic_phase = true; mouse_wheel_event.delta_x = 0; mouse_wheel_event.delta_y = 0; mouse_wheel_event.phase = blink::WebMouseWheelEvent::kPhaseEnded; mouse_wheel_event.dispatch_type = blink::WebInputEvent::DispatchType::kEventNonBlocking; rwh->ForwardWheelEvent(mouse_wheel_event); } return; } } isolate->ThrowException( v8::Exception::Error(gin::StringToV8(isolate, "Invalid event object"))); } void WebContents::BeginFrameSubscription(gin::Arguments* args) { bool only_dirty = false; FrameSubscriber::FrameCaptureCallback callback; if (args->Length() > 1) { if (!args->GetNext(&only_dirty)) { args->ThrowError(); return; } } if (!args->GetNext(&callback)) { args->ThrowError(); return; } frame_subscriber_ = std::make_unique<FrameSubscriber>(web_contents(), callback, only_dirty); } void WebContents::EndFrameSubscription() { frame_subscriber_.reset(); } void WebContents::StartDrag(const gin_helper::Dictionary& item, gin::Arguments* args) { base::FilePath file; std::vector<base::FilePath> files; if (!item.Get("files", &files) && item.Get("file", &file)) { files.push_back(file); } v8::Local<v8::Value> icon_value; if (!item.Get("icon", &icon_value)) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("'icon' parameter is required"); return; } NativeImage* icon = nullptr; if (!NativeImage::TryConvertNativeImage(args->isolate(), icon_value, &icon) || icon->image().IsEmpty()) { return; } // Start dragging. if (!files.empty()) { base::CurrentThread::ScopedNestableTaskAllower allow; DragFileItems(files, icon->image(), web_contents()->GetNativeView()); } else { gin_helper::ErrorThrower(args->isolate()) .ThrowError("Must specify either 'file' or 'files' option"); } } v8::Local<v8::Promise> WebContents::CapturePage(gin::Arguments* args) { gfx::Rect rect; gin_helper::Promise<gfx::Image> promise(args->isolate()); v8::Local<v8::Promise> handle = promise.GetHandle(); // get rect arguments if they exist args->GetNext(&rect); auto* const view = web_contents()->GetRenderWidgetHostView(); if (!view) { promise.Resolve(gfx::Image()); return handle; } #if !BUILDFLAG(IS_MAC) // If the view's renderer is suspended this may fail on Windows/Linux - // bail if so. See CopyFromSurface in // content/public/browser/render_widget_host_view.h. auto* rfh = web_contents()->GetMainFrame(); if (rfh && rfh->GetVisibilityState() == blink::mojom::PageVisibilityState::kHidden) { promise.Resolve(gfx::Image()); return handle; } #endif // BUILDFLAG(IS_MAC) // Capture full page if user doesn't specify a |rect|. const gfx::Size view_size = rect.IsEmpty() ? view->GetViewBounds().size() : rect.size(); // By default, the requested bitmap size is the view size in screen // coordinates. However, if there's more pixel detail available on the // current system, increase the requested bitmap size to capture it all. gfx::Size bitmap_size = view_size; const gfx::NativeView native_view = view->GetNativeView(); const float scale = display::Screen::GetScreen() ->GetDisplayNearestView(native_view) .device_scale_factor(); if (scale > 1.0f) bitmap_size = gfx::ScaleToCeiledSize(view_size, scale); view->CopyFromSurface(gfx::Rect(rect.origin(), view_size), bitmap_size, base::BindOnce(&OnCapturePageDone, std::move(promise))); return handle; } void WebContents::IncrementCapturerCount(gin::Arguments* args) { gfx::Size size; bool stay_hidden = false; bool stay_awake = false; // get size arguments if they exist args->GetNext(&size); // get stayHidden arguments if they exist args->GetNext(&stay_hidden); // get stayAwake arguments if they exist args->GetNext(&stay_awake); std::ignore = web_contents() ->IncrementCapturerCount(size, stay_hidden, stay_awake) .Release(); } void WebContents::DecrementCapturerCount(gin::Arguments* args) { bool stay_hidden = false; bool stay_awake = false; // get stayHidden arguments if they exist args->GetNext(&stay_hidden); // get stayAwake arguments if they exist args->GetNext(&stay_awake); web_contents()->DecrementCapturerCount(stay_hidden, stay_awake); } bool WebContents::IsBeingCaptured() { return web_contents()->IsBeingCaptured(); } void WebContents::OnCursorChanged(const content::WebCursor& webcursor) { const ui::Cursor& cursor = webcursor.cursor(); if (cursor.type() == ui::mojom::CursorType::kCustom) { Emit("cursor-changed", CursorTypeToString(cursor), gfx::Image::CreateFrom1xBitmap(cursor.custom_bitmap()), cursor.image_scale_factor(), gfx::Size(cursor.custom_bitmap().width(), cursor.custom_bitmap().height()), cursor.custom_hotspot()); } else { Emit("cursor-changed", CursorTypeToString(cursor)); } } bool WebContents::IsGuest() const { return type_ == Type::kWebView; } void WebContents::AttachToIframe(content::WebContents* embedder_web_contents, int embedder_frame_id) { attached_ = true; if (guest_delegate_) guest_delegate_->AttachToIframe(embedder_web_contents, embedder_frame_id); } bool WebContents::IsOffScreen() const { #if BUILDFLAG(ENABLE_OSR) return type_ == Type::kOffScreen; #else return false; #endif } #if BUILDFLAG(ENABLE_OSR) void WebContents::OnPaint(const gfx::Rect& dirty_rect, const SkBitmap& bitmap) { Emit("paint", dirty_rect, gfx::Image::CreateFrom1xBitmap(bitmap)); } void WebContents::StartPainting() { auto* osr_wcv = GetOffScreenWebContentsView(); if (osr_wcv) osr_wcv->SetPainting(true); } void WebContents::StopPainting() { auto* osr_wcv = GetOffScreenWebContentsView(); if (osr_wcv) osr_wcv->SetPainting(false); } bool WebContents::IsPainting() const { auto* osr_wcv = GetOffScreenWebContentsView(); return osr_wcv && osr_wcv->IsPainting(); } void WebContents::SetFrameRate(int frame_rate) { auto* osr_wcv = GetOffScreenWebContentsView(); if (osr_wcv) osr_wcv->SetFrameRate(frame_rate); } int WebContents::GetFrameRate() const { auto* osr_wcv = GetOffScreenWebContentsView(); return osr_wcv ? osr_wcv->GetFrameRate() : 0; } #endif void WebContents::Invalidate() { if (IsOffScreen()) { #if BUILDFLAG(ENABLE_OSR) auto* osr_rwhv = GetOffScreenRenderWidgetHostView(); if (osr_rwhv) osr_rwhv->Invalidate(); #endif } else { auto* const window = owner_window(); if (window) window->Invalidate(); } } gfx::Size WebContents::GetSizeForNewRenderView(content::WebContents* wc) { if (IsOffScreen() && wc == web_contents()) { auto* relay = NativeWindowRelay::FromWebContents(web_contents()); if (relay) { auto* owner_window = relay->GetNativeWindow(); return owner_window ? owner_window->GetSize() : gfx::Size(); } } return gfx::Size(); } void WebContents::SetZoomLevel(double level) { zoom_controller_->SetZoomLevel(level); } double WebContents::GetZoomLevel() const { return zoom_controller_->GetZoomLevel(); } void WebContents::SetZoomFactor(gin_helper::ErrorThrower thrower, double factor) { if (factor < std::numeric_limits<double>::epsilon()) { thrower.ThrowError("'zoomFactor' must be a double greater than 0.0"); return; } auto level = blink::PageZoomFactorToZoomLevel(factor); SetZoomLevel(level); } double WebContents::GetZoomFactor() const { auto level = GetZoomLevel(); return blink::PageZoomLevelToZoomFactor(level); } void WebContents::SetTemporaryZoomLevel(double level) { zoom_controller_->SetTemporaryZoomLevel(level); } void WebContents::DoGetZoomLevel( electron::mojom::ElectronWebContentsUtility::DoGetZoomLevelCallback callback) { std::move(callback).Run(GetZoomLevel()); } std::vector<base::FilePath> WebContents::GetPreloadPaths() const { auto result = SessionPreferences::GetValidPreloads(GetBrowserContext()); if (auto* web_preferences = WebContentsPreferences::From(web_contents())) { base::FilePath preload; if (web_preferences->GetPreloadPath(&preload)) { result.emplace_back(preload); } } return result; } v8::Local<v8::Value> WebContents::GetLastWebPreferences( v8::Isolate* isolate) const { auto* web_preferences = WebContentsPreferences::From(web_contents()); if (!web_preferences) return v8::Null(isolate); return gin::ConvertToV8(isolate, *web_preferences->last_preference()); } v8::Local<v8::Value> WebContents::GetOwnerBrowserWindow( v8::Isolate* isolate) const { if (owner_window()) return BrowserWindow::From(isolate, owner_window()); else return v8::Null(isolate); } v8::Local<v8::Value> WebContents::Session(v8::Isolate* isolate) { return v8::Local<v8::Value>::New(isolate, session_); } content::WebContents* WebContents::HostWebContents() const { if (!embedder_) return nullptr; return embedder_->web_contents(); } void WebContents::SetEmbedder(const WebContents* embedder) { if (embedder) { NativeWindow* owner_window = nullptr; auto* relay = NativeWindowRelay::FromWebContents(embedder->web_contents()); if (relay) { owner_window = relay->GetNativeWindow(); } if (owner_window) SetOwnerWindow(owner_window); content::RenderWidgetHostView* rwhv = web_contents()->GetRenderWidgetHostView(); if (rwhv) { rwhv->Hide(); rwhv->Show(); } } } void WebContents::SetDevToolsWebContents(const WebContents* devtools) { if (inspectable_web_contents_) inspectable_web_contents_->SetDevToolsWebContents(devtools->web_contents()); } v8::Local<v8::Value> WebContents::GetNativeView(v8::Isolate* isolate) const { gfx::NativeView ptr = web_contents()->GetNativeView(); auto buffer = node::Buffer::Copy(isolate, reinterpret_cast<char*>(&ptr), sizeof(gfx::NativeView)); if (buffer.IsEmpty()) return v8::Null(isolate); else return buffer.ToLocalChecked(); } v8::Local<v8::Value> WebContents::DevToolsWebContents(v8::Isolate* isolate) { if (devtools_web_contents_.IsEmpty()) return v8::Null(isolate); else return v8::Local<v8::Value>::New(isolate, devtools_web_contents_); } v8::Local<v8::Value> WebContents::Debugger(v8::Isolate* isolate) { if (debugger_.IsEmpty()) { auto handle = electron::api::Debugger::Create(isolate, web_contents()); debugger_.Reset(isolate, handle.ToV8()); } return v8::Local<v8::Value>::New(isolate, debugger_); } content::RenderFrameHost* WebContents::MainFrame() { return web_contents()->GetMainFrame(); } void WebContents::NotifyUserActivation() { content::RenderFrameHost* frame = web_contents()->GetMainFrame(); if (frame) frame->NotifyUserActivation( blink::mojom::UserActivationNotificationType::kInteraction); } void WebContents::SetImageAnimationPolicy(const std::string& new_policy) { auto* web_preferences = WebContentsPreferences::From(web_contents()); web_preferences->SetImageAnimationPolicy(new_policy); web_contents()->OnWebPreferencesChanged(); } v8::Local<v8::Promise> WebContents::GetProcessMemoryInfo(v8::Isolate* isolate) { gin_helper::Promise<gin_helper::Dictionary> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); auto* frame_host = web_contents()->GetMainFrame(); if (!frame_host) { promise.RejectWithErrorMessage("Failed to create memory dump"); return handle; } auto pid = frame_host->GetProcess()->GetProcess().Pid(); v8::Global<v8::Context> context(isolate, isolate->GetCurrentContext()); memory_instrumentation::MemoryInstrumentation::GetInstance() ->RequestGlobalDumpForPid( pid, std::vector<std::string>(), base::BindOnce(&ElectronBindings::DidReceiveMemoryDump, std::move(context), std::move(promise), pid)); return handle; } v8::Local<v8::Promise> WebContents::TakeHeapSnapshot( v8::Isolate* isolate, const base::FilePath& file_path) { gin_helper::Promise<void> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); base::ThreadRestrictions::ScopedAllowIO allow_io; base::File file(file_path, base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE); if (!file.IsValid()) { promise.RejectWithErrorMessage("takeHeapSnapshot failed"); return handle; } auto* frame_host = web_contents()->GetMainFrame(); if (!frame_host) { promise.RejectWithErrorMessage("takeHeapSnapshot failed"); return handle; } if (!frame_host->IsRenderFrameCreated()) { promise.RejectWithErrorMessage("takeHeapSnapshot failed"); return handle; } // This dance with `base::Owned` is to ensure that the interface stays alive // until the callback is called. Otherwise it would be closed at the end of // this function. auto electron_renderer = std::make_unique<mojo::Remote<mojom::ElectronRenderer>>(); frame_host->GetRemoteInterfaces()->GetInterface( electron_renderer->BindNewPipeAndPassReceiver()); auto* raw_ptr = electron_renderer.get(); (*raw_ptr)->TakeHeapSnapshot( mojo::WrapPlatformFile(base::ScopedPlatformFile(file.TakePlatformFile())), base::BindOnce( [](mojo::Remote<mojom::ElectronRenderer>* ep, gin_helper::Promise<void> promise, bool success) { if (success) { promise.Resolve(); } else { promise.RejectWithErrorMessage("takeHeapSnapshot failed"); } }, base::Owned(std::move(electron_renderer)), std::move(promise))); return handle; } void WebContents::GrantDevicePermission( const url::Origin& origin, const base::Value* device, content::PermissionType permissionType, content::RenderFrameHost* render_frame_host) { granted_devices_[render_frame_host->GetFrameTreeNodeId()][permissionType] [origin] .push_back( std::make_unique<base::Value>(device->Clone())); } std::vector<base::Value> WebContents::GetGrantedDevices( const url::Origin& origin, content::PermissionType permissionType, content::RenderFrameHost* render_frame_host) { const auto& devices_for_frame_host_it = granted_devices_.find(render_frame_host->GetFrameTreeNodeId()); if (devices_for_frame_host_it == granted_devices_.end()) return {}; const auto& current_devices_it = devices_for_frame_host_it->second.find(permissionType); if (current_devices_it == devices_for_frame_host_it->second.end()) return {}; const auto& origin_devices_it = current_devices_it->second.find(origin); if (origin_devices_it == current_devices_it->second.end()) return {}; std::vector<base::Value> results; for (const auto& object : origin_devices_it->second) results.push_back(object->Clone()); return results; } void WebContents::UpdatePreferredSize(content::WebContents* web_contents, const gfx::Size& pref_size) { Emit("preferred-size-changed", pref_size); } bool WebContents::CanOverscrollContent() { return false; } std::unique_ptr<content::EyeDropper> WebContents::OpenEyeDropper( content::RenderFrameHost* frame, content::EyeDropperListener* listener) { return ShowEyeDropper(frame, listener); } void WebContents::RunFileChooser( content::RenderFrameHost* render_frame_host, scoped_refptr<content::FileSelectListener> listener, const blink::mojom::FileChooserParams& params) { FileSelectHelper::RunFileChooser(render_frame_host, std::move(listener), params); } void WebContents::EnumerateDirectory( content::WebContents* web_contents, scoped_refptr<content::FileSelectListener> listener, const base::FilePath& path) { FileSelectHelper::EnumerateDirectory(web_contents, std::move(listener), path); } bool WebContents::IsFullscreenForTabOrPending( const content::WebContents* source) { return html_fullscreen_; } bool WebContents::TakeFocus(content::WebContents* source, bool reverse) { if (source && source->GetOutermostWebContents() == source) { // If this is the outermost web contents and the user has tabbed or // shift + tabbed through all the elements, reset the focus back to // the first or last element so that it doesn't stay in the body. source->FocusThroughTabTraversal(reverse); return true; } return false; } content::PictureInPictureResult WebContents::EnterPictureInPicture( content::WebContents* web_contents) { #if BUILDFLAG(ENABLE_PICTURE_IN_PICTURE) return PictureInPictureWindowManager::GetInstance() ->EnterVideoPictureInPicture(web_contents); #else return content::PictureInPictureResult::kNotSupported; #endif } void WebContents::ExitPictureInPicture() { #if BUILDFLAG(ENABLE_PICTURE_IN_PICTURE) PictureInPictureWindowManager::GetInstance()->ExitPictureInPicture(); #endif } void WebContents::DevToolsSaveToFile(const std::string& url, const std::string& content, bool save_as) { base::FilePath path; auto it = saved_files_.find(url); if (it != saved_files_.end() && !save_as) { path = it->second; } else { file_dialog::DialogSettings settings; settings.parent_window = owner_window(); settings.force_detached = offscreen_; settings.title = url; settings.default_path = base::FilePath::FromUTF8Unsafe(url); if (!file_dialog::ShowSaveDialogSync(settings, &path)) { base::Value url_value(url); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.canceledSaveURL", &url_value, nullptr, nullptr); return; } } saved_files_[url] = path; // Notify DevTools. base::Value url_value(url); base::Value file_system_path_value(path.AsUTF8Unsafe()); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.savedURL", &url_value, &file_system_path_value, nullptr); file_task_runner_->PostTask(FROM_HERE, base::BindOnce(&WriteToFile, path, content)); } void WebContents::DevToolsAppendToFile(const std::string& url, const std::string& content) { auto it = saved_files_.find(url); if (it == saved_files_.end()) return; // Notify DevTools. base::Value url_value(url); inspectable_web_contents_->CallClientFunction("DevToolsAPI.appendedToURL", &url_value, nullptr, nullptr); file_task_runner_->PostTask( FROM_HERE, base::BindOnce(&AppendToFile, it->second, content)); } void WebContents::DevToolsRequestFileSystems() { auto file_system_paths = GetAddedFileSystemPaths(GetDevToolsWebContents()); if (file_system_paths.empty()) { base::ListValue empty_file_system_value; inspectable_web_contents_->CallClientFunction( "DevToolsAPI.fileSystemsLoaded", &empty_file_system_value, nullptr, nullptr); return; } std::vector<FileSystem> file_systems; for (const auto& file_system_path : file_system_paths) { base::FilePath path = base::FilePath::FromUTF8Unsafe(file_system_path.first); std::string file_system_id = RegisterFileSystem(GetDevToolsWebContents(), path); FileSystem file_system = CreateFileSystemStruct(GetDevToolsWebContents(), file_system_id, file_system_path.first, file_system_path.second); file_systems.push_back(file_system); } base::ListValue file_system_value; for (const auto& file_system : file_systems) file_system_value.Append(CreateFileSystemValue(file_system)); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.fileSystemsLoaded", &file_system_value, nullptr, nullptr); } void WebContents::DevToolsAddFileSystem( const std::string& type, const base::FilePath& file_system_path) { base::FilePath path = file_system_path; if (path.empty()) { std::vector<base::FilePath> paths; file_dialog::DialogSettings settings; settings.parent_window = owner_window(); settings.force_detached = offscreen_; settings.properties = file_dialog::OPEN_DIALOG_OPEN_DIRECTORY; if (!file_dialog::ShowOpenDialogSync(settings, &paths)) return; path = paths[0]; } std::string file_system_id = RegisterFileSystem(GetDevToolsWebContents(), path); if (IsDevToolsFileSystemAdded(GetDevToolsWebContents(), path.AsUTF8Unsafe())) return; FileSystem file_system = CreateFileSystemStruct( GetDevToolsWebContents(), file_system_id, path.AsUTF8Unsafe(), type); std::unique_ptr<base::DictionaryValue> file_system_value( CreateFileSystemValue(file_system)); auto* pref_service = GetPrefService(GetDevToolsWebContents()); DictionaryPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths); update.Get()->SetKey(path.AsUTF8Unsafe(), base::Value(type)); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.fileSystemAdded", nullptr, file_system_value.get(), nullptr); } void WebContents::DevToolsRemoveFileSystem( const base::FilePath& file_system_path) { if (!inspectable_web_contents_) return; std::string path = file_system_path.AsUTF8Unsafe(); storage::IsolatedContext::GetInstance()->RevokeFileSystemByPath( file_system_path); auto* pref_service = GetPrefService(GetDevToolsWebContents()); DictionaryPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths); update.Get()->RemoveKey(path); base::Value file_system_path_value(path); inspectable_web_contents_->CallClientFunction("DevToolsAPI.fileSystemRemoved", &file_system_path_value, nullptr, nullptr); } void WebContents::DevToolsIndexPath( int request_id, const std::string& file_system_path, const std::string& excluded_folders_message) { if (!IsDevToolsFileSystemAdded(GetDevToolsWebContents(), file_system_path)) { OnDevToolsIndexingDone(request_id, file_system_path); return; } if (devtools_indexing_jobs_.count(request_id) != 0) return; std::vector<std::string> excluded_folders; std::unique_ptr<base::Value> parsed_excluded_folders = base::JSONReader::ReadDeprecated(excluded_folders_message); if (parsed_excluded_folders && parsed_excluded_folders->is_list()) { for (const base::Value& folder_path : parsed_excluded_folders->GetListDeprecated()) { if (folder_path.is_string()) excluded_folders.push_back(folder_path.GetString()); } } devtools_indexing_jobs_[request_id] = scoped_refptr<DevToolsFileSystemIndexer::FileSystemIndexingJob>( devtools_file_system_indexer_->IndexPath( file_system_path, excluded_folders, base::BindRepeating( &WebContents::OnDevToolsIndexingWorkCalculated, weak_factory_.GetWeakPtr(), request_id, file_system_path), base::BindRepeating(&WebContents::OnDevToolsIndexingWorked, weak_factory_.GetWeakPtr(), request_id, file_system_path), base::BindRepeating(&WebContents::OnDevToolsIndexingDone, weak_factory_.GetWeakPtr(), request_id, file_system_path))); } void WebContents::DevToolsStopIndexing(int request_id) { auto it = devtools_indexing_jobs_.find(request_id); if (it == devtools_indexing_jobs_.end()) return; it->second->Stop(); devtools_indexing_jobs_.erase(it); } void WebContents::DevToolsSearchInPath(int request_id, const std::string& file_system_path, const std::string& query) { if (!IsDevToolsFileSystemAdded(GetDevToolsWebContents(), file_system_path)) { OnDevToolsSearchCompleted(request_id, file_system_path, std::vector<std::string>()); return; } devtools_file_system_indexer_->SearchInPath( file_system_path, query, base::BindRepeating(&WebContents::OnDevToolsSearchCompleted, weak_factory_.GetWeakPtr(), request_id, file_system_path)); } void WebContents::DevToolsSetEyeDropperActive(bool active) { auto* web_contents = GetWebContents(); if (!web_contents) return; if (active) { eye_dropper_ = std::make_unique<DevToolsEyeDropper>( web_contents, base::BindRepeating(&WebContents::ColorPickedInEyeDropper, base::Unretained(this))); } else { eye_dropper_.reset(); } } void WebContents::ColorPickedInEyeDropper(int r, int g, int b, int a) { base::DictionaryValue color; color.SetInteger("r", r); color.SetInteger("g", g); color.SetInteger("b", b); color.SetInteger("a", a); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.eyeDropperPickedColor", &color, nullptr, nullptr); } #if defined(TOOLKIT_VIEWS) && !BUILDFLAG(IS_MAC) ui::ImageModel WebContents::GetDevToolsWindowIcon() { return owner_window() ? owner_window()->GetWindowAppIcon() : ui::ImageModel{}; } #endif #if BUILDFLAG(IS_LINUX) void WebContents::GetDevToolsWindowWMClass(std::string* name, std::string* class_name) { *class_name = Browser::Get()->GetName(); *name = base::ToLowerASCII(*class_name); } #endif void WebContents::OnDevToolsIndexingWorkCalculated( int request_id, const std::string& file_system_path, int total_work) { base::Value request_id_value(request_id); base::Value file_system_path_value(file_system_path); base::Value total_work_value(total_work); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.indexingTotalWorkCalculated", &request_id_value, &file_system_path_value, &total_work_value); } void WebContents::OnDevToolsIndexingWorked(int request_id, const std::string& file_system_path, int worked) { base::Value request_id_value(request_id); base::Value file_system_path_value(file_system_path); base::Value worked_value(worked); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.indexingWorked", &request_id_value, &file_system_path_value, &worked_value); } void WebContents::OnDevToolsIndexingDone(int request_id, const std::string& file_system_path) { devtools_indexing_jobs_.erase(request_id); base::Value request_id_value(request_id); base::Value file_system_path_value(file_system_path); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.indexingDone", &request_id_value, &file_system_path_value, nullptr); } void WebContents::OnDevToolsSearchCompleted( int request_id, const std::string& file_system_path, const std::vector<std::string>& file_paths) { base::ListValue file_paths_value; for (const auto& file_path : file_paths) { file_paths_value.Append(file_path); } base::Value request_id_value(request_id); base::Value file_system_path_value(file_system_path); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.searchCompleted", &request_id_value, &file_system_path_value, &file_paths_value); } void WebContents::SetHtmlApiFullscreen(bool enter_fullscreen) { // Window is already in fullscreen mode, save the state. if (enter_fullscreen && owner_window_->IsFullscreen()) { native_fullscreen_ = true; UpdateHtmlApiFullscreen(true); return; } // Exit html fullscreen state but not window's fullscreen mode. if (!enter_fullscreen && native_fullscreen_) { UpdateHtmlApiFullscreen(false); return; } // Set fullscreen on window if allowed. auto* web_preferences = WebContentsPreferences::From(GetWebContents()); bool html_fullscreenable = web_preferences ? !web_preferences->ShouldDisableHtmlFullscreenWindowResize() : true; if (html_fullscreenable) { owner_window_->SetFullScreen(enter_fullscreen); } UpdateHtmlApiFullscreen(enter_fullscreen); native_fullscreen_ = false; } void WebContents::UpdateHtmlApiFullscreen(bool fullscreen) { if (fullscreen == is_html_fullscreen()) return; html_fullscreen_ = fullscreen; // Notify renderer of the html fullscreen change. web_contents() ->GetRenderViewHost() ->GetWidget() ->SynchronizeVisualProperties(); // The embedder WebContents is separated from the frame tree of webview, so // we must manually sync their fullscreen states. if (embedder_) embedder_->SetHtmlApiFullscreen(fullscreen); if (fullscreen) { Emit("enter-html-full-screen"); owner_window_->NotifyWindowEnterHtmlFullScreen(); } else { Emit("leave-html-full-screen"); owner_window_->NotifyWindowLeaveHtmlFullScreen(); } // Make sure all child webviews quit html fullscreen. if (!fullscreen && !IsGuest()) { auto* manager = WebViewManager::GetWebViewManager(web_contents()); manager->ForEachGuest( web_contents(), base::BindRepeating([](content::WebContents* guest) { WebContents* api_web_contents = WebContents::From(guest); api_web_contents->SetHtmlApiFullscreen(false); return false; })); } } // static v8::Local<v8::ObjectTemplate> WebContents::FillObjectTemplate( v8::Isolate* isolate, v8::Local<v8::ObjectTemplate> templ) { gin::InvokerOptions options; options.holder_is_first_argument = true; options.holder_type = "WebContents"; templ->Set( gin::StringToSymbol(isolate, "isDestroyed"), gin::CreateFunctionTemplate( isolate, base::BindRepeating(&gin_helper::Destroyable::IsDestroyed), options)); // We use gin_helper::ObjectTemplateBuilder instead of // gin::ObjectTemplateBuilder here to handle the fact that WebContents is // destroyable. return gin_helper::ObjectTemplateBuilder(isolate, templ) .SetMethod("destroy", &WebContents::Destroy) .SetMethod("getBackgroundThrottling", &WebContents::GetBackgroundThrottling) .SetMethod("setBackgroundThrottling", &WebContents::SetBackgroundThrottling) .SetMethod("getProcessId", &WebContents::GetProcessID) .SetMethod("getOSProcessId", &WebContents::GetOSProcessID) .SetMethod("equal", &WebContents::Equal) .SetMethod("_loadURL", &WebContents::LoadURL) .SetMethod("reload", &WebContents::Reload) .SetMethod("reloadIgnoringCache", &WebContents::ReloadIgnoringCache) .SetMethod("downloadURL", &WebContents::DownloadURL) .SetMethod("getURL", &WebContents::GetURL) .SetMethod("getTitle", &WebContents::GetTitle) .SetMethod("isLoading", &WebContents::IsLoading) .SetMethod("isLoadingMainFrame", &WebContents::IsLoadingMainFrame) .SetMethod("isWaitingForResponse", &WebContents::IsWaitingForResponse) .SetMethod("stop", &WebContents::Stop) .SetMethod("canGoBack", &WebContents::CanGoBack) .SetMethod("goBack", &WebContents::GoBack) .SetMethod("canGoForward", &WebContents::CanGoForward) .SetMethod("goForward", &WebContents::GoForward) .SetMethod("canGoToOffset", &WebContents::CanGoToOffset) .SetMethod("goToOffset", &WebContents::GoToOffset) .SetMethod("canGoToIndex", &WebContents::CanGoToIndex) .SetMethod("goToIndex", &WebContents::GoToIndex) .SetMethod("getActiveIndex", &WebContents::GetActiveIndex) .SetMethod("clearHistory", &WebContents::ClearHistory) .SetMethod("length", &WebContents::GetHistoryLength) .SetMethod("isCrashed", &WebContents::IsCrashed) .SetMethod("forcefullyCrashRenderer", &WebContents::ForcefullyCrashRenderer) .SetMethod("setUserAgent", &WebContents::SetUserAgent) .SetMethod("getUserAgent", &WebContents::GetUserAgent) .SetMethod("savePage", &WebContents::SavePage) .SetMethod("openDevTools", &WebContents::OpenDevTools) .SetMethod("closeDevTools", &WebContents::CloseDevTools) .SetMethod("isDevToolsOpened", &WebContents::IsDevToolsOpened) .SetMethod("isDevToolsFocused", &WebContents::IsDevToolsFocused) .SetMethod("enableDeviceEmulation", &WebContents::EnableDeviceEmulation) .SetMethod("disableDeviceEmulation", &WebContents::DisableDeviceEmulation) .SetMethod("toggleDevTools", &WebContents::ToggleDevTools) .SetMethod("inspectElement", &WebContents::InspectElement) .SetMethod("setIgnoreMenuShortcuts", &WebContents::SetIgnoreMenuShortcuts) .SetMethod("setAudioMuted", &WebContents::SetAudioMuted) .SetMethod("isAudioMuted", &WebContents::IsAudioMuted) .SetMethod("isCurrentlyAudible", &WebContents::IsCurrentlyAudible) .SetMethod("undo", &WebContents::Undo) .SetMethod("redo", &WebContents::Redo) .SetMethod("cut", &WebContents::Cut) .SetMethod("copy", &WebContents::Copy) .SetMethod("paste", &WebContents::Paste) .SetMethod("pasteAndMatchStyle", &WebContents::PasteAndMatchStyle) .SetMethod("delete", &WebContents::Delete) .SetMethod("selectAll", &WebContents::SelectAll) .SetMethod("unselect", &WebContents::Unselect) .SetMethod("replace", &WebContents::Replace) .SetMethod("replaceMisspelling", &WebContents::ReplaceMisspelling) .SetMethod("findInPage", &WebContents::FindInPage) .SetMethod("stopFindInPage", &WebContents::StopFindInPage) .SetMethod("focus", &WebContents::Focus) .SetMethod("isFocused", &WebContents::IsFocused) .SetMethod("sendInputEvent", &WebContents::SendInputEvent) .SetMethod("beginFrameSubscription", &WebContents::BeginFrameSubscription) .SetMethod("endFrameSubscription", &WebContents::EndFrameSubscription) .SetMethod("startDrag", &WebContents::StartDrag) .SetMethod("attachToIframe", &WebContents::AttachToIframe) .SetMethod("detachFromOuterFrame", &WebContents::DetachFromOuterFrame) .SetMethod("isOffscreen", &WebContents::IsOffScreen) #if BUILDFLAG(ENABLE_OSR) .SetMethod("startPainting", &WebContents::StartPainting) .SetMethod("stopPainting", &WebContents::StopPainting) .SetMethod("isPainting", &WebContents::IsPainting) .SetMethod("setFrameRate", &WebContents::SetFrameRate) .SetMethod("getFrameRate", &WebContents::GetFrameRate) #endif .SetMethod("invalidate", &WebContents::Invalidate) .SetMethod("setZoomLevel", &WebContents::SetZoomLevel) .SetMethod("getZoomLevel", &WebContents::GetZoomLevel) .SetMethod("setZoomFactor", &WebContents::SetZoomFactor) .SetMethod("getZoomFactor", &WebContents::GetZoomFactor) .SetMethod("getType", &WebContents::GetType) .SetMethod("_getPreloadPaths", &WebContents::GetPreloadPaths) .SetMethod("getLastWebPreferences", &WebContents::GetLastWebPreferences) .SetMethod("getOwnerBrowserWindow", &WebContents::GetOwnerBrowserWindow) .SetMethod("inspectServiceWorker", &WebContents::InspectServiceWorker) .SetMethod("inspectSharedWorker", &WebContents::InspectSharedWorker) .SetMethod("inspectSharedWorkerById", &WebContents::InspectSharedWorkerById) .SetMethod("getAllSharedWorkers", &WebContents::GetAllSharedWorkers) #if BUILDFLAG(ENABLE_PRINTING) .SetMethod("_print", &WebContents::Print) .SetMethod("_printToPDF", &WebContents::PrintToPDF) #endif .SetMethod("_setNextChildWebPreferences", &WebContents::SetNextChildWebPreferences) .SetMethod("addWorkSpace", &WebContents::AddWorkSpace) .SetMethod("removeWorkSpace", &WebContents::RemoveWorkSpace) .SetMethod("showDefinitionForSelection", &WebContents::ShowDefinitionForSelection) .SetMethod("copyImageAt", &WebContents::CopyImageAt) .SetMethod("capturePage", &WebContents::CapturePage) .SetMethod("setEmbedder", &WebContents::SetEmbedder) .SetMethod("setDevToolsWebContents", &WebContents::SetDevToolsWebContents) .SetMethod("getNativeView", &WebContents::GetNativeView) .SetMethod("incrementCapturerCount", &WebContents::IncrementCapturerCount) .SetMethod("decrementCapturerCount", &WebContents::DecrementCapturerCount) .SetMethod("isBeingCaptured", &WebContents::IsBeingCaptured) .SetMethod("setWebRTCIPHandlingPolicy", &WebContents::SetWebRTCIPHandlingPolicy) .SetMethod("getMediaSourceId", &WebContents::GetMediaSourceID) .SetMethod("getWebRTCIPHandlingPolicy", &WebContents::GetWebRTCIPHandlingPolicy) .SetMethod("takeHeapSnapshot", &WebContents::TakeHeapSnapshot) .SetMethod("setImageAnimationPolicy", &WebContents::SetImageAnimationPolicy) .SetMethod("_getProcessMemoryInfo", &WebContents::GetProcessMemoryInfo) .SetProperty("id", &WebContents::ID) .SetProperty("session", &WebContents::Session) .SetProperty("hostWebContents", &WebContents::HostWebContents) .SetProperty("devToolsWebContents", &WebContents::DevToolsWebContents) .SetProperty("debugger", &WebContents::Debugger) .SetProperty("mainFrame", &WebContents::MainFrame) .Build(); } const char* WebContents::GetTypeName() { return "WebContents"; } ElectronBrowserContext* WebContents::GetBrowserContext() const { return static_cast<ElectronBrowserContext*>( web_contents()->GetBrowserContext()); } // static gin::Handle<WebContents> WebContents::New( v8::Isolate* isolate, const gin_helper::Dictionary& options) { gin::Handle<WebContents> handle = gin::CreateHandle(isolate, new WebContents(isolate, options)); v8::TryCatch try_catch(isolate); gin_helper::CallMethod(isolate, handle.get(), "_init"); if (try_catch.HasCaught()) { node::errors::TriggerUncaughtException(isolate, try_catch); } return handle; } // static gin::Handle<WebContents> WebContents::CreateAndTake( v8::Isolate* isolate, std::unique_ptr<content::WebContents> web_contents, Type type) { gin::Handle<WebContents> handle = gin::CreateHandle( isolate, new WebContents(isolate, std::move(web_contents), type)); v8::TryCatch try_catch(isolate); gin_helper::CallMethod(isolate, handle.get(), "_init"); if (try_catch.HasCaught()) { node::errors::TriggerUncaughtException(isolate, try_catch); } return handle; } // static WebContents* WebContents::From(content::WebContents* web_contents) { if (!web_contents) return nullptr; auto* data = static_cast<UserDataLink*>( web_contents->GetUserData(kElectronApiWebContentsKey)); return data ? data->web_contents.get() : nullptr; } // static gin::Handle<WebContents> WebContents::FromOrCreate( v8::Isolate* isolate, content::WebContents* web_contents) { WebContents* api_web_contents = From(web_contents); if (!api_web_contents) { api_web_contents = new WebContents(isolate, web_contents); v8::TryCatch try_catch(isolate); gin_helper::CallMethod(isolate, api_web_contents, "_init"); if (try_catch.HasCaught()) { node::errors::TriggerUncaughtException(isolate, try_catch); } } return gin::CreateHandle(isolate, api_web_contents); } // static gin::Handle<WebContents> WebContents::CreateFromWebPreferences( v8::Isolate* isolate, const gin_helper::Dictionary& web_preferences) { // Check if webPreferences has |webContents| option. gin::Handle<WebContents> web_contents; if (web_preferences.GetHidden("webContents", &web_contents) && !web_contents.IsEmpty()) { // Set webPreferences from options if using an existing webContents. // These preferences will be used when the webContent launches new // render processes. auto* existing_preferences = WebContentsPreferences::From(web_contents->web_contents()); gin_helper::Dictionary web_preferences_dict; if (gin::ConvertFromV8(isolate, web_preferences.GetHandle(), &web_preferences_dict)) { existing_preferences->SetFromDictionary(web_preferences_dict); absl::optional<SkColor> color = existing_preferences->GetBackgroundColor(); web_contents->web_contents()->SetPageBaseBackgroundColor(color); // Because web preferences don't recognize transparency, // only set rwhv background color if a color exists auto* rwhv = web_contents->web_contents()->GetRenderWidgetHostView(); if (rwhv && color.has_value()) SetBackgroundColor(rwhv, color.value()); } } else { // Create one if not. web_contents = WebContents::New(isolate, web_preferences); } return web_contents; } // static WebContents* WebContents::FromID(int32_t id) { return GetAllWebContents().Lookup(id); } // static gin::WrapperInfo WebContents::kWrapperInfo = {gin::kEmbedderNativeGin}; } // namespace api } // namespace electron namespace { using electron::api::GetAllWebContents; using electron::api::WebContents; gin::Handle<WebContents> WebContentsFromID(v8::Isolate* isolate, int32_t id) { WebContents* contents = WebContents::FromID(id); return contents ? gin::CreateHandle(isolate, contents) : gin::Handle<WebContents>(); } gin::Handle<WebContents> WebContentsFromDevToolsTargetID( v8::Isolate* isolate, std::string target_id) { auto agent_host = content::DevToolsAgentHost::GetForId(target_id); WebContents* contents = agent_host ? WebContents::From(agent_host->GetWebContents()) : nullptr; return contents ? gin::CreateHandle(isolate, contents) : gin::Handle<WebContents>(); } std::vector<gin::Handle<WebContents>> GetAllWebContentsAsV8( v8::Isolate* isolate) { std::vector<gin::Handle<WebContents>> list; for (auto iter = base::IDMap<WebContents*>::iterator(&GetAllWebContents()); !iter.IsAtEnd(); iter.Advance()) { list.push_back(gin::CreateHandle(isolate, iter.GetCurrentValue())); } return list; } void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused, v8::Local<v8::Context> context, void* priv) { v8::Isolate* isolate = context->GetIsolate(); gin_helper::Dictionary dict(isolate, exports); dict.Set("WebContents", WebContents::GetConstructor(context)); dict.SetMethod("fromId", &WebContentsFromID); dict.SetMethod("fromDevToolsTargetId", &WebContentsFromDevToolsTargetID); dict.SetMethod("getAllWebContents", &GetAllWebContentsAsV8); } } // namespace NODE_LINKED_MODULE_CONTEXT_AWARE(electron_browser_web_contents, Initialize)
closed
electron/electron
https://github.com/electron/electron
33,806
[Bug]: clarify in Security document when contextIsolation should be enabled
### 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 Security [doc](https://www.electronjs.org/docs/latest/tutorial/security#3-enable-context-isolation-for-remote-content) states: >Enable Context Isolation for remote content Based on some of the discussion in [this issue](https://github.com/electron/electron/issues/23506) (specifically [here](https://github.com/electron/electron/issues/23506#issuecomment-922092517)), it sounds like Electron is recommending that we enable `contextIsolation` for *all* content, remote or local. Should the Sec doc be updated in that case? ### Proposed Solution Remove the bit about "remote content" from that section ### Alternatives Considered n/a ### Additional Information _No response_
https://github.com/electron/electron/issues/33806
https://github.com/electron/electron/pull/33807
5ae234d5e1d20bc9db5abb780d79b694a4ef09d7
2d0ad043542d99d28332127915b70084409b5786
2022-04-15T21:02:10Z
c++
2022-04-18T14:09:54Z
docs/api/context-bridge.md
# contextBridge > Create a safe, bi-directional, synchronous bridge across isolated contexts Process: [Renderer](../glossary.md#renderer-process) An example of exposing an API to a renderer from an isolated preload script is given below: ```javascript // Preload (Isolated World) const { contextBridge, ipcRenderer } = require('electron') contextBridge.exposeInMainWorld( 'electron', { doThing: () => ipcRenderer.send('do-a-thing') } ) ``` ```javascript // Renderer (Main World) window.electron.doThing() ``` ## Glossary ### Main World The "Main World" is the JavaScript context that your main renderer code runs in. By default, the page you load in your renderer executes code in this world. ### Isolated World When `contextIsolation` is enabled in your `webPreferences` (this is the default behavior since Electron 12.0.0), your `preload` scripts run in an "Isolated World". You can read more about context isolation and what it affects in the [security](../tutorial/security.md#3-enable-context-isolation-for-remote-content) docs. ## Methods The `contextBridge` module has the following methods: ### `contextBridge.exposeInMainWorld(apiKey, api)` * `apiKey` string - The key to inject the API onto `window` with. The API will be accessible on `window[apiKey]`. * `api` any - Your API, more information on what this API can be and how it works is available below. ## Usage ### API The `api` provided to [`exposeInMainWorld`](#contextbridgeexposeinmainworldapikey-api) must be a `Function`, `string`, `number`, `Array`, `boolean`, or an object whose keys are strings and values are a `Function`, `string`, `number`, `Array`, `boolean`, or another nested object that meets the same conditions. `Function` values are proxied to the other context and all other values are **copied** and **frozen**. Any data / primitives sent in the API become immutable and updates on either side of the bridge do not result in an update on the other side. An example of a complex API is shown below: ```javascript const { contextBridge } = require('electron') contextBridge.exposeInMainWorld( 'electron', { doThing: () => ipcRenderer.send('do-a-thing'), myPromises: [Promise.resolve(), Promise.reject(new Error('whoops'))], anAsyncFunction: async () => 123, data: { myFlags: ['a', 'b', 'c'], bootTime: 1234 }, nestedAPI: { evenDeeper: { youCanDoThisAsMuchAsYouWant: { fn: () => ({ returnData: 123 }) } } } } ) ``` ### API Functions `Function` values that you bind through the `contextBridge` are proxied through Electron to ensure that contexts remain isolated. This results in some key limitations that we've outlined below. #### Parameter / Error / Return Type support Because parameters, errors and return values are **copied** when they are sent over the bridge, there are only certain types that can be used. At a high level, if the type you want to use can be serialized and deserialized into the same object it will work. A table of type support has been included below for completeness: | Type | Complexity | Parameter Support | Return Value Support | Limitations | | ---- | ---------- | ----------------- | -------------------- | ----------- | | `string` | Simple | ✅ | ✅ | N/A | | `number` | Simple | ✅ | ✅ | N/A | | `boolean` | Simple | ✅ | ✅ | N/A | | `Object` | Complex | ✅ | ✅ | Keys must be supported using only "Simple" types in this table. Values must be supported in this table. Prototype modifications are dropped. Sending custom classes will copy values but not the prototype. | | `Array` | Complex | ✅ | ✅ | Same limitations as the `Object` type | | `Error` | Complex | ✅ | ✅ | Errors that are thrown are also copied, this can result in the message and stack trace of the error changing slightly due to being thrown in a different context, and any custom properties on the Error object [will be lost](https://github.com/electron/electron/issues/25596) | | `Promise` | Complex | ✅ | ✅ | N/A | `Function` | Complex | ✅ | ✅ | Prototype modifications are dropped. Sending classes or constructors will not work. | | [Cloneable Types](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm) | Simple | ✅ | ✅ | See the linked document on cloneable types | | `Element` | Complex | ✅ | ✅ | Prototype modifications are dropped. Sending custom elements will not work. | | `Blob` | Complex | ✅ | ✅ | N/A | | `Symbol` | N/A | ❌ | ❌ | Symbols cannot be copied across contexts so they are dropped | If the type you care about is not in the above table, it is probably not supported. ### Exposing Node Global Symbols The `contextBridge` can be used by the preload script to give your renderer access to Node APIs. The table of supported types described above also applies to Node APIs that you expose through `contextBridge`. Please note that many Node APIs grant access to local system resources. Be very cautious about which globals and APIs you expose to untrusted remote content. ```javascript const { contextBridge } = require('electron') const crypto = require('crypto') contextBridge.exposeInMainWorld('nodeCrypto', { sha256sum (data) { const hash = crypto.createHash('sha256') hash.update(data) return hash.digest('hex') } }) ```
closed
electron/electron
https://github.com/electron/electron
33,806
[Bug]: clarify in Security document when contextIsolation should be enabled
### 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 Security [doc](https://www.electronjs.org/docs/latest/tutorial/security#3-enable-context-isolation-for-remote-content) states: >Enable Context Isolation for remote content Based on some of the discussion in [this issue](https://github.com/electron/electron/issues/23506) (specifically [here](https://github.com/electron/electron/issues/23506#issuecomment-922092517)), it sounds like Electron is recommending that we enable `contextIsolation` for *all* content, remote or local. Should the Sec doc be updated in that case? ### Proposed Solution Remove the bit about "remote content" from that section ### Alternatives Considered n/a ### Additional Information _No response_
https://github.com/electron/electron/issues/33806
https://github.com/electron/electron/pull/33807
5ae234d5e1d20bc9db5abb780d79b694a4ef09d7
2d0ad043542d99d28332127915b70084409b5786
2022-04-15T21:02:10Z
c++
2022-04-18T14:09:54Z
docs/breaking-changes.md
# Breaking Changes Breaking changes will be documented here, and deprecation warnings added to JS code where possible, at least [one major version](tutorial/electron-versioning.md#semver) before the change is made. ### Types of Breaking Changes This document uses the following convention to categorize breaking changes: * **API Changed:** An API was changed in such a way that code that has not been updated is guaranteed to throw an exception. * **Behavior Changed:** The behavior of Electron has changed, but not in such a way that an exception will necessarily be thrown. * **Default Changed:** Code depending on the old default may break, not necessarily throwing an exception. The old behavior can be restored by explicitly specifying the value. * **Deprecated:** An API was marked as deprecated. The API will continue to function, but will emit a deprecation warning, and will be removed in a future release. * **Removed:** An API or feature was removed, and is no longer supported by Electron. ## Planned Breaking API Changes (20.0) ### Default Changed: renderers without `nodeIntegration: true` are sandboxed by default Previously, renderers that specified a preload script defaulted to being unsandboxed. This meant that by default, preload scripts had access to Node.js. In Electron 20, this default has changed. Beginning in Electron 20, renderers will be sandboxed by default, unless `nodeIntegration: true` or `sandbox: false` is specified. If your preload scripts do not depend on Node, no action is needed. If your preload scripts _do_ depend on Node, either refactor them to remove Node usage from the renderer, or explicitly specify `sandbox: false` for the relevant renderers. ### Removed: `skipTaskbar` on Linux On X11, `skipTaskbar` sends a `_NET_WM_STATE_SKIP_TASKBAR` message to the X11 window manager. There is not a direct equivalent for Wayland, and the known workarounds have unacceptable tradeoffs (e.g. Window.is_skip_taskbar in GNOME requires unsafe mode), so Electron is unable to support this feature on Linux. ## Planned Breaking API Changes (19.0) None ## Planned Breaking API Changes (18.0) ### Removed: `nativeWindowOpen` Prior to Electron 15, `window.open` was by default shimmed to use `BrowserWindowProxy`. This meant that `window.open('about:blank')` did not work to open synchronously scriptable child windows, among other incompatibilities. Since Electron 15, `nativeWindowOpen` has been enabled by default. See the documentation for [window.open in Electron](api/window-open.md) for more details. ## Planned Breaking API Changes (17.0) ### Removed: `desktopCapturer.getSources` in the renderer The `desktopCapturer.getSources` API is now only available in the main process. This has been changed in order to improve the default security of Electron apps. If you need this functionality, it can be replaced as follows: ```js // Main process const { ipcMain, desktopCapturer } = require('electron') ipcMain.handle( 'DESKTOP_CAPTURER_GET_SOURCES', (event, opts) => desktopCapturer.getSources(opts) ) ``` ```js // Renderer process const { ipcRenderer } = require('electron') const desktopCapturer = { getSources: (opts) => ipcRenderer.invoke('DESKTOP_CAPTURER_GET_SOURCES', opts) } ``` However, you should consider further restricting the information returned to the renderer; for instance, displaying a source selector to the user and only returning the selected source. ### Deprecated: `nativeWindowOpen` Prior to Electron 15, `window.open` was by default shimmed to use `BrowserWindowProxy`. This meant that `window.open('about:blank')` did not work to open synchronously scriptable child windows, among other incompatibilities. Since Electron 15, `nativeWindowOpen` has been enabled by default. See the documentation for [window.open in Electron](api/window-open.md) for more details. ## Planned Breaking API Changes (16.0) ### Behavior Changed: `crashReporter` implementation switched to Crashpad on Linux The underlying implementation of the `crashReporter` API on Linux has changed from Breakpad to Crashpad, bringing it in line with Windows and Mac. As a result of this, child processes are now automatically monitored, and calling `process.crashReporter.start` in Node child processes is no longer needed (and is not advisable, as it will start a second instance of the Crashpad reporter). There are also some subtle changes to how annotations will be reported on Linux, including that long values will no longer be split between annotations appended with `__1`, `__2` and so on, and instead will be truncated at the (new, longer) annotation value limit. ### Deprecated: `desktopCapturer.getSources` in the renderer Usage of the `desktopCapturer.getSources` API in the renderer has been deprecated and will be removed. This change improves the default security of Electron apps. See [here](#removed-desktopcapturergetsources-in-the-renderer) for details on how to replace this API in your app. ## Planned Breaking API Changes (15.0) ### Default Changed: `nativeWindowOpen` defaults to `true` Prior to Electron 15, `window.open` was by default shimmed to use `BrowserWindowProxy`. This meant that `window.open('about:blank')` did not work to open synchronously scriptable child windows, among other incompatibilities. `nativeWindowOpen` is no longer experimental, and is now the default. See the documentation for [window.open in Electron](api/window-open.md) for more details. ## Planned Breaking API Changes (14.0) ### Removed: `remote` module The `remote` module was deprecated in Electron 12, and will be removed in Electron 14. It is replaced by the [`@electron/remote`](https://github.com/electron/remote) module. ```js // Deprecated in Electron 12: const { BrowserWindow } = require('electron').remote ``` ```js // Replace with: const { BrowserWindow } = require('@electron/remote') // In the main process: require('@electron/remote/main').initialize() ``` ### Removed: `app.allowRendererProcessReuse` The `app.allowRendererProcessReuse` property will be removed as part of our plan to more closely align with Chromium's process model for security, performance and maintainability. For more detailed information see [#18397](https://github.com/electron/electron/issues/18397). ### Removed: Browser Window Affinity The `affinity` option when constructing a new `BrowserWindow` will be removed as part of our plan to more closely align with Chromium's process model for security, performance and maintainability. For more detailed information see [#18397](https://github.com/electron/electron/issues/18397). ### API Changed: `window.open()` The optional parameter `frameName` will no longer set the title of the window. This now follows the specification described by the [native documentation](https://developer.mozilla.org/en-US/docs/Web/API/Window/open#parameters) under the corresponding parameter `windowName`. If you were using this parameter to set the title of a window, you can instead use [win.setTitle(title)](api/browser-window.md#winsettitletitle). ### Removed: `worldSafeExecuteJavaScript` In Electron 14, `worldSafeExecuteJavaScript` will be removed. There is no alternative, please ensure your code works with this property enabled. It has been enabled by default since Electron 12. You will be affected by this change if you use either `webFrame.executeJavaScript` or `webFrame.executeJavaScriptInIsolatedWorld`. You will need to ensure that values returned by either of those methods are supported by the [Context Bridge API](api/context-bridge.md#parameter--error--return-type-support) as these methods use the same value passing semantics. ### Removed: BrowserWindowConstructorOptions inheriting from parent windows Prior to Electron 14, windows opened with `window.open` would inherit BrowserWindow constructor options such as `transparent` and `resizable` from their parent window. Beginning with Electron 14, this behavior is removed, and windows will not inherit any BrowserWindow constructor options from their parents. Instead, explicitly set options for the new window with `setWindowOpenHandler`: ```js webContents.setWindowOpenHandler((details) => { return { action: 'allow', overrideBrowserWindowOptions: { // ... } } }) ``` ### Removed: `additionalFeatures` The deprecated `additionalFeatures` property in the `new-window` and `did-create-window` events of WebContents has been removed. Since `new-window` uses positional arguments, the argument is still present, but will always be the empty array `[]`. (Though note, the `new-window` event itself is deprecated, and is replaced by `setWindowOpenHandler`.) Bare keys in window features will now present as keys with the value `true` in the options object. ```js // Removed in Electron 14 // Triggered by window.open('...', '', 'my-key') webContents.on('did-create-window', (window, details) => { if (details.additionalFeatures.includes('my-key')) { // ... } }) // Replace with webContents.on('did-create-window', (window, details) => { if (details.options['my-key']) { // ... } }) ``` ## Planned Breaking API Changes (13.0) ### API Changed: `session.setPermissionCheckHandler(handler)` The `handler` methods first parameter was previously always a `webContents`, it can now sometimes be `null`. You should use the `requestingOrigin`, `embeddingOrigin` and `securityOrigin` properties to respond to the permission check correctly. As the `webContents` can be `null` it can no longer be relied on. ```js // Old code session.setPermissionCheckHandler((webContents, permission) => { if (webContents.getURL().startsWith('https://google.com/') && permission === 'notification') { return true } return false }) // Replace with session.setPermissionCheckHandler((webContents, permission, requestingOrigin) => { if (new URL(requestingOrigin).hostname === 'google.com' && permission === 'notification') { return true } return false }) ``` ### Removed: `shell.moveItemToTrash()` The deprecated synchronous `shell.moveItemToTrash()` API has been removed. Use the asynchronous `shell.trashItem()` instead. ```js // Removed in Electron 13 shell.moveItemToTrash(path) // Replace with shell.trashItem(path).then(/* ... */) ``` ### Removed: `BrowserWindow` extension APIs The deprecated extension APIs have been removed: * `BrowserWindow.addExtension(path)` * `BrowserWindow.addDevToolsExtension(path)` * `BrowserWindow.removeExtension(name)` * `BrowserWindow.removeDevToolsExtension(name)` * `BrowserWindow.getExtensions()` * `BrowserWindow.getDevToolsExtensions()` Use the session APIs instead: * `ses.loadExtension(path)` * `ses.removeExtension(extension_id)` * `ses.getAllExtensions()` ```js // Removed in Electron 13 BrowserWindow.addExtension(path) BrowserWindow.addDevToolsExtension(path) // Replace with session.defaultSession.loadExtension(path) ``` ```js // Removed in Electron 13 BrowserWindow.removeExtension(name) BrowserWindow.removeDevToolsExtension(name) // Replace with session.defaultSession.removeExtension(extension_id) ``` ```js // Removed in Electron 13 BrowserWindow.getExtensions() BrowserWindow.getDevToolsExtensions() // Replace with session.defaultSession.getAllExtensions() ``` ### Removed: methods in `systemPreferences` The following `systemPreferences` methods have been deprecated: * `systemPreferences.isDarkMode()` * `systemPreferences.isInvertedColorScheme()` * `systemPreferences.isHighContrastColorScheme()` Use the following `nativeTheme` properties instead: * `nativeTheme.shouldUseDarkColors` * `nativeTheme.shouldUseInvertedColorScheme` * `nativeTheme.shouldUseHighContrastColors` ```js // Removed in Electron 13 systemPreferences.isDarkMode() // Replace with nativeTheme.shouldUseDarkColors // Removed in Electron 13 systemPreferences.isInvertedColorScheme() // Replace with nativeTheme.shouldUseInvertedColorScheme // Removed in Electron 13 systemPreferences.isHighContrastColorScheme() // Replace with nativeTheme.shouldUseHighContrastColors ``` ### Deprecated: WebContents `new-window` event The `new-window` event of WebContents has been deprecated. It is replaced by [`webContents.setWindowOpenHandler()`](api/web-contents.md#contentssetwindowopenhandlerhandler). ```js // Deprecated in Electron 13 webContents.on('new-window', (event) => { event.preventDefault() }) // Replace with webContents.setWindowOpenHandler((details) => { return { action: 'deny' } }) ``` ## Planned Breaking API Changes (12.0) ### Removed: Pepper Flash support Chromium has removed support for Flash, and so we must follow suit. See Chromium's [Flash Roadmap](https://www.chromium.org/flash-roadmap) for more details. ### Default Changed: `worldSafeExecuteJavaScript` defaults to `true` In Electron 12, `worldSafeExecuteJavaScript` will be enabled by default. To restore the previous behavior, `worldSafeExecuteJavaScript: false` must be specified in WebPreferences. Please note that setting this option to `false` is **insecure**. This option will be removed in Electron 14 so please migrate your code to support the default value. ### Default Changed: `contextIsolation` defaults to `true` In Electron 12, `contextIsolation` will be enabled by default. To restore the previous behavior, `contextIsolation: false` must be specified in WebPreferences. We [recommend having contextIsolation enabled](tutorial/security.md#3-enable-context-isolation-for-remote-content) for the security of your application. Another implication is that `require()` cannot be used in the renderer process unless `nodeIntegration` is `true` and `contextIsolation` is `false`. For more details see: https://github.com/electron/electron/issues/23506 ### Removed: `crashReporter.getCrashesDirectory()` The `crashReporter.getCrashesDirectory` method has been removed. Usage should be replaced by `app.getPath('crashDumps')`. ```js // Removed in Electron 12 crashReporter.getCrashesDirectory() // Replace with app.getPath('crashDumps') ``` ### Removed: `crashReporter` methods in the renderer process The following `crashReporter` methods are no longer available in the renderer process: * `crashReporter.start` * `crashReporter.getLastCrashReport` * `crashReporter.getUploadedReports` * `crashReporter.getUploadToServer` * `crashReporter.setUploadToServer` * `crashReporter.getCrashesDirectory` They should be called only from the main process. See [#23265](https://github.com/electron/electron/pull/23265) for more details. ### Default Changed: `crashReporter.start({ compress: true })` The default value of the `compress` option to `crashReporter.start` has changed from `false` to `true`. This means that crash dumps will be uploaded to the crash ingestion server with the `Content-Encoding: gzip` header, and the body will be compressed. If your crash ingestion server does not support compressed payloads, you can turn off compression by specifying `{ compress: false }` in the crash reporter options. ### Deprecated: `remote` module The `remote` module is deprecated in Electron 12, and will be removed in Electron 14. It is replaced by the [`@electron/remote`](https://github.com/electron/remote) module. ```js // Deprecated in Electron 12: const { BrowserWindow } = require('electron').remote ``` ```js // Replace with: const { BrowserWindow } = require('@electron/remote') // In the main process: require('@electron/remote/main').initialize() ``` ### Deprecated: `shell.moveItemToTrash()` The synchronous `shell.moveItemToTrash()` has been replaced by the new, asynchronous `shell.trashItem()`. ```js // Deprecated in Electron 12 shell.moveItemToTrash(path) // Replace with shell.trashItem(path).then(/* ... */) ``` ## Planned Breaking API Changes (11.0) ### Removed: `BrowserView.{destroy, fromId, fromWebContents, getAllViews}` and `id` property of `BrowserView` The experimental APIs `BrowserView.{destroy, fromId, fromWebContents, getAllViews}` have now been removed. Additionally, the `id` property of `BrowserView` has also been removed. For more detailed information, see [#23578](https://github.com/electron/electron/pull/23578). ## Planned Breaking API Changes (10.0) ### Deprecated: `companyName` argument to `crashReporter.start()` The `companyName` argument to `crashReporter.start()`, which was previously required, is now optional, and further, is deprecated. To get the same behavior in a non-deprecated way, you can pass a `companyName` value in `globalExtra`. ```js // Deprecated in Electron 10 crashReporter.start({ companyName: 'Umbrella Corporation' }) // Replace with crashReporter.start({ globalExtra: { _companyName: 'Umbrella Corporation' } }) ``` ### Deprecated: `crashReporter.getCrashesDirectory()` The `crashReporter.getCrashesDirectory` method has been deprecated. Usage should be replaced by `app.getPath('crashDumps')`. ```js // Deprecated in Electron 10 crashReporter.getCrashesDirectory() // Replace with app.getPath('crashDumps') ``` ### Deprecated: `crashReporter` methods in the renderer process Calling the following `crashReporter` methods from the renderer process is deprecated: * `crashReporter.start` * `crashReporter.getLastCrashReport` * `crashReporter.getUploadedReports` * `crashReporter.getUploadToServer` * `crashReporter.setUploadToServer` * `crashReporter.getCrashesDirectory` The only non-deprecated methods remaining in the `crashReporter` module in the renderer are `addExtraParameter`, `removeExtraParameter` and `getParameters`. All above methods remain non-deprecated when called from the main process. See [#23265](https://github.com/electron/electron/pull/23265) for more details. ### Deprecated: `crashReporter.start({ compress: false })` Setting `{ compress: false }` in `crashReporter.start` is deprecated. Nearly all crash ingestion servers support gzip compression. This option will be removed in a future version of Electron. ### Default Changed: `enableRemoteModule` defaults to `false` In Electron 9, using the remote module without explicitly enabling it via the `enableRemoteModule` WebPreferences option began emitting a warning. In Electron 10, the remote module is now disabled by default. To use the remote module, `enableRemoteModule: true` must be specified in WebPreferences: ```js const w = new BrowserWindow({ webPreferences: { enableRemoteModule: true } }) ``` We [recommend moving away from the remote module](https://medium.com/@nornagon/electrons-remote-module-considered-harmful-70d69500f31). ### `protocol.unregisterProtocol` ### `protocol.uninterceptProtocol` The APIs are now synchronous and the optional callback is no longer needed. ```javascript // Deprecated protocol.unregisterProtocol(scheme, () => { /* ... */ }) // Replace with protocol.unregisterProtocol(scheme) ``` ### `protocol.registerFileProtocol` ### `protocol.registerBufferProtocol` ### `protocol.registerStringProtocol` ### `protocol.registerHttpProtocol` ### `protocol.registerStreamProtocol` ### `protocol.interceptFileProtocol` ### `protocol.interceptStringProtocol` ### `protocol.interceptBufferProtocol` ### `protocol.interceptHttpProtocol` ### `protocol.interceptStreamProtocol` The APIs are now synchronous and the optional callback is no longer needed. ```javascript // Deprecated protocol.registerFileProtocol(scheme, handler, () => { /* ... */ }) // Replace with protocol.registerFileProtocol(scheme, handler) ``` The registered or intercepted protocol does not have effect on current page until navigation happens. ### `protocol.isProtocolHandled` This API is deprecated and users should use `protocol.isProtocolRegistered` and `protocol.isProtocolIntercepted` instead. ```javascript // Deprecated protocol.isProtocolHandled(scheme).then(() => { /* ... */ }) // Replace with const isRegistered = protocol.isProtocolRegistered(scheme) const isIntercepted = protocol.isProtocolIntercepted(scheme) ``` ## Planned Breaking API Changes (9.0) ### Default Changed: Loading non-context-aware native modules in the renderer process is disabled by default As of Electron 9 we do not allow loading of non-context-aware native modules in the renderer process. This is to improve security, performance and maintainability of Electron as a project. If this impacts you, you can temporarily set `app.allowRendererProcessReuse` to `false` to revert to the old behavior. This flag will only be an option until Electron 11 so you should plan to update your native modules to be context aware. For more detailed information see [#18397](https://github.com/electron/electron/issues/18397). ### Deprecated: `BrowserWindow` extension APIs The following extension APIs have been deprecated: * `BrowserWindow.addExtension(path)` * `BrowserWindow.addDevToolsExtension(path)` * `BrowserWindow.removeExtension(name)` * `BrowserWindow.removeDevToolsExtension(name)` * `BrowserWindow.getExtensions()` * `BrowserWindow.getDevToolsExtensions()` Use the session APIs instead: * `ses.loadExtension(path)` * `ses.removeExtension(extension_id)` * `ses.getAllExtensions()` ```js // Deprecated in Electron 9 BrowserWindow.addExtension(path) BrowserWindow.addDevToolsExtension(path) // Replace with session.defaultSession.loadExtension(path) ``` ```js // Deprecated in Electron 9 BrowserWindow.removeExtension(name) BrowserWindow.removeDevToolsExtension(name) // Replace with session.defaultSession.removeExtension(extension_id) ``` ```js // Deprecated in Electron 9 BrowserWindow.getExtensions() BrowserWindow.getDevToolsExtensions() // Replace with session.defaultSession.getAllExtensions() ``` ### Removed: `<webview>.getWebContents()` This API, which was deprecated in Electron 8.0, is now removed. ```js // Removed in Electron 9.0 webview.getWebContents() // Replace with const { remote } = require('electron') remote.webContents.fromId(webview.getWebContentsId()) ``` ### Removed: `webFrame.setLayoutZoomLevelLimits()` Chromium has removed support for changing the layout zoom level limits, and it is beyond Electron's capacity to maintain it. The function was deprecated in Electron 8.x, and has been removed in Electron 9.x. The layout zoom level limits are now fixed at a minimum of 0.25 and a maximum of 5.0, as defined [here](https://chromium.googlesource.com/chromium/src/+/938b37a6d2886bf8335fc7db792f1eb46c65b2ae/third_party/blink/common/page/page_zoom.cc#11). ### Behavior Changed: Sending non-JS objects over IPC now throws an exception In Electron 8.0, IPC was changed to use the Structured Clone Algorithm, bringing significant performance improvements. To help ease the transition, the old IPC serialization algorithm was kept and used for some objects that aren't serializable with Structured Clone. In particular, DOM objects (e.g. `Element`, `Location` and `DOMMatrix`), Node.js objects backed by C++ classes (e.g. `process.env`, some members of `Stream`), and Electron objects backed by C++ classes (e.g. `WebContents`, `BrowserWindow` and `WebFrame`) are not serializable with Structured Clone. Whenever the old algorithm was invoked, a deprecation warning was printed. In Electron 9.0, the old serialization algorithm has been removed, and sending such non-serializable objects will now throw an "object could not be cloned" error. ### API Changed: `shell.openItem` is now `shell.openPath` The `shell.openItem` API has been replaced with an asynchronous `shell.openPath` API. You can see the original API proposal and reasoning [here](https://github.com/electron/governance/blob/main/wg-api/spec-documents/shell-openitem.md). ## Planned Breaking API Changes (8.0) ### Behavior Changed: Values sent over IPC are now serialized with Structured Clone Algorithm The algorithm used to serialize objects sent over IPC (through `ipcRenderer.send`, `ipcRenderer.sendSync`, `WebContents.send` and related methods) has been switched from a custom algorithm to V8's built-in [Structured Clone Algorithm][SCA], the same algorithm used to serialize messages for `postMessage`. This brings about a 2x performance improvement for large messages, but also brings some breaking changes in behavior. * Sending Functions, Promises, WeakMaps, WeakSets, or objects containing any such values, over IPC will now throw an exception, instead of silently converting the functions to `undefined`. ```js // Previously: ipcRenderer.send('channel', { value: 3, someFunction: () => {} }) // => results in { value: 3 } arriving in the main process // From Electron 8: ipcRenderer.send('channel', { value: 3, someFunction: () => {} }) // => throws Error("() => {} could not be cloned.") ``` * `NaN`, `Infinity` and `-Infinity` will now be correctly serialized, instead of being converted to `null`. * Objects containing cyclic references will now be correctly serialized, instead of being converted to `null`. * `Set`, `Map`, `Error` and `RegExp` values will be correctly serialized, instead of being converted to `{}`. * `BigInt` values will be correctly serialized, instead of being converted to `null`. * Sparse arrays will be serialized as such, instead of being converted to dense arrays with `null`s. * `Date` objects will be transferred as `Date` objects, instead of being converted to their ISO string representation. * Typed Arrays (such as `Uint8Array`, `Uint16Array`, `Uint32Array` and so on) will be transferred as such, instead of being converted to Node.js `Buffer`. * Node.js `Buffer` objects will be transferred as `Uint8Array`s. You can convert a `Uint8Array` back to a Node.js `Buffer` by wrapping the underlying `ArrayBuffer`: ```js Buffer.from(value.buffer, value.byteOffset, value.byteLength) ``` Sending any objects that aren't native JS types, such as DOM objects (e.g. `Element`, `Location`, `DOMMatrix`), Node.js objects (e.g. `process.env`, `Stream`), or Electron objects (e.g. `WebContents`, `BrowserWindow`, `WebFrame`) is deprecated. In Electron 8, these objects will be serialized as before with a DeprecationWarning message, but starting in Electron 9, sending these kinds of objects will throw a 'could not be cloned' error. [SCA]: https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm ### Deprecated: `<webview>.getWebContents()` This API is implemented using the `remote` module, which has both performance and security implications. Therefore its usage should be explicit. ```js // Deprecated webview.getWebContents() // Replace with const { remote } = require('electron') remote.webContents.fromId(webview.getWebContentsId()) ``` However, it is recommended to avoid using the `remote` module altogether. ```js // main const { ipcMain, webContents } = require('electron') const getGuestForWebContents = (webContentsId, contents) => { const guest = webContents.fromId(webContentsId) if (!guest) { throw new Error(`Invalid webContentsId: ${webContentsId}`) } if (guest.hostWebContents !== contents) { throw new Error('Access denied to webContents') } return guest } ipcMain.handle('openDevTools', (event, webContentsId) => { const guest = getGuestForWebContents(webContentsId, event.sender) guest.openDevTools() }) // renderer const { ipcRenderer } = require('electron') ipcRenderer.invoke('openDevTools', webview.getWebContentsId()) ``` ### Deprecated: `webFrame.setLayoutZoomLevelLimits()` Chromium has removed support for changing the layout zoom level limits, and it is beyond Electron's capacity to maintain it. The function will emit a warning in Electron 8.x, and cease to exist in Electron 9.x. The layout zoom level limits are now fixed at a minimum of 0.25 and a maximum of 5.0, as defined [here](https://chromium.googlesource.com/chromium/src/+/938b37a6d2886bf8335fc7db792f1eb46c65b2ae/third_party/blink/common/page/page_zoom.cc#11). ### Deprecated events in `systemPreferences` The following `systemPreferences` events have been deprecated: * `inverted-color-scheme-changed` * `high-contrast-color-scheme-changed` Use the new `updated` event on the `nativeTheme` module instead. ```js // Deprecated systemPreferences.on('inverted-color-scheme-changed', () => { /* ... */ }) systemPreferences.on('high-contrast-color-scheme-changed', () => { /* ... */ }) // Replace with nativeTheme.on('updated', () => { /* ... */ }) ``` ### Deprecated: methods in `systemPreferences` The following `systemPreferences` methods have been deprecated: * `systemPreferences.isDarkMode()` * `systemPreferences.isInvertedColorScheme()` * `systemPreferences.isHighContrastColorScheme()` Use the following `nativeTheme` properties instead: * `nativeTheme.shouldUseDarkColors` * `nativeTheme.shouldUseInvertedColorScheme` * `nativeTheme.shouldUseHighContrastColors` ```js // Deprecated systemPreferences.isDarkMode() // Replace with nativeTheme.shouldUseDarkColors // Deprecated systemPreferences.isInvertedColorScheme() // Replace with nativeTheme.shouldUseInvertedColorScheme // Deprecated systemPreferences.isHighContrastColorScheme() // Replace with nativeTheme.shouldUseHighContrastColors ``` ## Planned Breaking API Changes (7.0) ### Deprecated: Atom.io Node Headers URL This is the URL specified as `disturl` in a `.npmrc` file or as the `--dist-url` command line flag when building native Node modules. Both will be supported for the foreseeable future but it is recommended that you switch. Deprecated: https://atom.io/download/electron Replace with: https://electronjs.org/headers ### API Changed: `session.clearAuthCache()` no longer accepts options The `session.clearAuthCache` API no longer accepts options for what to clear, and instead unconditionally clears the whole cache. ```js // Deprecated session.clearAuthCache({ type: 'password' }) // Replace with session.clearAuthCache() ``` ### API Changed: `powerMonitor.querySystemIdleState` is now `powerMonitor.getSystemIdleState` ```js // Removed in Electron 7.0 powerMonitor.querySystemIdleState(threshold, callback) // Replace with synchronous API const idleState = powerMonitor.getSystemIdleState(threshold) ``` ### API Changed: `powerMonitor.querySystemIdleTime` is now `powerMonitor.getSystemIdleTime` ```js // Removed in Electron 7.0 powerMonitor.querySystemIdleTime(callback) // Replace with synchronous API const idleTime = powerMonitor.getSystemIdleTime() ``` ### API Changed: `webFrame.setIsolatedWorldInfo` replaces separate methods ```js // Removed in Electron 7.0 webFrame.setIsolatedWorldContentSecurityPolicy(worldId, csp) webFrame.setIsolatedWorldHumanReadableName(worldId, name) webFrame.setIsolatedWorldSecurityOrigin(worldId, securityOrigin) // Replace with webFrame.setIsolatedWorldInfo( worldId, { securityOrigin: 'some_origin', name: 'human_readable_name', csp: 'content_security_policy' }) ``` ### Removed: `marked` property on `getBlinkMemoryInfo` This property was removed in Chromium 77, and as such is no longer available. ### Behavior Changed: `webkitdirectory` attribute for `<input type="file"/>` now lists directory contents The `webkitdirectory` property on HTML file inputs allows them to select folders. Previous versions of Electron had an incorrect implementation where the `event.target.files` of the input returned a `FileList` that returned one `File` corresponding to the selected folder. As of Electron 7, that `FileList` is now list of all files contained within the folder, similarly to Chrome, Firefox, and Edge ([link to MDN docs](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/webkitdirectory)). As an illustration, take a folder with this structure: ```console folder ├── file1 ├── file2 └── file3 ``` In Electron <=6, this would return a `FileList` with a `File` object for: ```console path/to/folder ``` In Electron 7, this now returns a `FileList` with a `File` object for: ```console /path/to/folder/file3 /path/to/folder/file2 /path/to/folder/file1 ``` Note that `webkitdirectory` no longer exposes the path to the selected folder. If you require the path to the selected folder rather than the folder contents, see the `dialog.showOpenDialog` API ([link](api/dialog.md#dialogshowopendialogbrowserwindow-options)). ### API Changed: Callback-based versions of promisified APIs Electron 5 and Electron 6 introduced Promise-based versions of existing asynchronous APIs and deprecated their older, callback-based counterparts. In Electron 7, all deprecated callback-based APIs are now removed. These functions now only return Promises: * `app.getFileIcon()` [#15742](https://github.com/electron/electron/pull/15742) * `app.dock.show()` [#16904](https://github.com/electron/electron/pull/16904) * `contentTracing.getCategories()` [#16583](https://github.com/electron/electron/pull/16583) * `contentTracing.getTraceBufferUsage()` [#16600](https://github.com/electron/electron/pull/16600) * `contentTracing.startRecording()` [#16584](https://github.com/electron/electron/pull/16584) * `contentTracing.stopRecording()` [#16584](https://github.com/electron/electron/pull/16584) * `contents.executeJavaScript()` [#17312](https://github.com/electron/electron/pull/17312) * `cookies.flushStore()` [#16464](https://github.com/electron/electron/pull/16464) * `cookies.get()` [#16464](https://github.com/electron/electron/pull/16464) * `cookies.remove()` [#16464](https://github.com/electron/electron/pull/16464) * `cookies.set()` [#16464](https://github.com/electron/electron/pull/16464) * `debugger.sendCommand()` [#16861](https://github.com/electron/electron/pull/16861) * `dialog.showCertificateTrustDialog()` [#17181](https://github.com/electron/electron/pull/17181) * `inAppPurchase.getProducts()` [#17355](https://github.com/electron/electron/pull/17355) * `inAppPurchase.purchaseProduct()`[#17355](https://github.com/electron/electron/pull/17355) * `netLog.stopLogging()` [#16862](https://github.com/electron/electron/pull/16862) * `session.clearAuthCache()` [#17259](https://github.com/electron/electron/pull/17259) * `session.clearCache()` [#17185](https://github.com/electron/electron/pull/17185) * `session.clearHostResolverCache()` [#17229](https://github.com/electron/electron/pull/17229) * `session.clearStorageData()` [#17249](https://github.com/electron/electron/pull/17249) * `session.getBlobData()` [#17303](https://github.com/electron/electron/pull/17303) * `session.getCacheSize()` [#17185](https://github.com/electron/electron/pull/17185) * `session.resolveProxy()` [#17222](https://github.com/electron/electron/pull/17222) * `session.setProxy()` [#17222](https://github.com/electron/electron/pull/17222) * `shell.openExternal()` [#16176](https://github.com/electron/electron/pull/16176) * `webContents.loadFile()` [#15855](https://github.com/electron/electron/pull/15855) * `webContents.loadURL()` [#15855](https://github.com/electron/electron/pull/15855) * `webContents.hasServiceWorker()` [#16535](https://github.com/electron/electron/pull/16535) * `webContents.printToPDF()` [#16795](https://github.com/electron/electron/pull/16795) * `webContents.savePage()` [#16742](https://github.com/electron/electron/pull/16742) * `webFrame.executeJavaScript()` [#17312](https://github.com/electron/electron/pull/17312) * `webFrame.executeJavaScriptInIsolatedWorld()` [#17312](https://github.com/electron/electron/pull/17312) * `webviewTag.executeJavaScript()` [#17312](https://github.com/electron/electron/pull/17312) * `win.capturePage()` [#15743](https://github.com/electron/electron/pull/15743) These functions now have two forms, synchronous and Promise-based asynchronous: * `dialog.showMessageBox()`/`dialog.showMessageBoxSync()` [#17298](https://github.com/electron/electron/pull/17298) * `dialog.showOpenDialog()`/`dialog.showOpenDialogSync()` [#16973](https://github.com/electron/electron/pull/16973) * `dialog.showSaveDialog()`/`dialog.showSaveDialogSync()` [#17054](https://github.com/electron/electron/pull/17054) ## Planned Breaking API Changes (6.0) ### API Changed: `win.setMenu(null)` is now `win.removeMenu()` ```js // Deprecated win.setMenu(null) // Replace with win.removeMenu() ``` ### API Changed: `electron.screen` in the renderer process should be accessed via `remote` ```js // Deprecated require('electron').screen // Replace with require('electron').remote.screen ``` ### API Changed: `require()`ing node builtins in sandboxed renderers no longer implicitly loads the `remote` version ```js // Deprecated require('child_process') // Replace with require('electron').remote.require('child_process') // Deprecated require('fs') // Replace with require('electron').remote.require('fs') // Deprecated require('os') // Replace with require('electron').remote.require('os') // Deprecated require('path') // Replace with require('electron').remote.require('path') ``` ### Deprecated: `powerMonitor.querySystemIdleState` replaced with `powerMonitor.getSystemIdleState` ```js // Deprecated powerMonitor.querySystemIdleState(threshold, callback) // Replace with synchronous API const idleState = powerMonitor.getSystemIdleState(threshold) ``` ### Deprecated: `powerMonitor.querySystemIdleTime` replaced with `powerMonitor.getSystemIdleTime` ```js // Deprecated powerMonitor.querySystemIdleTime(callback) // Replace with synchronous API const idleTime = powerMonitor.getSystemIdleTime() ``` ### Deprecated: `app.enableMixedSandbox()` is no longer needed ```js // Deprecated app.enableMixedSandbox() ``` Mixed-sandbox mode is now enabled by default. ### Deprecated: `Tray.setHighlightMode` Under macOS Catalina our former Tray implementation breaks. Apple's native substitute doesn't support changing the highlighting behavior. ```js // Deprecated tray.setHighlightMode(mode) // API will be removed in v7.0 without replacement. ``` ## Planned Breaking API Changes (5.0) ### Default Changed: `nodeIntegration` and `webviewTag` default to false, `contextIsolation` defaults to true The following `webPreferences` option default values are deprecated in favor of the new defaults listed below. | Property | Deprecated Default | New Default | |----------|--------------------|-------------| | `contextIsolation` | `false` | `true` | | `nodeIntegration` | `true` | `false` | | `webviewTag` | `nodeIntegration` if set else `true` | `false` | E.g. Re-enabling the webviewTag ```js const w = new BrowserWindow({ webPreferences: { webviewTag: true } }) ``` ### Behavior Changed: `nodeIntegration` in child windows opened via `nativeWindowOpen` Child windows opened with the `nativeWindowOpen` option will always have Node.js integration disabled, unless `nodeIntegrationInSubFrames` is `true`. ### API Changed: Registering privileged schemes must now be done before app ready Renderer process APIs `webFrame.registerURLSchemeAsPrivileged` and `webFrame.registerURLSchemeAsBypassingCSP` as well as browser process API `protocol.registerStandardSchemes` have been removed. A new API, `protocol.registerSchemesAsPrivileged` has been added and should be used for registering custom schemes with the required privileges. Custom schemes are required to be registered before app ready. ### Deprecated: `webFrame.setIsolatedWorld*` replaced with `webFrame.setIsolatedWorldInfo` ```js // Deprecated webFrame.setIsolatedWorldContentSecurityPolicy(worldId, csp) webFrame.setIsolatedWorldHumanReadableName(worldId, name) webFrame.setIsolatedWorldSecurityOrigin(worldId, securityOrigin) // Replace with webFrame.setIsolatedWorldInfo( worldId, { securityOrigin: 'some_origin', name: 'human_readable_name', csp: 'content_security_policy' }) ``` ### API Changed: `webFrame.setSpellCheckProvider` now takes an asynchronous callback The `spellCheck` callback is now asynchronous, and `autoCorrectWord` parameter has been removed. ```js // Deprecated webFrame.setSpellCheckProvider('en-US', true, { spellCheck: (text) => { return !spellchecker.isMisspelled(text) } }) // Replace with webFrame.setSpellCheckProvider('en-US', { spellCheck: (words, callback) => { callback(words.filter(text => spellchecker.isMisspelled(text))) } }) ``` ### API Changed: `webContents.getZoomLevel` and `webContents.getZoomFactor` are now synchronous `webContents.getZoomLevel` and `webContents.getZoomFactor` no longer take callback parameters, instead directly returning their number values. ```js // Deprecated webContents.getZoomLevel((level) => { console.log(level) }) // Replace with const level = webContents.getZoomLevel() console.log(level) ``` ```js // Deprecated webContents.getZoomFactor((factor) => { console.log(factor) }) // Replace with const factor = webContents.getZoomFactor() console.log(factor) ``` ## Planned Breaking API Changes (4.0) The following list includes the breaking API changes made in Electron 4.0. ### `app.makeSingleInstance` ```js // Deprecated app.makeSingleInstance((argv, cwd) => { /* ... */ }) // Replace with app.requestSingleInstanceLock() app.on('second-instance', (event, argv, cwd) => { /* ... */ }) ``` ### `app.releaseSingleInstance` ```js // Deprecated app.releaseSingleInstance() // Replace with app.releaseSingleInstanceLock() ``` ### `app.getGPUInfo` ```js app.getGPUInfo('complete') // Now behaves the same with `basic` on macOS app.getGPUInfo('basic') ``` ### `win_delay_load_hook` When building native modules for windows, the `win_delay_load_hook` variable in the module's `binding.gyp` must be true (which is the default). If this hook is not present, then the native module will fail to load on Windows, with an error message like `Cannot find module`. See the [native module guide](/docs/tutorial/using-native-node-modules.md) for more. ## Breaking API Changes (3.0) The following list includes the breaking API changes in Electron 3.0. ### `app` ```js // Deprecated app.getAppMemoryInfo() // Replace with app.getAppMetrics() // Deprecated const metrics = app.getAppMetrics() const { memory } = metrics[0] // Deprecated property ``` ### `BrowserWindow` ```js // Deprecated const optionsA = { webPreferences: { blinkFeatures: '' } } const windowA = new BrowserWindow(optionsA) // Replace with const optionsB = { webPreferences: { enableBlinkFeatures: '' } } const windowB = new BrowserWindow(optionsB) // Deprecated window.on('app-command', (e, cmd) => { if (cmd === 'media-play_pause') { // do something } }) // Replace with window.on('app-command', (e, cmd) => { if (cmd === 'media-play-pause') { // do something } }) ``` ### `clipboard` ```js // Deprecated clipboard.readRtf() // Replace with clipboard.readRTF() // Deprecated clipboard.writeRtf() // Replace with clipboard.writeRTF() // Deprecated clipboard.readHtml() // Replace with clipboard.readHTML() // Deprecated clipboard.writeHtml() // Replace with clipboard.writeHTML() ``` ### `crashReporter` ```js // Deprecated crashReporter.start({ companyName: 'Crashly', submitURL: 'https://crash.server.com', autoSubmit: true }) // Replace with crashReporter.start({ companyName: 'Crashly', submitURL: 'https://crash.server.com', uploadToServer: true }) ``` ### `nativeImage` ```js // Deprecated nativeImage.createFromBuffer(buffer, 1.0) // Replace with nativeImage.createFromBuffer(buffer, { scaleFactor: 1.0 }) ``` ### `process` ```js // Deprecated const info = process.getProcessMemoryInfo() ``` ### `screen` ```js // Deprecated screen.getMenuBarHeight() // Replace with screen.getPrimaryDisplay().workArea ``` ### `session` ```js // Deprecated ses.setCertificateVerifyProc((hostname, certificate, callback) => { callback(true) }) // Replace with ses.setCertificateVerifyProc((request, callback) => { callback(0) }) ``` ### `Tray` ```js // Deprecated tray.setHighlightMode(true) // Replace with tray.setHighlightMode('on') // Deprecated tray.setHighlightMode(false) // Replace with tray.setHighlightMode('off') ``` ### `webContents` ```js // Deprecated webContents.openDevTools({ detach: true }) // Replace with webContents.openDevTools({ mode: 'detach' }) // Removed webContents.setSize(options) // There is no replacement for this API ``` ### `webFrame` ```js // Deprecated webFrame.registerURLSchemeAsSecure('app') // Replace with protocol.registerStandardSchemes(['app'], { secure: true }) // Deprecated webFrame.registerURLSchemeAsPrivileged('app', { secure: true }) // Replace with protocol.registerStandardSchemes(['app'], { secure: true }) ``` ### `<webview>` ```js // Removed webview.setAttribute('disableguestresize', '') // There is no replacement for this API // Removed webview.setAttribute('guestinstance', instanceId) // There is no replacement for this API // Keyboard listeners no longer work on webview tag webview.onkeydown = () => { /* handler */ } webview.onkeyup = () => { /* handler */ } ``` ### Node Headers URL This is the URL specified as `disturl` in a `.npmrc` file or as the `--dist-url` command line flag when building native Node modules. Deprecated: https://atom.io/download/atom-shell Replace with: https://atom.io/download/electron ## Breaking API Changes (2.0) The following list includes the breaking API changes made in Electron 2.0. ### `BrowserWindow` ```js // Deprecated const optionsA = { titleBarStyle: 'hidden-inset' } const windowA = new BrowserWindow(optionsA) // Replace with const optionsB = { titleBarStyle: 'hiddenInset' } const windowB = new BrowserWindow(optionsB) ``` ### `menu` ```js // Removed menu.popup(browserWindow, 100, 200, 2) // Replaced with menu.popup(browserWindow, { x: 100, y: 200, positioningItem: 2 }) ``` ### `nativeImage` ```js // Removed nativeImage.toPng() // Replaced with nativeImage.toPNG() // Removed nativeImage.toJpeg() // Replaced with nativeImage.toJPEG() ``` ### `process` * `process.versions.electron` and `process.version.chrome` will be made read-only properties for consistency with the other `process.versions` properties set by Node. ### `webContents` ```js // Removed webContents.setZoomLevelLimits(1, 2) // Replaced with webContents.setVisualZoomLevelLimits(1, 2) ``` ### `webFrame` ```js // Removed webFrame.setZoomLevelLimits(1, 2) // Replaced with webFrame.setVisualZoomLevelLimits(1, 2) ``` ### `<webview>` ```js // Removed webview.setZoomLevelLimits(1, 2) // Replaced with webview.setVisualZoomLevelLimits(1, 2) ``` ### Duplicate ARM Assets Each Electron release includes two identical ARM builds with slightly different filenames, like `electron-v1.7.3-linux-arm.zip` and `electron-v1.7.3-linux-armv7l.zip`. The asset with the `v7l` prefix was added to clarify to users which ARM version it supports, and to disambiguate it from future armv6l and arm64 assets that may be produced. The file _without the prefix_ is still being published to avoid breaking any setups that may be consuming it. Starting at 2.0, the unprefixed file will no longer be published. For details, see [6986](https://github.com/electron/electron/pull/6986) and [7189](https://github.com/electron/electron/pull/7189).
closed
electron/electron
https://github.com/electron/electron
33,806
[Bug]: clarify in Security document when contextIsolation should be enabled
### 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 Security [doc](https://www.electronjs.org/docs/latest/tutorial/security#3-enable-context-isolation-for-remote-content) states: >Enable Context Isolation for remote content Based on some of the discussion in [this issue](https://github.com/electron/electron/issues/23506) (specifically [here](https://github.com/electron/electron/issues/23506#issuecomment-922092517)), it sounds like Electron is recommending that we enable `contextIsolation` for *all* content, remote or local. Should the Sec doc be updated in that case? ### Proposed Solution Remove the bit about "remote content" from that section ### Alternatives Considered n/a ### Additional Information _No response_
https://github.com/electron/electron/issues/33806
https://github.com/electron/electron/pull/33807
5ae234d5e1d20bc9db5abb780d79b694a4ef09d7
2d0ad043542d99d28332127915b70084409b5786
2022-04-15T21:02:10Z
c++
2022-04-18T14:09:54Z
docs/tutorial/security.md
--- title: Security description: A set of guidelines for building secure Electron apps slug: security hide_title: true toc_max_heading_level: 3 --- # Security :::info Reporting security issues For information on how to properly disclose an Electron vulnerability, see [SECURITY.md](https://github.com/electron/electron/tree/main/SECURITY.md). For upstream Chromium vulnerabilities: Electron keeps up to date with alternating Chromium releases. For more information, see the [Electron Release Timelines](../tutorial/electron-timelines.md) document. ::: ## Preface As web developers, we usually enjoy the strong security net of the browser — the risks associated with the code we write are relatively small. Our websites are granted limited powers in a sandbox, and we trust that our users enjoy a browser built by a large team of engineers that is able to quickly respond to newly discovered security threats. When working with Electron, it is important to understand that Electron is not a web browser. It allows you to build feature-rich desktop applications with familiar web technologies, but your code wields much greater power. JavaScript can access the filesystem, user shell, and more. This allows you to build high quality native applications, but the inherent security risks scale with the additional powers granted to your code. With that in mind, be aware that displaying arbitrary content from untrusted sources poses a severe security risk that Electron is not intended to handle. In fact, the most popular Electron apps (Atom, Slack, Visual Studio Code, etc) display primarily local content (or trusted, secure remote content without Node integration) — if your application executes code from an online source, it is your responsibility to ensure that the code is not malicious. ## General guidelines ### Security is everyone's responsibility It is important to remember that the security of your Electron application is the result of the overall security of the framework foundation (*Chromium*, *Node.js*), Electron itself, all NPM dependencies and your code. As such, it is your responsibility to follow a few important best practices: * **Keep your application up-to-date with the latest Electron framework release.** When releasing your product, you’re also shipping a bundle composed of Electron, Chromium shared library and Node.js. Vulnerabilities affecting these components may impact the security of your application. By updating Electron to the latest version, you ensure that critical vulnerabilities (such as *nodeIntegration bypasses*) are already patched and cannot be exploited in your application. For more information, see "[Use a current version of Electron](#16-use-a-current-version-of-electron)". * **Evaluate your dependencies.** While NPM provides half a million reusable packages, it is your responsibility to choose trusted 3rd-party libraries. If you use outdated libraries affected by known vulnerabilities or rely on poorly maintained code, your application security could be in jeopardy. * **Adopt secure coding practices.** The first line of defense for your application is your own code. Common web vulnerabilities, such as Cross-Site Scripting (XSS), have a higher security impact on Electron applications hence it is highly recommended to adopt secure software development best practices and perform security testing. ### Isolation for untrusted content A security issue exists whenever you receive code from an untrusted source (e.g. a remote server) and execute it locally. As an example, consider a remote website being displayed inside a default [`BrowserWindow`][browser-window]. If an attacker somehow manages to change said content (either by attacking the source directly, or by sitting between your app and the actual destination), they will be able to execute native code on the user's machine. :::warning Under no circumstances should you load and execute remote code with Node.js integration enabled. Instead, use only local files (packaged together with your application) to execute Node.js code. To display remote content, use the [`<webview>`][webview-tag] tag or [`BrowserView`][browser-view], make sure to disable the `nodeIntegration` and enable `contextIsolation`. ::: :::info Electron security warnings Security warnings and recommendations are printed to the developer console. They only show up when the binary's name is Electron, indicating that a developer is currently looking at the console. You can force-enable or force-disable these warnings by setting `ELECTRON_ENABLE_SECURITY_WARNINGS` or `ELECTRON_DISABLE_SECURITY_WARNINGS` on either `process.env` or the `window` object. ::: ## Checklist: Security recommendations You should at least follow these steps to improve the security of your application: 1. [Only load secure content](#1-only-load-secure-content) 2. [Disable the Node.js integration in all renderers that display remote content](#2-do-not-enable-nodejs-integration-for-remote-content) 3. [Enable context isolation in all renderers that display remote content](#3-enable-context-isolation-for-remote-content) 4. [Enable process sandboxing](#4-enable-process-sandboxing) 5. [Use `ses.setPermissionRequestHandler()` in all sessions that load remote content](#5-handle-session-permission-requests-from-remote-content) 6. [Do not disable `webSecurity`](#6-do-not-disable-websecurity) 7. [Define a `Content-Security-Policy`](#7-define-a-content-security-policy) and use restrictive rules (i.e. `script-src 'self'`) 8. [Do not enable `allowRunningInsecureContent`](#8-do-not-enable-allowrunninginsecurecontent) 9. [Do not enable experimental features](#9-do-not-enable-experimental-features) 10. [Do not use `enableBlinkFeatures`](#10-do-not-use-enableblinkfeatures) 11. [`<webview>`: Do not use `allowpopups`](#11-do-not-use-allowpopups-for-webviews) 12. [`<webview>`: Verify options and params](#12-verify-webview-options-before-creation) 13. [Disable or limit navigation](#13-disable-or-limit-navigation) 14. [Disable or limit creation of new windows](#14-disable-or-limit-creation-of-new-windows) 15. [Do not use `shell.openExternal` with untrusted content](#15-do-not-use-shellopenexternal-with-untrusted-content) 16. [Use a current version of Electron](#16-use-a-current-version-of-electron) To automate the detection of misconfigurations and insecure patterns, it is possible to use [Electronegativity](https://github.com/doyensec/electronegativity). For additional details on potential weaknesses and implementation bugs when developing applications using Electron, please refer to this [guide for developers and auditors](https://doyensec.com/resources/us-17-Carettoni-Electronegativity-A-Study-Of-Electron-Security-wp.pdf). ### 1. Only load secure content Any resources not included with your application should be loaded using a secure protocol like `HTTPS`. In other words, do not use insecure protocols like `HTTP`. Similarly, we recommend the use of `WSS` over `WS`, `FTPS` over `FTP`, and so on. #### Why? `HTTPS` has three main benefits: 1. It authenticates the remote server, ensuring your app connects to the correct host instead of an impersonator. 1. It ensures data integrity, asserting that the data was not modified while in transit between your application and the host. 1. It encrypts the traffic between your user and the destination host, making it more difficult to eavesdrop on the information sent between your app and the host. #### How? ```js title='main.js (Main Process)' // Bad browserWindow.loadURL('http://example.com') // Good browserWindow.loadURL('https://example.com') ``` ```html title='index.html (Renderer Process)' <!-- Bad --> <script crossorigin src="http://example.com/react.js"></script> <link rel="stylesheet" href="http://example.com/style.css"> <!-- Good --> <script crossorigin src="https://example.com/react.js"></script> <link rel="stylesheet" href="https://example.com/style.css"> ``` ### 2. Do not enable Node.js integration for remote content :::info This recommendation is the default behavior in Electron since 5.0.0. ::: It is paramount that you do not enable Node.js integration in any renderer ([`BrowserWindow`][browser-window], [`BrowserView`][browser-view], or [`<webview>`][webview-tag]) that loads remote content. The goal is to limit the powers you grant to remote content, thus making it dramatically more difficult for an attacker to harm your users should they gain the ability to execute JavaScript on your website. After this, you can grant additional permissions for specific hosts. For example, if you are opening a BrowserWindow pointed at `https://example.com/`, you can give that website exactly the abilities it needs, but no more. #### Why? A cross-site-scripting (XSS) attack is more dangerous if an attacker can jump out of the renderer process and execute code on the user's computer. Cross-site-scripting attacks are fairly common - and while an issue, their power is usually limited to messing with the website that they are executed on. Disabling Node.js integration helps prevent an XSS from being escalated into a so-called "Remote Code Execution" (RCE) attack. #### How? ```js title='main.js (Main Process)' // Bad const mainWindow = new BrowserWindow({ webPreferences: { contextIsolation: false, nodeIntegration: true, nodeIntegrationInWorker: true } }) mainWindow.loadURL('https://example.com') ``` ```js title='main.js (Main Process)' // Good const mainWindow = new BrowserWindow({ webPreferences: { preload: path.join(app.getAppPath(), 'preload.js') } }) mainWindow.loadURL('https://example.com') ``` ```html title='index.html (Renderer Process)' <!-- Bad --> <webview nodeIntegration src="page.html"></webview> <!-- Good --> <webview src="page.html"></webview> ``` When disabling Node.js integration, you can still expose APIs to your website that do consume Node.js modules or features. Preload scripts continue to have access to `require` and other Node.js features, allowing developers to expose a custom API to remotely loaded content via the [contextBridge API](../api/context-bridge.md). ### 3. Enable Context Isolation for remote content :::info This recommendation is the default behavior in Electron since 12.0.0. ::: Context isolation is an Electron feature that allows developers to run code in preload scripts and in Electron APIs in a dedicated JavaScript context. In practice, that means that global objects like `Array.prototype.push` or `JSON.parse` cannot be modified by scripts running in the renderer process. Electron uses the same technology as Chromium's [Content Scripts](https://developer.chrome.com/extensions/content_scripts#execution-environment) to enable this behavior. Even when `nodeIntegration: false` is used, to truly enforce strong isolation and prevent the use of Node primitives `contextIsolation` **must** also be used. :::info For more information on what `contextIsolation` is and how to enable it please see our dedicated [Context Isolation](context-isolation.md) document. :::info ### 4. Enable process sandboxing [Sandboxing](https://chromium.googlesource.com/chromium/src/+/HEAD/docs/design/sandbox.md) is a Chromium feature that uses the operating system to significantly limit what renderer processes have access to. You should enable the sandbox in all renderers. Loading, reading or processing any untrusted content in an unsandboxed process, including the main process, is not advised. :::info For more information on what `contextIsolation` is and how to enable it please see our dedicated [Process Sandboxing](sandbox.md) document. :::info ### 5. Handle session permission requests from remote content You may have seen permission requests while using Chrome: they pop up whenever the website attempts to use a feature that the user has to manually approve ( like notifications). The API is based on the [Chromium permissions API](https://developer.chrome.com/extensions/permissions) and implements the same types of permissions. #### Why? By default, Electron will automatically approve all permission requests unless the developer has manually configured a custom handler. While a solid default, security-conscious developers might want to assume the very opposite. #### How? ```js title='main.js (Main Process)' const { session } = require('electron') const URL = require('url').URL session .fromPartition('some-partition') .setPermissionRequestHandler((webContents, permission, callback) => { const parsedUrl = new URL(webContents.getURL()) if (permission === 'notifications') { // Approves the permissions request callback(true) } // Verify URL if (parsedUrl.protocol !== 'https:' || parsedUrl.host !== 'example.com') { // Denies the permissions request return callback(false) } }) ``` ### 6. Do not disable `webSecurity` :::info This recommendation is Electron's default. ::: You may have already guessed that disabling the `webSecurity` property on a renderer process ([`BrowserWindow`][browser-window], [`BrowserView`][browser-view], or [`<webview>`][webview-tag]) disables crucial security features. Do not disable `webSecurity` in production applications. #### Why? Disabling `webSecurity` will disable the same-origin policy and set `allowRunningInsecureContent` property to `true`. In other words, it allows the execution of insecure code from different domains. #### How? ```js title='main.js (Main Process)' // Bad const mainWindow = new BrowserWindow({ webPreferences: { webSecurity: false } }) ``` ```js title='main.js (Main Process)' // Good const mainWindow = new BrowserWindow() ``` ```html title='index.html (Renderer Process)' <!-- Bad --> <webview disablewebsecurity src="page.html"></webview> <!-- Good --> <webview src="page.html"></webview> ``` ### 7. Define a Content Security Policy A Content Security Policy (CSP) is an additional layer of protection against cross-site-scripting attacks and data injection attacks. We recommend that they be enabled by any website you load inside Electron. #### Why? CSP allows the server serving content to restrict and control the resources Electron can load for that given web page. `https://example.com` should be allowed to load scripts from the origins you defined while scripts from `https://evil.attacker.com` should not be allowed to run. Defining a CSP is an easy way to improve your application's security. #### How? The following CSP will allow Electron to execute scripts from the current website and from `apis.example.com`. ```plaintext // Bad Content-Security-Policy: '*' // Good Content-Security-Policy: script-src 'self' https://apis.example.com ``` #### CSP HTTP headers Electron respects the [`Content-Security-Policy` HTTP header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy) which can be set using Electron's [`webRequest.onHeadersReceived`](../api/web-request.md#webrequestonheadersreceivedfilter-listener) handler: ```javascript title='main.js (Main Process)' const { session } = require('electron') session.defaultSession.webRequest.onHeadersReceived((details, callback) => { callback({ responseHeaders: { ...details.responseHeaders, 'Content-Security-Policy': ['default-src \'none\''] } }) }) ``` #### CSP meta tag CSP's preferred delivery mechanism is an HTTP header. However, it is not possible to use this method when loading a resource using the `file://` protocol. It can be useful in some cases to set a policy on a page directly in the markup using a `<meta>` tag: ```html title='index.html (Renderer Process)' <meta http-equiv="Content-Security-Policy" content="default-src 'none'"> ``` ### 8. Do not enable `allowRunningInsecureContent` :::info This recommendation is Electron's default. ::: By default, Electron will not allow websites loaded over `HTTPS` to load and execute scripts, CSS, or plugins from insecure sources (`HTTP`). Setting the property `allowRunningInsecureContent` to `true` disables that protection. Loading the initial HTML of a website over `HTTPS` and attempting to load subsequent resources via `HTTP` is also known as "mixed content". #### Why? Loading content over `HTTPS` assures the authenticity and integrity of the loaded resources while encrypting the traffic itself. See the section on [only displaying secure content](#1-only-load-secure-content) for more details. #### How? ```js title='main.js (Main Process)' // Bad const mainWindow = new BrowserWindow({ webPreferences: { allowRunningInsecureContent: true } }) ``` ```js title='main.js (Main Process)' // Good const mainWindow = new BrowserWindow({}) ``` ### 9. Do not enable experimental features :::info This recommendation is Electron's default. ::: Advanced users of Electron can enable experimental Chromium features using the `experimentalFeatures` property. #### Why? Experimental features are, as the name suggests, experimental and have not been enabled for all Chromium users. Furthermore, their impact on Electron as a whole has likely not been tested. Legitimate use cases exist, but unless you know what you are doing, you should not enable this property. #### How? ```js title='main.js (Main Process)' // Bad const mainWindow = new BrowserWindow({ webPreferences: { experimentalFeatures: true } }) ``` ```js title='main.js (Main Process)' // Good const mainWindow = new BrowserWindow({}) ``` ### 10. Do not use `enableBlinkFeatures` :::info This recommendation is Electron's default. ::: Blink is the name of the rendering engine behind Chromium. As with `experimentalFeatures`, the `enableBlinkFeatures` property allows developers to enable features that have been disabled by default. #### Why? Generally speaking, there are likely good reasons if a feature was not enabled by default. Legitimate use cases for enabling specific features exist. As a developer, you should know exactly why you need to enable a feature, what the ramifications are, and how it impacts the security of your application. Under no circumstances should you enable features speculatively. #### How? ```js title='main.js (Main Process)' // Bad const mainWindow = new BrowserWindow({ webPreferences: { enableBlinkFeatures: 'ExecCommandInJavaScript' } }) ``` ```js title='main.js (Main Process)' // Good const mainWindow = new BrowserWindow() ``` ### 11. Do not use `allowpopups` for WebViews :::info This recommendation is Electron's default. ::: If you are using [`<webview>`][webview-tag], you might need the pages and scripts loaded in your `<webview>` tag to open new windows. The `allowpopups` attribute enables them to create new [`BrowserWindows`][browser-window] using the `window.open()` method. `<webview>` tags are otherwise not allowed to create new windows. #### Why? If you do not need popups, you are better off not allowing the creation of new [`BrowserWindows`][browser-window] by default. This follows the principle of minimally required access: Don't let a website create new popups unless you know it needs that feature. #### How? ```html title='index.html (Renderer Process)' <!-- Bad --> <webview allowpopups src="page.html"></webview> <!-- Good --> <webview src="page.html"></webview> ``` ### 12. Verify WebView options before creation A WebView created in a renderer process that does not have Node.js integration enabled will not be able to enable integration itself. However, a WebView will always create an independent renderer process with its own `webPreferences`. It is a good idea to control the creation of new [`<webview>`][webview-tag] tags from the main process and to verify that their webPreferences do not disable security features. #### Why? Since `<webview>` live in the DOM, they can be created by a script running on your website even if Node.js integration is otherwise disabled. Electron enables developers to disable various security features that control a renderer process. In most cases, developers do not need to disable any of those features - and you should therefore not allow different configurations for newly created [`<webview>`][webview-tag] tags. #### How? Before a [`<webview>`][webview-tag] tag is attached, Electron will fire the `will-attach-webview` event on the hosting `webContents`. Use the event to prevent the creation of `webViews` with possibly insecure options. ```js title='main.js (Main Process)' app.on('web-contents-created', (event, contents) => { contents.on('will-attach-webview', (event, webPreferences, params) => { // Strip away preload scripts if unused or verify their location is legitimate delete webPreferences.preload // Disable Node.js integration webPreferences.nodeIntegration = false // Verify URL being loaded if (!params.src.startsWith('https://example.com/')) { event.preventDefault() } }) }) ``` Again, this list merely minimizes the risk, but does not remove it. If your goal is to display a website, a browser will be a more secure option. ### 13. Disable or limit navigation If your app has no need to navigate or only needs to navigate to known pages, it is a good idea to limit navigation outright to that known scope, disallowing any other kinds of navigation. #### Why? Navigation is a common attack vector. If an attacker can convince your app to navigate away from its current page, they can possibly force your app to open web sites on the Internet. Even if your `webContents` are configured to be more secure (like having `nodeIntegration` disabled or `contextIsolation` enabled), getting your app to open a random web site will make the work of exploiting your app a lot easier. A common attack pattern is that the attacker convinces your app's users to interact with the app in such a way that it navigates to one of the attacker's pages. This is usually done via links, plugins, or other user-generated content. #### How? If your app has no need for navigation, you can call `event.preventDefault()` in a [`will-navigate`][will-navigate] handler. If you know which pages your app might navigate to, check the URL in the event handler and only let navigation occur if it matches the URLs you're expecting. We recommend that you use Node's parser for URLs. Simple string comparisons can sometimes be fooled - a `startsWith('https://example.com')` test would let `https://example.com.attacker.com` through. ```js title='main.js (Main Process)' const URL = require('url').URL app.on('web-contents-created', (event, contents) => { contents.on('will-navigate', (event, navigationUrl) => { const parsedUrl = new URL(navigationUrl) if (parsedUrl.origin !== 'https://example.com') { event.preventDefault() } }) }) ``` ### 14. Disable or limit creation of new windows If you have a known set of windows, it's a good idea to limit the creation of additional windows in your app. #### Why? Much like navigation, the creation of new `webContents` is a common attack vector. Attackers attempt to convince your app to create new windows, frames, or other renderer processes with more privileges than they had before; or with pages opened that they couldn't open before. If you have no need to create windows in addition to the ones you know you'll need to create, disabling the creation buys you a little bit of extra security at no cost. This is commonly the case for apps that open one `BrowserWindow` and do not need to open an arbitrary number of additional windows at runtime. #### How? [`webContents`][web-contents] will delegate to its [window open handler][window-open-handler] before creating new windows. The handler will receive, amongst other parameters, the `url` the window was requested to open and the options used to create it. We recommend that you register a handler to monitor the creation of windows, and deny any unexpected window creation. ```js title='main.js (Main Process)' const { shell } = require('electron') app.on('web-contents-created', (event, contents) => { contents.setWindowOpenHandler(({ url }) => { // In this example, we'll ask the operating system // to open this event's url in the default browser. // // See the following item for considerations regarding what // URLs should be allowed through to shell.openExternal. if (isSafeForExternalOpen(url)) { setImmediate(() => { shell.openExternal(url) }) } return { action: 'deny' } }) }) ``` ### 15. Do not use `shell.openExternal` with untrusted content The shell module's [`openExternal`][open-external] API allows opening a given protocol URI with the desktop's native utilities. On macOS, for instance, this function is similar to the `open` terminal command utility and will open the specific application based on the URI and filetype association. #### Why? Improper use of [`openExternal`][open-external] can be leveraged to compromise the user's host. When openExternal is used with untrusted content, it can be leveraged to execute arbitrary commands. #### How? ```js title='main.js (Main Process)' // Bad const { shell } = require('electron') shell.openExternal(USER_CONTROLLED_DATA_HERE) ``` ```js title='main.js (Main Process)' // Good const { shell } = require('electron') shell.openExternal('https://example.com/index.html') ``` ### 16. Use a current version of Electron You should strive for always using the latest available version of Electron. Whenever a new major version is released, you should attempt to update your app as quickly as possible. #### Why? An application built with an older version of Electron, Chromium, and Node.js is an easier target than an application that is using more recent versions of those components. Generally speaking, security issues and exploits for older versions of Chromium and Node.js are more widely available. Both Chromium and Node.js are impressive feats of engineering built by thousands of talented developers. Given their popularity, their security is carefully tested and analyzed by equally skilled security researchers. Many of those researchers [disclose vulnerabilities responsibly][responsible-disclosure], which generally means that researchers will give Chromium and Node.js some time to fix issues before publishing them. Your application will be more secure if it is running a recent version of Electron (and thus, Chromium and Node.js) for which potential security issues are not as widely known. #### How? Migrate your app one major version at a time, while referring to Electron's [Breaking Changes][breaking-changes] document to see if any code needs to be updated. ### 17. Validate the `sender` of all IPC messages You should always validate incoming IPC messages `sender` property to ensure you aren't performing actions or sending information to untrusted renderers. #### Why? All Web Frames can in theory send IPC messages to the main process, including iframes and child windows in some scenarios. If you have an IPC message that returns user data to the sender via `event.reply` or performs privileged actions that the renderer can't natively, you should ensure you aren't listening to third party web frames. You should be validating the `sender` of **all** IPC messages by default. #### How? ```js title='main.js (Main Process)' // Bad ipcMain.handle('get-secrets', () => { return getSecrets(); }); // Good ipcMain.handle('get-secrets', (e) => { if (!validateSender(e.senderFrame)) return null; return getSecrets(); }); function validateSender(frame) { // Value the host of the URL using an actual URL parser and an allowlist if ((new URL(frame.url)).host === 'electronjs.org') return true; return false; } ``` [breaking-changes]: ../breaking-changes.md [browser-window]: ../api/browser-window.md [browser-view]: ../api/browser-view.md [webview-tag]: ../api/webview-tag.md [web-contents]: ../api/web-contents.md [window-open-handler]: ../api/web-contents.md#contentssetwindowopenhandlerhandler [will-navigate]: ../api/web-contents.md#event-will-navigate [open-external]: ../api/shell.md#shellopenexternalurl-options [responsible-disclosure]: https://en.wikipedia.org/wiki/Responsible_disclosure
closed
electron/electron
https://github.com/electron/electron
33,806
[Bug]: clarify in Security document when contextIsolation should be enabled
### 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 Security [doc](https://www.electronjs.org/docs/latest/tutorial/security#3-enable-context-isolation-for-remote-content) states: >Enable Context Isolation for remote content Based on some of the discussion in [this issue](https://github.com/electron/electron/issues/23506) (specifically [here](https://github.com/electron/electron/issues/23506#issuecomment-922092517)), it sounds like Electron is recommending that we enable `contextIsolation` for *all* content, remote or local. Should the Sec doc be updated in that case? ### Proposed Solution Remove the bit about "remote content" from that section ### Alternatives Considered n/a ### Additional Information _No response_
https://github.com/electron/electron/issues/33806
https://github.com/electron/electron/pull/33807
5ae234d5e1d20bc9db5abb780d79b694a4ef09d7
2d0ad043542d99d28332127915b70084409b5786
2022-04-15T21:02:10Z
c++
2022-04-18T14:09:54Z
docs/api/context-bridge.md
# contextBridge > Create a safe, bi-directional, synchronous bridge across isolated contexts Process: [Renderer](../glossary.md#renderer-process) An example of exposing an API to a renderer from an isolated preload script is given below: ```javascript // Preload (Isolated World) const { contextBridge, ipcRenderer } = require('electron') contextBridge.exposeInMainWorld( 'electron', { doThing: () => ipcRenderer.send('do-a-thing') } ) ``` ```javascript // Renderer (Main World) window.electron.doThing() ``` ## Glossary ### Main World The "Main World" is the JavaScript context that your main renderer code runs in. By default, the page you load in your renderer executes code in this world. ### Isolated World When `contextIsolation` is enabled in your `webPreferences` (this is the default behavior since Electron 12.0.0), your `preload` scripts run in an "Isolated World". You can read more about context isolation and what it affects in the [security](../tutorial/security.md#3-enable-context-isolation-for-remote-content) docs. ## Methods The `contextBridge` module has the following methods: ### `contextBridge.exposeInMainWorld(apiKey, api)` * `apiKey` string - The key to inject the API onto `window` with. The API will be accessible on `window[apiKey]`. * `api` any - Your API, more information on what this API can be and how it works is available below. ## Usage ### API The `api` provided to [`exposeInMainWorld`](#contextbridgeexposeinmainworldapikey-api) must be a `Function`, `string`, `number`, `Array`, `boolean`, or an object whose keys are strings and values are a `Function`, `string`, `number`, `Array`, `boolean`, or another nested object that meets the same conditions. `Function` values are proxied to the other context and all other values are **copied** and **frozen**. Any data / primitives sent in the API become immutable and updates on either side of the bridge do not result in an update on the other side. An example of a complex API is shown below: ```javascript const { contextBridge } = require('electron') contextBridge.exposeInMainWorld( 'electron', { doThing: () => ipcRenderer.send('do-a-thing'), myPromises: [Promise.resolve(), Promise.reject(new Error('whoops'))], anAsyncFunction: async () => 123, data: { myFlags: ['a', 'b', 'c'], bootTime: 1234 }, nestedAPI: { evenDeeper: { youCanDoThisAsMuchAsYouWant: { fn: () => ({ returnData: 123 }) } } } } ) ``` ### API Functions `Function` values that you bind through the `contextBridge` are proxied through Electron to ensure that contexts remain isolated. This results in some key limitations that we've outlined below. #### Parameter / Error / Return Type support Because parameters, errors and return values are **copied** when they are sent over the bridge, there are only certain types that can be used. At a high level, if the type you want to use can be serialized and deserialized into the same object it will work. A table of type support has been included below for completeness: | Type | Complexity | Parameter Support | Return Value Support | Limitations | | ---- | ---------- | ----------------- | -------------------- | ----------- | | `string` | Simple | ✅ | ✅ | N/A | | `number` | Simple | ✅ | ✅ | N/A | | `boolean` | Simple | ✅ | ✅ | N/A | | `Object` | Complex | ✅ | ✅ | Keys must be supported using only "Simple" types in this table. Values must be supported in this table. Prototype modifications are dropped. Sending custom classes will copy values but not the prototype. | | `Array` | Complex | ✅ | ✅ | Same limitations as the `Object` type | | `Error` | Complex | ✅ | ✅ | Errors that are thrown are also copied, this can result in the message and stack trace of the error changing slightly due to being thrown in a different context, and any custom properties on the Error object [will be lost](https://github.com/electron/electron/issues/25596) | | `Promise` | Complex | ✅ | ✅ | N/A | `Function` | Complex | ✅ | ✅ | Prototype modifications are dropped. Sending classes or constructors will not work. | | [Cloneable Types](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm) | Simple | ✅ | ✅ | See the linked document on cloneable types | | `Element` | Complex | ✅ | ✅ | Prototype modifications are dropped. Sending custom elements will not work. | | `Blob` | Complex | ✅ | ✅ | N/A | | `Symbol` | N/A | ❌ | ❌ | Symbols cannot be copied across contexts so they are dropped | If the type you care about is not in the above table, it is probably not supported. ### Exposing Node Global Symbols The `contextBridge` can be used by the preload script to give your renderer access to Node APIs. The table of supported types described above also applies to Node APIs that you expose through `contextBridge`. Please note that many Node APIs grant access to local system resources. Be very cautious about which globals and APIs you expose to untrusted remote content. ```javascript const { contextBridge } = require('electron') const crypto = require('crypto') contextBridge.exposeInMainWorld('nodeCrypto', { sha256sum (data) { const hash = crypto.createHash('sha256') hash.update(data) return hash.digest('hex') } }) ```
closed
electron/electron
https://github.com/electron/electron
33,806
[Bug]: clarify in Security document when contextIsolation should be enabled
### 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 Security [doc](https://www.electronjs.org/docs/latest/tutorial/security#3-enable-context-isolation-for-remote-content) states: >Enable Context Isolation for remote content Based on some of the discussion in [this issue](https://github.com/electron/electron/issues/23506) (specifically [here](https://github.com/electron/electron/issues/23506#issuecomment-922092517)), it sounds like Electron is recommending that we enable `contextIsolation` for *all* content, remote or local. Should the Sec doc be updated in that case? ### Proposed Solution Remove the bit about "remote content" from that section ### Alternatives Considered n/a ### Additional Information _No response_
https://github.com/electron/electron/issues/33806
https://github.com/electron/electron/pull/33807
5ae234d5e1d20bc9db5abb780d79b694a4ef09d7
2d0ad043542d99d28332127915b70084409b5786
2022-04-15T21:02:10Z
c++
2022-04-18T14:09:54Z
docs/breaking-changes.md
# Breaking Changes Breaking changes will be documented here, and deprecation warnings added to JS code where possible, at least [one major version](tutorial/electron-versioning.md#semver) before the change is made. ### Types of Breaking Changes This document uses the following convention to categorize breaking changes: * **API Changed:** An API was changed in such a way that code that has not been updated is guaranteed to throw an exception. * **Behavior Changed:** The behavior of Electron has changed, but not in such a way that an exception will necessarily be thrown. * **Default Changed:** Code depending on the old default may break, not necessarily throwing an exception. The old behavior can be restored by explicitly specifying the value. * **Deprecated:** An API was marked as deprecated. The API will continue to function, but will emit a deprecation warning, and will be removed in a future release. * **Removed:** An API or feature was removed, and is no longer supported by Electron. ## Planned Breaking API Changes (20.0) ### Default Changed: renderers without `nodeIntegration: true` are sandboxed by default Previously, renderers that specified a preload script defaulted to being unsandboxed. This meant that by default, preload scripts had access to Node.js. In Electron 20, this default has changed. Beginning in Electron 20, renderers will be sandboxed by default, unless `nodeIntegration: true` or `sandbox: false` is specified. If your preload scripts do not depend on Node, no action is needed. If your preload scripts _do_ depend on Node, either refactor them to remove Node usage from the renderer, or explicitly specify `sandbox: false` for the relevant renderers. ### Removed: `skipTaskbar` on Linux On X11, `skipTaskbar` sends a `_NET_WM_STATE_SKIP_TASKBAR` message to the X11 window manager. There is not a direct equivalent for Wayland, and the known workarounds have unacceptable tradeoffs (e.g. Window.is_skip_taskbar in GNOME requires unsafe mode), so Electron is unable to support this feature on Linux. ## Planned Breaking API Changes (19.0) None ## Planned Breaking API Changes (18.0) ### Removed: `nativeWindowOpen` Prior to Electron 15, `window.open` was by default shimmed to use `BrowserWindowProxy`. This meant that `window.open('about:blank')` did not work to open synchronously scriptable child windows, among other incompatibilities. Since Electron 15, `nativeWindowOpen` has been enabled by default. See the documentation for [window.open in Electron](api/window-open.md) for more details. ## Planned Breaking API Changes (17.0) ### Removed: `desktopCapturer.getSources` in the renderer The `desktopCapturer.getSources` API is now only available in the main process. This has been changed in order to improve the default security of Electron apps. If you need this functionality, it can be replaced as follows: ```js // Main process const { ipcMain, desktopCapturer } = require('electron') ipcMain.handle( 'DESKTOP_CAPTURER_GET_SOURCES', (event, opts) => desktopCapturer.getSources(opts) ) ``` ```js // Renderer process const { ipcRenderer } = require('electron') const desktopCapturer = { getSources: (opts) => ipcRenderer.invoke('DESKTOP_CAPTURER_GET_SOURCES', opts) } ``` However, you should consider further restricting the information returned to the renderer; for instance, displaying a source selector to the user and only returning the selected source. ### Deprecated: `nativeWindowOpen` Prior to Electron 15, `window.open` was by default shimmed to use `BrowserWindowProxy`. This meant that `window.open('about:blank')` did not work to open synchronously scriptable child windows, among other incompatibilities. Since Electron 15, `nativeWindowOpen` has been enabled by default. See the documentation for [window.open in Electron](api/window-open.md) for more details. ## Planned Breaking API Changes (16.0) ### Behavior Changed: `crashReporter` implementation switched to Crashpad on Linux The underlying implementation of the `crashReporter` API on Linux has changed from Breakpad to Crashpad, bringing it in line with Windows and Mac. As a result of this, child processes are now automatically monitored, and calling `process.crashReporter.start` in Node child processes is no longer needed (and is not advisable, as it will start a second instance of the Crashpad reporter). There are also some subtle changes to how annotations will be reported on Linux, including that long values will no longer be split between annotations appended with `__1`, `__2` and so on, and instead will be truncated at the (new, longer) annotation value limit. ### Deprecated: `desktopCapturer.getSources` in the renderer Usage of the `desktopCapturer.getSources` API in the renderer has been deprecated and will be removed. This change improves the default security of Electron apps. See [here](#removed-desktopcapturergetsources-in-the-renderer) for details on how to replace this API in your app. ## Planned Breaking API Changes (15.0) ### Default Changed: `nativeWindowOpen` defaults to `true` Prior to Electron 15, `window.open` was by default shimmed to use `BrowserWindowProxy`. This meant that `window.open('about:blank')` did not work to open synchronously scriptable child windows, among other incompatibilities. `nativeWindowOpen` is no longer experimental, and is now the default. See the documentation for [window.open in Electron](api/window-open.md) for more details. ## Planned Breaking API Changes (14.0) ### Removed: `remote` module The `remote` module was deprecated in Electron 12, and will be removed in Electron 14. It is replaced by the [`@electron/remote`](https://github.com/electron/remote) module. ```js // Deprecated in Electron 12: const { BrowserWindow } = require('electron').remote ``` ```js // Replace with: const { BrowserWindow } = require('@electron/remote') // In the main process: require('@electron/remote/main').initialize() ``` ### Removed: `app.allowRendererProcessReuse` The `app.allowRendererProcessReuse` property will be removed as part of our plan to more closely align with Chromium's process model for security, performance and maintainability. For more detailed information see [#18397](https://github.com/electron/electron/issues/18397). ### Removed: Browser Window Affinity The `affinity` option when constructing a new `BrowserWindow` will be removed as part of our plan to more closely align with Chromium's process model for security, performance and maintainability. For more detailed information see [#18397](https://github.com/electron/electron/issues/18397). ### API Changed: `window.open()` The optional parameter `frameName` will no longer set the title of the window. This now follows the specification described by the [native documentation](https://developer.mozilla.org/en-US/docs/Web/API/Window/open#parameters) under the corresponding parameter `windowName`. If you were using this parameter to set the title of a window, you can instead use [win.setTitle(title)](api/browser-window.md#winsettitletitle). ### Removed: `worldSafeExecuteJavaScript` In Electron 14, `worldSafeExecuteJavaScript` will be removed. There is no alternative, please ensure your code works with this property enabled. It has been enabled by default since Electron 12. You will be affected by this change if you use either `webFrame.executeJavaScript` or `webFrame.executeJavaScriptInIsolatedWorld`. You will need to ensure that values returned by either of those methods are supported by the [Context Bridge API](api/context-bridge.md#parameter--error--return-type-support) as these methods use the same value passing semantics. ### Removed: BrowserWindowConstructorOptions inheriting from parent windows Prior to Electron 14, windows opened with `window.open` would inherit BrowserWindow constructor options such as `transparent` and `resizable` from their parent window. Beginning with Electron 14, this behavior is removed, and windows will not inherit any BrowserWindow constructor options from their parents. Instead, explicitly set options for the new window with `setWindowOpenHandler`: ```js webContents.setWindowOpenHandler((details) => { return { action: 'allow', overrideBrowserWindowOptions: { // ... } } }) ``` ### Removed: `additionalFeatures` The deprecated `additionalFeatures` property in the `new-window` and `did-create-window` events of WebContents has been removed. Since `new-window` uses positional arguments, the argument is still present, but will always be the empty array `[]`. (Though note, the `new-window` event itself is deprecated, and is replaced by `setWindowOpenHandler`.) Bare keys in window features will now present as keys with the value `true` in the options object. ```js // Removed in Electron 14 // Triggered by window.open('...', '', 'my-key') webContents.on('did-create-window', (window, details) => { if (details.additionalFeatures.includes('my-key')) { // ... } }) // Replace with webContents.on('did-create-window', (window, details) => { if (details.options['my-key']) { // ... } }) ``` ## Planned Breaking API Changes (13.0) ### API Changed: `session.setPermissionCheckHandler(handler)` The `handler` methods first parameter was previously always a `webContents`, it can now sometimes be `null`. You should use the `requestingOrigin`, `embeddingOrigin` and `securityOrigin` properties to respond to the permission check correctly. As the `webContents` can be `null` it can no longer be relied on. ```js // Old code session.setPermissionCheckHandler((webContents, permission) => { if (webContents.getURL().startsWith('https://google.com/') && permission === 'notification') { return true } return false }) // Replace with session.setPermissionCheckHandler((webContents, permission, requestingOrigin) => { if (new URL(requestingOrigin).hostname === 'google.com' && permission === 'notification') { return true } return false }) ``` ### Removed: `shell.moveItemToTrash()` The deprecated synchronous `shell.moveItemToTrash()` API has been removed. Use the asynchronous `shell.trashItem()` instead. ```js // Removed in Electron 13 shell.moveItemToTrash(path) // Replace with shell.trashItem(path).then(/* ... */) ``` ### Removed: `BrowserWindow` extension APIs The deprecated extension APIs have been removed: * `BrowserWindow.addExtension(path)` * `BrowserWindow.addDevToolsExtension(path)` * `BrowserWindow.removeExtension(name)` * `BrowserWindow.removeDevToolsExtension(name)` * `BrowserWindow.getExtensions()` * `BrowserWindow.getDevToolsExtensions()` Use the session APIs instead: * `ses.loadExtension(path)` * `ses.removeExtension(extension_id)` * `ses.getAllExtensions()` ```js // Removed in Electron 13 BrowserWindow.addExtension(path) BrowserWindow.addDevToolsExtension(path) // Replace with session.defaultSession.loadExtension(path) ``` ```js // Removed in Electron 13 BrowserWindow.removeExtension(name) BrowserWindow.removeDevToolsExtension(name) // Replace with session.defaultSession.removeExtension(extension_id) ``` ```js // Removed in Electron 13 BrowserWindow.getExtensions() BrowserWindow.getDevToolsExtensions() // Replace with session.defaultSession.getAllExtensions() ``` ### Removed: methods in `systemPreferences` The following `systemPreferences` methods have been deprecated: * `systemPreferences.isDarkMode()` * `systemPreferences.isInvertedColorScheme()` * `systemPreferences.isHighContrastColorScheme()` Use the following `nativeTheme` properties instead: * `nativeTheme.shouldUseDarkColors` * `nativeTheme.shouldUseInvertedColorScheme` * `nativeTheme.shouldUseHighContrastColors` ```js // Removed in Electron 13 systemPreferences.isDarkMode() // Replace with nativeTheme.shouldUseDarkColors // Removed in Electron 13 systemPreferences.isInvertedColorScheme() // Replace with nativeTheme.shouldUseInvertedColorScheme // Removed in Electron 13 systemPreferences.isHighContrastColorScheme() // Replace with nativeTheme.shouldUseHighContrastColors ``` ### Deprecated: WebContents `new-window` event The `new-window` event of WebContents has been deprecated. It is replaced by [`webContents.setWindowOpenHandler()`](api/web-contents.md#contentssetwindowopenhandlerhandler). ```js // Deprecated in Electron 13 webContents.on('new-window', (event) => { event.preventDefault() }) // Replace with webContents.setWindowOpenHandler((details) => { return { action: 'deny' } }) ``` ## Planned Breaking API Changes (12.0) ### Removed: Pepper Flash support Chromium has removed support for Flash, and so we must follow suit. See Chromium's [Flash Roadmap](https://www.chromium.org/flash-roadmap) for more details. ### Default Changed: `worldSafeExecuteJavaScript` defaults to `true` In Electron 12, `worldSafeExecuteJavaScript` will be enabled by default. To restore the previous behavior, `worldSafeExecuteJavaScript: false` must be specified in WebPreferences. Please note that setting this option to `false` is **insecure**. This option will be removed in Electron 14 so please migrate your code to support the default value. ### Default Changed: `contextIsolation` defaults to `true` In Electron 12, `contextIsolation` will be enabled by default. To restore the previous behavior, `contextIsolation: false` must be specified in WebPreferences. We [recommend having contextIsolation enabled](tutorial/security.md#3-enable-context-isolation-for-remote-content) for the security of your application. Another implication is that `require()` cannot be used in the renderer process unless `nodeIntegration` is `true` and `contextIsolation` is `false`. For more details see: https://github.com/electron/electron/issues/23506 ### Removed: `crashReporter.getCrashesDirectory()` The `crashReporter.getCrashesDirectory` method has been removed. Usage should be replaced by `app.getPath('crashDumps')`. ```js // Removed in Electron 12 crashReporter.getCrashesDirectory() // Replace with app.getPath('crashDumps') ``` ### Removed: `crashReporter` methods in the renderer process The following `crashReporter` methods are no longer available in the renderer process: * `crashReporter.start` * `crashReporter.getLastCrashReport` * `crashReporter.getUploadedReports` * `crashReporter.getUploadToServer` * `crashReporter.setUploadToServer` * `crashReporter.getCrashesDirectory` They should be called only from the main process. See [#23265](https://github.com/electron/electron/pull/23265) for more details. ### Default Changed: `crashReporter.start({ compress: true })` The default value of the `compress` option to `crashReporter.start` has changed from `false` to `true`. This means that crash dumps will be uploaded to the crash ingestion server with the `Content-Encoding: gzip` header, and the body will be compressed. If your crash ingestion server does not support compressed payloads, you can turn off compression by specifying `{ compress: false }` in the crash reporter options. ### Deprecated: `remote` module The `remote` module is deprecated in Electron 12, and will be removed in Electron 14. It is replaced by the [`@electron/remote`](https://github.com/electron/remote) module. ```js // Deprecated in Electron 12: const { BrowserWindow } = require('electron').remote ``` ```js // Replace with: const { BrowserWindow } = require('@electron/remote') // In the main process: require('@electron/remote/main').initialize() ``` ### Deprecated: `shell.moveItemToTrash()` The synchronous `shell.moveItemToTrash()` has been replaced by the new, asynchronous `shell.trashItem()`. ```js // Deprecated in Electron 12 shell.moveItemToTrash(path) // Replace with shell.trashItem(path).then(/* ... */) ``` ## Planned Breaking API Changes (11.0) ### Removed: `BrowserView.{destroy, fromId, fromWebContents, getAllViews}` and `id` property of `BrowserView` The experimental APIs `BrowserView.{destroy, fromId, fromWebContents, getAllViews}` have now been removed. Additionally, the `id` property of `BrowserView` has also been removed. For more detailed information, see [#23578](https://github.com/electron/electron/pull/23578). ## Planned Breaking API Changes (10.0) ### Deprecated: `companyName` argument to `crashReporter.start()` The `companyName` argument to `crashReporter.start()`, which was previously required, is now optional, and further, is deprecated. To get the same behavior in a non-deprecated way, you can pass a `companyName` value in `globalExtra`. ```js // Deprecated in Electron 10 crashReporter.start({ companyName: 'Umbrella Corporation' }) // Replace with crashReporter.start({ globalExtra: { _companyName: 'Umbrella Corporation' } }) ``` ### Deprecated: `crashReporter.getCrashesDirectory()` The `crashReporter.getCrashesDirectory` method has been deprecated. Usage should be replaced by `app.getPath('crashDumps')`. ```js // Deprecated in Electron 10 crashReporter.getCrashesDirectory() // Replace with app.getPath('crashDumps') ``` ### Deprecated: `crashReporter` methods in the renderer process Calling the following `crashReporter` methods from the renderer process is deprecated: * `crashReporter.start` * `crashReporter.getLastCrashReport` * `crashReporter.getUploadedReports` * `crashReporter.getUploadToServer` * `crashReporter.setUploadToServer` * `crashReporter.getCrashesDirectory` The only non-deprecated methods remaining in the `crashReporter` module in the renderer are `addExtraParameter`, `removeExtraParameter` and `getParameters`. All above methods remain non-deprecated when called from the main process. See [#23265](https://github.com/electron/electron/pull/23265) for more details. ### Deprecated: `crashReporter.start({ compress: false })` Setting `{ compress: false }` in `crashReporter.start` is deprecated. Nearly all crash ingestion servers support gzip compression. This option will be removed in a future version of Electron. ### Default Changed: `enableRemoteModule` defaults to `false` In Electron 9, using the remote module without explicitly enabling it via the `enableRemoteModule` WebPreferences option began emitting a warning. In Electron 10, the remote module is now disabled by default. To use the remote module, `enableRemoteModule: true` must be specified in WebPreferences: ```js const w = new BrowserWindow({ webPreferences: { enableRemoteModule: true } }) ``` We [recommend moving away from the remote module](https://medium.com/@nornagon/electrons-remote-module-considered-harmful-70d69500f31). ### `protocol.unregisterProtocol` ### `protocol.uninterceptProtocol` The APIs are now synchronous and the optional callback is no longer needed. ```javascript // Deprecated protocol.unregisterProtocol(scheme, () => { /* ... */ }) // Replace with protocol.unregisterProtocol(scheme) ``` ### `protocol.registerFileProtocol` ### `protocol.registerBufferProtocol` ### `protocol.registerStringProtocol` ### `protocol.registerHttpProtocol` ### `protocol.registerStreamProtocol` ### `protocol.interceptFileProtocol` ### `protocol.interceptStringProtocol` ### `protocol.interceptBufferProtocol` ### `protocol.interceptHttpProtocol` ### `protocol.interceptStreamProtocol` The APIs are now synchronous and the optional callback is no longer needed. ```javascript // Deprecated protocol.registerFileProtocol(scheme, handler, () => { /* ... */ }) // Replace with protocol.registerFileProtocol(scheme, handler) ``` The registered or intercepted protocol does not have effect on current page until navigation happens. ### `protocol.isProtocolHandled` This API is deprecated and users should use `protocol.isProtocolRegistered` and `protocol.isProtocolIntercepted` instead. ```javascript // Deprecated protocol.isProtocolHandled(scheme).then(() => { /* ... */ }) // Replace with const isRegistered = protocol.isProtocolRegistered(scheme) const isIntercepted = protocol.isProtocolIntercepted(scheme) ``` ## Planned Breaking API Changes (9.0) ### Default Changed: Loading non-context-aware native modules in the renderer process is disabled by default As of Electron 9 we do not allow loading of non-context-aware native modules in the renderer process. This is to improve security, performance and maintainability of Electron as a project. If this impacts you, you can temporarily set `app.allowRendererProcessReuse` to `false` to revert to the old behavior. This flag will only be an option until Electron 11 so you should plan to update your native modules to be context aware. For more detailed information see [#18397](https://github.com/electron/electron/issues/18397). ### Deprecated: `BrowserWindow` extension APIs The following extension APIs have been deprecated: * `BrowserWindow.addExtension(path)` * `BrowserWindow.addDevToolsExtension(path)` * `BrowserWindow.removeExtension(name)` * `BrowserWindow.removeDevToolsExtension(name)` * `BrowserWindow.getExtensions()` * `BrowserWindow.getDevToolsExtensions()` Use the session APIs instead: * `ses.loadExtension(path)` * `ses.removeExtension(extension_id)` * `ses.getAllExtensions()` ```js // Deprecated in Electron 9 BrowserWindow.addExtension(path) BrowserWindow.addDevToolsExtension(path) // Replace with session.defaultSession.loadExtension(path) ``` ```js // Deprecated in Electron 9 BrowserWindow.removeExtension(name) BrowserWindow.removeDevToolsExtension(name) // Replace with session.defaultSession.removeExtension(extension_id) ``` ```js // Deprecated in Electron 9 BrowserWindow.getExtensions() BrowserWindow.getDevToolsExtensions() // Replace with session.defaultSession.getAllExtensions() ``` ### Removed: `<webview>.getWebContents()` This API, which was deprecated in Electron 8.0, is now removed. ```js // Removed in Electron 9.0 webview.getWebContents() // Replace with const { remote } = require('electron') remote.webContents.fromId(webview.getWebContentsId()) ``` ### Removed: `webFrame.setLayoutZoomLevelLimits()` Chromium has removed support for changing the layout zoom level limits, and it is beyond Electron's capacity to maintain it. The function was deprecated in Electron 8.x, and has been removed in Electron 9.x. The layout zoom level limits are now fixed at a minimum of 0.25 and a maximum of 5.0, as defined [here](https://chromium.googlesource.com/chromium/src/+/938b37a6d2886bf8335fc7db792f1eb46c65b2ae/third_party/blink/common/page/page_zoom.cc#11). ### Behavior Changed: Sending non-JS objects over IPC now throws an exception In Electron 8.0, IPC was changed to use the Structured Clone Algorithm, bringing significant performance improvements. To help ease the transition, the old IPC serialization algorithm was kept and used for some objects that aren't serializable with Structured Clone. In particular, DOM objects (e.g. `Element`, `Location` and `DOMMatrix`), Node.js objects backed by C++ classes (e.g. `process.env`, some members of `Stream`), and Electron objects backed by C++ classes (e.g. `WebContents`, `BrowserWindow` and `WebFrame`) are not serializable with Structured Clone. Whenever the old algorithm was invoked, a deprecation warning was printed. In Electron 9.0, the old serialization algorithm has been removed, and sending such non-serializable objects will now throw an "object could not be cloned" error. ### API Changed: `shell.openItem` is now `shell.openPath` The `shell.openItem` API has been replaced with an asynchronous `shell.openPath` API. You can see the original API proposal and reasoning [here](https://github.com/electron/governance/blob/main/wg-api/spec-documents/shell-openitem.md). ## Planned Breaking API Changes (8.0) ### Behavior Changed: Values sent over IPC are now serialized with Structured Clone Algorithm The algorithm used to serialize objects sent over IPC (through `ipcRenderer.send`, `ipcRenderer.sendSync`, `WebContents.send` and related methods) has been switched from a custom algorithm to V8's built-in [Structured Clone Algorithm][SCA], the same algorithm used to serialize messages for `postMessage`. This brings about a 2x performance improvement for large messages, but also brings some breaking changes in behavior. * Sending Functions, Promises, WeakMaps, WeakSets, or objects containing any such values, over IPC will now throw an exception, instead of silently converting the functions to `undefined`. ```js // Previously: ipcRenderer.send('channel', { value: 3, someFunction: () => {} }) // => results in { value: 3 } arriving in the main process // From Electron 8: ipcRenderer.send('channel', { value: 3, someFunction: () => {} }) // => throws Error("() => {} could not be cloned.") ``` * `NaN`, `Infinity` and `-Infinity` will now be correctly serialized, instead of being converted to `null`. * Objects containing cyclic references will now be correctly serialized, instead of being converted to `null`. * `Set`, `Map`, `Error` and `RegExp` values will be correctly serialized, instead of being converted to `{}`. * `BigInt` values will be correctly serialized, instead of being converted to `null`. * Sparse arrays will be serialized as such, instead of being converted to dense arrays with `null`s. * `Date` objects will be transferred as `Date` objects, instead of being converted to their ISO string representation. * Typed Arrays (such as `Uint8Array`, `Uint16Array`, `Uint32Array` and so on) will be transferred as such, instead of being converted to Node.js `Buffer`. * Node.js `Buffer` objects will be transferred as `Uint8Array`s. You can convert a `Uint8Array` back to a Node.js `Buffer` by wrapping the underlying `ArrayBuffer`: ```js Buffer.from(value.buffer, value.byteOffset, value.byteLength) ``` Sending any objects that aren't native JS types, such as DOM objects (e.g. `Element`, `Location`, `DOMMatrix`), Node.js objects (e.g. `process.env`, `Stream`), or Electron objects (e.g. `WebContents`, `BrowserWindow`, `WebFrame`) is deprecated. In Electron 8, these objects will be serialized as before with a DeprecationWarning message, but starting in Electron 9, sending these kinds of objects will throw a 'could not be cloned' error. [SCA]: https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm ### Deprecated: `<webview>.getWebContents()` This API is implemented using the `remote` module, which has both performance and security implications. Therefore its usage should be explicit. ```js // Deprecated webview.getWebContents() // Replace with const { remote } = require('electron') remote.webContents.fromId(webview.getWebContentsId()) ``` However, it is recommended to avoid using the `remote` module altogether. ```js // main const { ipcMain, webContents } = require('electron') const getGuestForWebContents = (webContentsId, contents) => { const guest = webContents.fromId(webContentsId) if (!guest) { throw new Error(`Invalid webContentsId: ${webContentsId}`) } if (guest.hostWebContents !== contents) { throw new Error('Access denied to webContents') } return guest } ipcMain.handle('openDevTools', (event, webContentsId) => { const guest = getGuestForWebContents(webContentsId, event.sender) guest.openDevTools() }) // renderer const { ipcRenderer } = require('electron') ipcRenderer.invoke('openDevTools', webview.getWebContentsId()) ``` ### Deprecated: `webFrame.setLayoutZoomLevelLimits()` Chromium has removed support for changing the layout zoom level limits, and it is beyond Electron's capacity to maintain it. The function will emit a warning in Electron 8.x, and cease to exist in Electron 9.x. The layout zoom level limits are now fixed at a minimum of 0.25 and a maximum of 5.0, as defined [here](https://chromium.googlesource.com/chromium/src/+/938b37a6d2886bf8335fc7db792f1eb46c65b2ae/third_party/blink/common/page/page_zoom.cc#11). ### Deprecated events in `systemPreferences` The following `systemPreferences` events have been deprecated: * `inverted-color-scheme-changed` * `high-contrast-color-scheme-changed` Use the new `updated` event on the `nativeTheme` module instead. ```js // Deprecated systemPreferences.on('inverted-color-scheme-changed', () => { /* ... */ }) systemPreferences.on('high-contrast-color-scheme-changed', () => { /* ... */ }) // Replace with nativeTheme.on('updated', () => { /* ... */ }) ``` ### Deprecated: methods in `systemPreferences` The following `systemPreferences` methods have been deprecated: * `systemPreferences.isDarkMode()` * `systemPreferences.isInvertedColorScheme()` * `systemPreferences.isHighContrastColorScheme()` Use the following `nativeTheme` properties instead: * `nativeTheme.shouldUseDarkColors` * `nativeTheme.shouldUseInvertedColorScheme` * `nativeTheme.shouldUseHighContrastColors` ```js // Deprecated systemPreferences.isDarkMode() // Replace with nativeTheme.shouldUseDarkColors // Deprecated systemPreferences.isInvertedColorScheme() // Replace with nativeTheme.shouldUseInvertedColorScheme // Deprecated systemPreferences.isHighContrastColorScheme() // Replace with nativeTheme.shouldUseHighContrastColors ``` ## Planned Breaking API Changes (7.0) ### Deprecated: Atom.io Node Headers URL This is the URL specified as `disturl` in a `.npmrc` file or as the `--dist-url` command line flag when building native Node modules. Both will be supported for the foreseeable future but it is recommended that you switch. Deprecated: https://atom.io/download/electron Replace with: https://electronjs.org/headers ### API Changed: `session.clearAuthCache()` no longer accepts options The `session.clearAuthCache` API no longer accepts options for what to clear, and instead unconditionally clears the whole cache. ```js // Deprecated session.clearAuthCache({ type: 'password' }) // Replace with session.clearAuthCache() ``` ### API Changed: `powerMonitor.querySystemIdleState` is now `powerMonitor.getSystemIdleState` ```js // Removed in Electron 7.0 powerMonitor.querySystemIdleState(threshold, callback) // Replace with synchronous API const idleState = powerMonitor.getSystemIdleState(threshold) ``` ### API Changed: `powerMonitor.querySystemIdleTime` is now `powerMonitor.getSystemIdleTime` ```js // Removed in Electron 7.0 powerMonitor.querySystemIdleTime(callback) // Replace with synchronous API const idleTime = powerMonitor.getSystemIdleTime() ``` ### API Changed: `webFrame.setIsolatedWorldInfo` replaces separate methods ```js // Removed in Electron 7.0 webFrame.setIsolatedWorldContentSecurityPolicy(worldId, csp) webFrame.setIsolatedWorldHumanReadableName(worldId, name) webFrame.setIsolatedWorldSecurityOrigin(worldId, securityOrigin) // Replace with webFrame.setIsolatedWorldInfo( worldId, { securityOrigin: 'some_origin', name: 'human_readable_name', csp: 'content_security_policy' }) ``` ### Removed: `marked` property on `getBlinkMemoryInfo` This property was removed in Chromium 77, and as such is no longer available. ### Behavior Changed: `webkitdirectory` attribute for `<input type="file"/>` now lists directory contents The `webkitdirectory` property on HTML file inputs allows them to select folders. Previous versions of Electron had an incorrect implementation where the `event.target.files` of the input returned a `FileList` that returned one `File` corresponding to the selected folder. As of Electron 7, that `FileList` is now list of all files contained within the folder, similarly to Chrome, Firefox, and Edge ([link to MDN docs](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/webkitdirectory)). As an illustration, take a folder with this structure: ```console folder ├── file1 ├── file2 └── file3 ``` In Electron <=6, this would return a `FileList` with a `File` object for: ```console path/to/folder ``` In Electron 7, this now returns a `FileList` with a `File` object for: ```console /path/to/folder/file3 /path/to/folder/file2 /path/to/folder/file1 ``` Note that `webkitdirectory` no longer exposes the path to the selected folder. If you require the path to the selected folder rather than the folder contents, see the `dialog.showOpenDialog` API ([link](api/dialog.md#dialogshowopendialogbrowserwindow-options)). ### API Changed: Callback-based versions of promisified APIs Electron 5 and Electron 6 introduced Promise-based versions of existing asynchronous APIs and deprecated their older, callback-based counterparts. In Electron 7, all deprecated callback-based APIs are now removed. These functions now only return Promises: * `app.getFileIcon()` [#15742](https://github.com/electron/electron/pull/15742) * `app.dock.show()` [#16904](https://github.com/electron/electron/pull/16904) * `contentTracing.getCategories()` [#16583](https://github.com/electron/electron/pull/16583) * `contentTracing.getTraceBufferUsage()` [#16600](https://github.com/electron/electron/pull/16600) * `contentTracing.startRecording()` [#16584](https://github.com/electron/electron/pull/16584) * `contentTracing.stopRecording()` [#16584](https://github.com/electron/electron/pull/16584) * `contents.executeJavaScript()` [#17312](https://github.com/electron/electron/pull/17312) * `cookies.flushStore()` [#16464](https://github.com/electron/electron/pull/16464) * `cookies.get()` [#16464](https://github.com/electron/electron/pull/16464) * `cookies.remove()` [#16464](https://github.com/electron/electron/pull/16464) * `cookies.set()` [#16464](https://github.com/electron/electron/pull/16464) * `debugger.sendCommand()` [#16861](https://github.com/electron/electron/pull/16861) * `dialog.showCertificateTrustDialog()` [#17181](https://github.com/electron/electron/pull/17181) * `inAppPurchase.getProducts()` [#17355](https://github.com/electron/electron/pull/17355) * `inAppPurchase.purchaseProduct()`[#17355](https://github.com/electron/electron/pull/17355) * `netLog.stopLogging()` [#16862](https://github.com/electron/electron/pull/16862) * `session.clearAuthCache()` [#17259](https://github.com/electron/electron/pull/17259) * `session.clearCache()` [#17185](https://github.com/electron/electron/pull/17185) * `session.clearHostResolverCache()` [#17229](https://github.com/electron/electron/pull/17229) * `session.clearStorageData()` [#17249](https://github.com/electron/electron/pull/17249) * `session.getBlobData()` [#17303](https://github.com/electron/electron/pull/17303) * `session.getCacheSize()` [#17185](https://github.com/electron/electron/pull/17185) * `session.resolveProxy()` [#17222](https://github.com/electron/electron/pull/17222) * `session.setProxy()` [#17222](https://github.com/electron/electron/pull/17222) * `shell.openExternal()` [#16176](https://github.com/electron/electron/pull/16176) * `webContents.loadFile()` [#15855](https://github.com/electron/electron/pull/15855) * `webContents.loadURL()` [#15855](https://github.com/electron/electron/pull/15855) * `webContents.hasServiceWorker()` [#16535](https://github.com/electron/electron/pull/16535) * `webContents.printToPDF()` [#16795](https://github.com/electron/electron/pull/16795) * `webContents.savePage()` [#16742](https://github.com/electron/electron/pull/16742) * `webFrame.executeJavaScript()` [#17312](https://github.com/electron/electron/pull/17312) * `webFrame.executeJavaScriptInIsolatedWorld()` [#17312](https://github.com/electron/electron/pull/17312) * `webviewTag.executeJavaScript()` [#17312](https://github.com/electron/electron/pull/17312) * `win.capturePage()` [#15743](https://github.com/electron/electron/pull/15743) These functions now have two forms, synchronous and Promise-based asynchronous: * `dialog.showMessageBox()`/`dialog.showMessageBoxSync()` [#17298](https://github.com/electron/electron/pull/17298) * `dialog.showOpenDialog()`/`dialog.showOpenDialogSync()` [#16973](https://github.com/electron/electron/pull/16973) * `dialog.showSaveDialog()`/`dialog.showSaveDialogSync()` [#17054](https://github.com/electron/electron/pull/17054) ## Planned Breaking API Changes (6.0) ### API Changed: `win.setMenu(null)` is now `win.removeMenu()` ```js // Deprecated win.setMenu(null) // Replace with win.removeMenu() ``` ### API Changed: `electron.screen` in the renderer process should be accessed via `remote` ```js // Deprecated require('electron').screen // Replace with require('electron').remote.screen ``` ### API Changed: `require()`ing node builtins in sandboxed renderers no longer implicitly loads the `remote` version ```js // Deprecated require('child_process') // Replace with require('electron').remote.require('child_process') // Deprecated require('fs') // Replace with require('electron').remote.require('fs') // Deprecated require('os') // Replace with require('electron').remote.require('os') // Deprecated require('path') // Replace with require('electron').remote.require('path') ``` ### Deprecated: `powerMonitor.querySystemIdleState` replaced with `powerMonitor.getSystemIdleState` ```js // Deprecated powerMonitor.querySystemIdleState(threshold, callback) // Replace with synchronous API const idleState = powerMonitor.getSystemIdleState(threshold) ``` ### Deprecated: `powerMonitor.querySystemIdleTime` replaced with `powerMonitor.getSystemIdleTime` ```js // Deprecated powerMonitor.querySystemIdleTime(callback) // Replace with synchronous API const idleTime = powerMonitor.getSystemIdleTime() ``` ### Deprecated: `app.enableMixedSandbox()` is no longer needed ```js // Deprecated app.enableMixedSandbox() ``` Mixed-sandbox mode is now enabled by default. ### Deprecated: `Tray.setHighlightMode` Under macOS Catalina our former Tray implementation breaks. Apple's native substitute doesn't support changing the highlighting behavior. ```js // Deprecated tray.setHighlightMode(mode) // API will be removed in v7.0 without replacement. ``` ## Planned Breaking API Changes (5.0) ### Default Changed: `nodeIntegration` and `webviewTag` default to false, `contextIsolation` defaults to true The following `webPreferences` option default values are deprecated in favor of the new defaults listed below. | Property | Deprecated Default | New Default | |----------|--------------------|-------------| | `contextIsolation` | `false` | `true` | | `nodeIntegration` | `true` | `false` | | `webviewTag` | `nodeIntegration` if set else `true` | `false` | E.g. Re-enabling the webviewTag ```js const w = new BrowserWindow({ webPreferences: { webviewTag: true } }) ``` ### Behavior Changed: `nodeIntegration` in child windows opened via `nativeWindowOpen` Child windows opened with the `nativeWindowOpen` option will always have Node.js integration disabled, unless `nodeIntegrationInSubFrames` is `true`. ### API Changed: Registering privileged schemes must now be done before app ready Renderer process APIs `webFrame.registerURLSchemeAsPrivileged` and `webFrame.registerURLSchemeAsBypassingCSP` as well as browser process API `protocol.registerStandardSchemes` have been removed. A new API, `protocol.registerSchemesAsPrivileged` has been added and should be used for registering custom schemes with the required privileges. Custom schemes are required to be registered before app ready. ### Deprecated: `webFrame.setIsolatedWorld*` replaced with `webFrame.setIsolatedWorldInfo` ```js // Deprecated webFrame.setIsolatedWorldContentSecurityPolicy(worldId, csp) webFrame.setIsolatedWorldHumanReadableName(worldId, name) webFrame.setIsolatedWorldSecurityOrigin(worldId, securityOrigin) // Replace with webFrame.setIsolatedWorldInfo( worldId, { securityOrigin: 'some_origin', name: 'human_readable_name', csp: 'content_security_policy' }) ``` ### API Changed: `webFrame.setSpellCheckProvider` now takes an asynchronous callback The `spellCheck` callback is now asynchronous, and `autoCorrectWord` parameter has been removed. ```js // Deprecated webFrame.setSpellCheckProvider('en-US', true, { spellCheck: (text) => { return !spellchecker.isMisspelled(text) } }) // Replace with webFrame.setSpellCheckProvider('en-US', { spellCheck: (words, callback) => { callback(words.filter(text => spellchecker.isMisspelled(text))) } }) ``` ### API Changed: `webContents.getZoomLevel` and `webContents.getZoomFactor` are now synchronous `webContents.getZoomLevel` and `webContents.getZoomFactor` no longer take callback parameters, instead directly returning their number values. ```js // Deprecated webContents.getZoomLevel((level) => { console.log(level) }) // Replace with const level = webContents.getZoomLevel() console.log(level) ``` ```js // Deprecated webContents.getZoomFactor((factor) => { console.log(factor) }) // Replace with const factor = webContents.getZoomFactor() console.log(factor) ``` ## Planned Breaking API Changes (4.0) The following list includes the breaking API changes made in Electron 4.0. ### `app.makeSingleInstance` ```js // Deprecated app.makeSingleInstance((argv, cwd) => { /* ... */ }) // Replace with app.requestSingleInstanceLock() app.on('second-instance', (event, argv, cwd) => { /* ... */ }) ``` ### `app.releaseSingleInstance` ```js // Deprecated app.releaseSingleInstance() // Replace with app.releaseSingleInstanceLock() ``` ### `app.getGPUInfo` ```js app.getGPUInfo('complete') // Now behaves the same with `basic` on macOS app.getGPUInfo('basic') ``` ### `win_delay_load_hook` When building native modules for windows, the `win_delay_load_hook` variable in the module's `binding.gyp` must be true (which is the default). If this hook is not present, then the native module will fail to load on Windows, with an error message like `Cannot find module`. See the [native module guide](/docs/tutorial/using-native-node-modules.md) for more. ## Breaking API Changes (3.0) The following list includes the breaking API changes in Electron 3.0. ### `app` ```js // Deprecated app.getAppMemoryInfo() // Replace with app.getAppMetrics() // Deprecated const metrics = app.getAppMetrics() const { memory } = metrics[0] // Deprecated property ``` ### `BrowserWindow` ```js // Deprecated const optionsA = { webPreferences: { blinkFeatures: '' } } const windowA = new BrowserWindow(optionsA) // Replace with const optionsB = { webPreferences: { enableBlinkFeatures: '' } } const windowB = new BrowserWindow(optionsB) // Deprecated window.on('app-command', (e, cmd) => { if (cmd === 'media-play_pause') { // do something } }) // Replace with window.on('app-command', (e, cmd) => { if (cmd === 'media-play-pause') { // do something } }) ``` ### `clipboard` ```js // Deprecated clipboard.readRtf() // Replace with clipboard.readRTF() // Deprecated clipboard.writeRtf() // Replace with clipboard.writeRTF() // Deprecated clipboard.readHtml() // Replace with clipboard.readHTML() // Deprecated clipboard.writeHtml() // Replace with clipboard.writeHTML() ``` ### `crashReporter` ```js // Deprecated crashReporter.start({ companyName: 'Crashly', submitURL: 'https://crash.server.com', autoSubmit: true }) // Replace with crashReporter.start({ companyName: 'Crashly', submitURL: 'https://crash.server.com', uploadToServer: true }) ``` ### `nativeImage` ```js // Deprecated nativeImage.createFromBuffer(buffer, 1.0) // Replace with nativeImage.createFromBuffer(buffer, { scaleFactor: 1.0 }) ``` ### `process` ```js // Deprecated const info = process.getProcessMemoryInfo() ``` ### `screen` ```js // Deprecated screen.getMenuBarHeight() // Replace with screen.getPrimaryDisplay().workArea ``` ### `session` ```js // Deprecated ses.setCertificateVerifyProc((hostname, certificate, callback) => { callback(true) }) // Replace with ses.setCertificateVerifyProc((request, callback) => { callback(0) }) ``` ### `Tray` ```js // Deprecated tray.setHighlightMode(true) // Replace with tray.setHighlightMode('on') // Deprecated tray.setHighlightMode(false) // Replace with tray.setHighlightMode('off') ``` ### `webContents` ```js // Deprecated webContents.openDevTools({ detach: true }) // Replace with webContents.openDevTools({ mode: 'detach' }) // Removed webContents.setSize(options) // There is no replacement for this API ``` ### `webFrame` ```js // Deprecated webFrame.registerURLSchemeAsSecure('app') // Replace with protocol.registerStandardSchemes(['app'], { secure: true }) // Deprecated webFrame.registerURLSchemeAsPrivileged('app', { secure: true }) // Replace with protocol.registerStandardSchemes(['app'], { secure: true }) ``` ### `<webview>` ```js // Removed webview.setAttribute('disableguestresize', '') // There is no replacement for this API // Removed webview.setAttribute('guestinstance', instanceId) // There is no replacement for this API // Keyboard listeners no longer work on webview tag webview.onkeydown = () => { /* handler */ } webview.onkeyup = () => { /* handler */ } ``` ### Node Headers URL This is the URL specified as `disturl` in a `.npmrc` file or as the `--dist-url` command line flag when building native Node modules. Deprecated: https://atom.io/download/atom-shell Replace with: https://atom.io/download/electron ## Breaking API Changes (2.0) The following list includes the breaking API changes made in Electron 2.0. ### `BrowserWindow` ```js // Deprecated const optionsA = { titleBarStyle: 'hidden-inset' } const windowA = new BrowserWindow(optionsA) // Replace with const optionsB = { titleBarStyle: 'hiddenInset' } const windowB = new BrowserWindow(optionsB) ``` ### `menu` ```js // Removed menu.popup(browserWindow, 100, 200, 2) // Replaced with menu.popup(browserWindow, { x: 100, y: 200, positioningItem: 2 }) ``` ### `nativeImage` ```js // Removed nativeImage.toPng() // Replaced with nativeImage.toPNG() // Removed nativeImage.toJpeg() // Replaced with nativeImage.toJPEG() ``` ### `process` * `process.versions.electron` and `process.version.chrome` will be made read-only properties for consistency with the other `process.versions` properties set by Node. ### `webContents` ```js // Removed webContents.setZoomLevelLimits(1, 2) // Replaced with webContents.setVisualZoomLevelLimits(1, 2) ``` ### `webFrame` ```js // Removed webFrame.setZoomLevelLimits(1, 2) // Replaced with webFrame.setVisualZoomLevelLimits(1, 2) ``` ### `<webview>` ```js // Removed webview.setZoomLevelLimits(1, 2) // Replaced with webview.setVisualZoomLevelLimits(1, 2) ``` ### Duplicate ARM Assets Each Electron release includes two identical ARM builds with slightly different filenames, like `electron-v1.7.3-linux-arm.zip` and `electron-v1.7.3-linux-armv7l.zip`. The asset with the `v7l` prefix was added to clarify to users which ARM version it supports, and to disambiguate it from future armv6l and arm64 assets that may be produced. The file _without the prefix_ is still being published to avoid breaking any setups that may be consuming it. Starting at 2.0, the unprefixed file will no longer be published. For details, see [6986](https://github.com/electron/electron/pull/6986) and [7189](https://github.com/electron/electron/pull/7189).
closed
electron/electron
https://github.com/electron/electron
33,806
[Bug]: clarify in Security document when contextIsolation should be enabled
### 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 Security [doc](https://www.electronjs.org/docs/latest/tutorial/security#3-enable-context-isolation-for-remote-content) states: >Enable Context Isolation for remote content Based on some of the discussion in [this issue](https://github.com/electron/electron/issues/23506) (specifically [here](https://github.com/electron/electron/issues/23506#issuecomment-922092517)), it sounds like Electron is recommending that we enable `contextIsolation` for *all* content, remote or local. Should the Sec doc be updated in that case? ### Proposed Solution Remove the bit about "remote content" from that section ### Alternatives Considered n/a ### Additional Information _No response_
https://github.com/electron/electron/issues/33806
https://github.com/electron/electron/pull/33807
5ae234d5e1d20bc9db5abb780d79b694a4ef09d7
2d0ad043542d99d28332127915b70084409b5786
2022-04-15T21:02:10Z
c++
2022-04-18T14:09:54Z
docs/tutorial/security.md
--- title: Security description: A set of guidelines for building secure Electron apps slug: security hide_title: true toc_max_heading_level: 3 --- # Security :::info Reporting security issues For information on how to properly disclose an Electron vulnerability, see [SECURITY.md](https://github.com/electron/electron/tree/main/SECURITY.md). For upstream Chromium vulnerabilities: Electron keeps up to date with alternating Chromium releases. For more information, see the [Electron Release Timelines](../tutorial/electron-timelines.md) document. ::: ## Preface As web developers, we usually enjoy the strong security net of the browser — the risks associated with the code we write are relatively small. Our websites are granted limited powers in a sandbox, and we trust that our users enjoy a browser built by a large team of engineers that is able to quickly respond to newly discovered security threats. When working with Electron, it is important to understand that Electron is not a web browser. It allows you to build feature-rich desktop applications with familiar web technologies, but your code wields much greater power. JavaScript can access the filesystem, user shell, and more. This allows you to build high quality native applications, but the inherent security risks scale with the additional powers granted to your code. With that in mind, be aware that displaying arbitrary content from untrusted sources poses a severe security risk that Electron is not intended to handle. In fact, the most popular Electron apps (Atom, Slack, Visual Studio Code, etc) display primarily local content (or trusted, secure remote content without Node integration) — if your application executes code from an online source, it is your responsibility to ensure that the code is not malicious. ## General guidelines ### Security is everyone's responsibility It is important to remember that the security of your Electron application is the result of the overall security of the framework foundation (*Chromium*, *Node.js*), Electron itself, all NPM dependencies and your code. As such, it is your responsibility to follow a few important best practices: * **Keep your application up-to-date with the latest Electron framework release.** When releasing your product, you’re also shipping a bundle composed of Electron, Chromium shared library and Node.js. Vulnerabilities affecting these components may impact the security of your application. By updating Electron to the latest version, you ensure that critical vulnerabilities (such as *nodeIntegration bypasses*) are already patched and cannot be exploited in your application. For more information, see "[Use a current version of Electron](#16-use-a-current-version-of-electron)". * **Evaluate your dependencies.** While NPM provides half a million reusable packages, it is your responsibility to choose trusted 3rd-party libraries. If you use outdated libraries affected by known vulnerabilities or rely on poorly maintained code, your application security could be in jeopardy. * **Adopt secure coding practices.** The first line of defense for your application is your own code. Common web vulnerabilities, such as Cross-Site Scripting (XSS), have a higher security impact on Electron applications hence it is highly recommended to adopt secure software development best practices and perform security testing. ### Isolation for untrusted content A security issue exists whenever you receive code from an untrusted source (e.g. a remote server) and execute it locally. As an example, consider a remote website being displayed inside a default [`BrowserWindow`][browser-window]. If an attacker somehow manages to change said content (either by attacking the source directly, or by sitting between your app and the actual destination), they will be able to execute native code on the user's machine. :::warning Under no circumstances should you load and execute remote code with Node.js integration enabled. Instead, use only local files (packaged together with your application) to execute Node.js code. To display remote content, use the [`<webview>`][webview-tag] tag or [`BrowserView`][browser-view], make sure to disable the `nodeIntegration` and enable `contextIsolation`. ::: :::info Electron security warnings Security warnings and recommendations are printed to the developer console. They only show up when the binary's name is Electron, indicating that a developer is currently looking at the console. You can force-enable or force-disable these warnings by setting `ELECTRON_ENABLE_SECURITY_WARNINGS` or `ELECTRON_DISABLE_SECURITY_WARNINGS` on either `process.env` or the `window` object. ::: ## Checklist: Security recommendations You should at least follow these steps to improve the security of your application: 1. [Only load secure content](#1-only-load-secure-content) 2. [Disable the Node.js integration in all renderers that display remote content](#2-do-not-enable-nodejs-integration-for-remote-content) 3. [Enable context isolation in all renderers that display remote content](#3-enable-context-isolation-for-remote-content) 4. [Enable process sandboxing](#4-enable-process-sandboxing) 5. [Use `ses.setPermissionRequestHandler()` in all sessions that load remote content](#5-handle-session-permission-requests-from-remote-content) 6. [Do not disable `webSecurity`](#6-do-not-disable-websecurity) 7. [Define a `Content-Security-Policy`](#7-define-a-content-security-policy) and use restrictive rules (i.e. `script-src 'self'`) 8. [Do not enable `allowRunningInsecureContent`](#8-do-not-enable-allowrunninginsecurecontent) 9. [Do not enable experimental features](#9-do-not-enable-experimental-features) 10. [Do not use `enableBlinkFeatures`](#10-do-not-use-enableblinkfeatures) 11. [`<webview>`: Do not use `allowpopups`](#11-do-not-use-allowpopups-for-webviews) 12. [`<webview>`: Verify options and params](#12-verify-webview-options-before-creation) 13. [Disable or limit navigation](#13-disable-or-limit-navigation) 14. [Disable or limit creation of new windows](#14-disable-or-limit-creation-of-new-windows) 15. [Do not use `shell.openExternal` with untrusted content](#15-do-not-use-shellopenexternal-with-untrusted-content) 16. [Use a current version of Electron](#16-use-a-current-version-of-electron) To automate the detection of misconfigurations and insecure patterns, it is possible to use [Electronegativity](https://github.com/doyensec/electronegativity). For additional details on potential weaknesses and implementation bugs when developing applications using Electron, please refer to this [guide for developers and auditors](https://doyensec.com/resources/us-17-Carettoni-Electronegativity-A-Study-Of-Electron-Security-wp.pdf). ### 1. Only load secure content Any resources not included with your application should be loaded using a secure protocol like `HTTPS`. In other words, do not use insecure protocols like `HTTP`. Similarly, we recommend the use of `WSS` over `WS`, `FTPS` over `FTP`, and so on. #### Why? `HTTPS` has three main benefits: 1. It authenticates the remote server, ensuring your app connects to the correct host instead of an impersonator. 1. It ensures data integrity, asserting that the data was not modified while in transit between your application and the host. 1. It encrypts the traffic between your user and the destination host, making it more difficult to eavesdrop on the information sent between your app and the host. #### How? ```js title='main.js (Main Process)' // Bad browserWindow.loadURL('http://example.com') // Good browserWindow.loadURL('https://example.com') ``` ```html title='index.html (Renderer Process)' <!-- Bad --> <script crossorigin src="http://example.com/react.js"></script> <link rel="stylesheet" href="http://example.com/style.css"> <!-- Good --> <script crossorigin src="https://example.com/react.js"></script> <link rel="stylesheet" href="https://example.com/style.css"> ``` ### 2. Do not enable Node.js integration for remote content :::info This recommendation is the default behavior in Electron since 5.0.0. ::: It is paramount that you do not enable Node.js integration in any renderer ([`BrowserWindow`][browser-window], [`BrowserView`][browser-view], or [`<webview>`][webview-tag]) that loads remote content. The goal is to limit the powers you grant to remote content, thus making it dramatically more difficult for an attacker to harm your users should they gain the ability to execute JavaScript on your website. After this, you can grant additional permissions for specific hosts. For example, if you are opening a BrowserWindow pointed at `https://example.com/`, you can give that website exactly the abilities it needs, but no more. #### Why? A cross-site-scripting (XSS) attack is more dangerous if an attacker can jump out of the renderer process and execute code on the user's computer. Cross-site-scripting attacks are fairly common - and while an issue, their power is usually limited to messing with the website that they are executed on. Disabling Node.js integration helps prevent an XSS from being escalated into a so-called "Remote Code Execution" (RCE) attack. #### How? ```js title='main.js (Main Process)' // Bad const mainWindow = new BrowserWindow({ webPreferences: { contextIsolation: false, nodeIntegration: true, nodeIntegrationInWorker: true } }) mainWindow.loadURL('https://example.com') ``` ```js title='main.js (Main Process)' // Good const mainWindow = new BrowserWindow({ webPreferences: { preload: path.join(app.getAppPath(), 'preload.js') } }) mainWindow.loadURL('https://example.com') ``` ```html title='index.html (Renderer Process)' <!-- Bad --> <webview nodeIntegration src="page.html"></webview> <!-- Good --> <webview src="page.html"></webview> ``` When disabling Node.js integration, you can still expose APIs to your website that do consume Node.js modules or features. Preload scripts continue to have access to `require` and other Node.js features, allowing developers to expose a custom API to remotely loaded content via the [contextBridge API](../api/context-bridge.md). ### 3. Enable Context Isolation for remote content :::info This recommendation is the default behavior in Electron since 12.0.0. ::: Context isolation is an Electron feature that allows developers to run code in preload scripts and in Electron APIs in a dedicated JavaScript context. In practice, that means that global objects like `Array.prototype.push` or `JSON.parse` cannot be modified by scripts running in the renderer process. Electron uses the same technology as Chromium's [Content Scripts](https://developer.chrome.com/extensions/content_scripts#execution-environment) to enable this behavior. Even when `nodeIntegration: false` is used, to truly enforce strong isolation and prevent the use of Node primitives `contextIsolation` **must** also be used. :::info For more information on what `contextIsolation` is and how to enable it please see our dedicated [Context Isolation](context-isolation.md) document. :::info ### 4. Enable process sandboxing [Sandboxing](https://chromium.googlesource.com/chromium/src/+/HEAD/docs/design/sandbox.md) is a Chromium feature that uses the operating system to significantly limit what renderer processes have access to. You should enable the sandbox in all renderers. Loading, reading or processing any untrusted content in an unsandboxed process, including the main process, is not advised. :::info For more information on what `contextIsolation` is and how to enable it please see our dedicated [Process Sandboxing](sandbox.md) document. :::info ### 5. Handle session permission requests from remote content You may have seen permission requests while using Chrome: they pop up whenever the website attempts to use a feature that the user has to manually approve ( like notifications). The API is based on the [Chromium permissions API](https://developer.chrome.com/extensions/permissions) and implements the same types of permissions. #### Why? By default, Electron will automatically approve all permission requests unless the developer has manually configured a custom handler. While a solid default, security-conscious developers might want to assume the very opposite. #### How? ```js title='main.js (Main Process)' const { session } = require('electron') const URL = require('url').URL session .fromPartition('some-partition') .setPermissionRequestHandler((webContents, permission, callback) => { const parsedUrl = new URL(webContents.getURL()) if (permission === 'notifications') { // Approves the permissions request callback(true) } // Verify URL if (parsedUrl.protocol !== 'https:' || parsedUrl.host !== 'example.com') { // Denies the permissions request return callback(false) } }) ``` ### 6. Do not disable `webSecurity` :::info This recommendation is Electron's default. ::: You may have already guessed that disabling the `webSecurity` property on a renderer process ([`BrowserWindow`][browser-window], [`BrowserView`][browser-view], or [`<webview>`][webview-tag]) disables crucial security features. Do not disable `webSecurity` in production applications. #### Why? Disabling `webSecurity` will disable the same-origin policy and set `allowRunningInsecureContent` property to `true`. In other words, it allows the execution of insecure code from different domains. #### How? ```js title='main.js (Main Process)' // Bad const mainWindow = new BrowserWindow({ webPreferences: { webSecurity: false } }) ``` ```js title='main.js (Main Process)' // Good const mainWindow = new BrowserWindow() ``` ```html title='index.html (Renderer Process)' <!-- Bad --> <webview disablewebsecurity src="page.html"></webview> <!-- Good --> <webview src="page.html"></webview> ``` ### 7. Define a Content Security Policy A Content Security Policy (CSP) is an additional layer of protection against cross-site-scripting attacks and data injection attacks. We recommend that they be enabled by any website you load inside Electron. #### Why? CSP allows the server serving content to restrict and control the resources Electron can load for that given web page. `https://example.com` should be allowed to load scripts from the origins you defined while scripts from `https://evil.attacker.com` should not be allowed to run. Defining a CSP is an easy way to improve your application's security. #### How? The following CSP will allow Electron to execute scripts from the current website and from `apis.example.com`. ```plaintext // Bad Content-Security-Policy: '*' // Good Content-Security-Policy: script-src 'self' https://apis.example.com ``` #### CSP HTTP headers Electron respects the [`Content-Security-Policy` HTTP header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy) which can be set using Electron's [`webRequest.onHeadersReceived`](../api/web-request.md#webrequestonheadersreceivedfilter-listener) handler: ```javascript title='main.js (Main Process)' const { session } = require('electron') session.defaultSession.webRequest.onHeadersReceived((details, callback) => { callback({ responseHeaders: { ...details.responseHeaders, 'Content-Security-Policy': ['default-src \'none\''] } }) }) ``` #### CSP meta tag CSP's preferred delivery mechanism is an HTTP header. However, it is not possible to use this method when loading a resource using the `file://` protocol. It can be useful in some cases to set a policy on a page directly in the markup using a `<meta>` tag: ```html title='index.html (Renderer Process)' <meta http-equiv="Content-Security-Policy" content="default-src 'none'"> ``` ### 8. Do not enable `allowRunningInsecureContent` :::info This recommendation is Electron's default. ::: By default, Electron will not allow websites loaded over `HTTPS` to load and execute scripts, CSS, or plugins from insecure sources (`HTTP`). Setting the property `allowRunningInsecureContent` to `true` disables that protection. Loading the initial HTML of a website over `HTTPS` and attempting to load subsequent resources via `HTTP` is also known as "mixed content". #### Why? Loading content over `HTTPS` assures the authenticity and integrity of the loaded resources while encrypting the traffic itself. See the section on [only displaying secure content](#1-only-load-secure-content) for more details. #### How? ```js title='main.js (Main Process)' // Bad const mainWindow = new BrowserWindow({ webPreferences: { allowRunningInsecureContent: true } }) ``` ```js title='main.js (Main Process)' // Good const mainWindow = new BrowserWindow({}) ``` ### 9. Do not enable experimental features :::info This recommendation is Electron's default. ::: Advanced users of Electron can enable experimental Chromium features using the `experimentalFeatures` property. #### Why? Experimental features are, as the name suggests, experimental and have not been enabled for all Chromium users. Furthermore, their impact on Electron as a whole has likely not been tested. Legitimate use cases exist, but unless you know what you are doing, you should not enable this property. #### How? ```js title='main.js (Main Process)' // Bad const mainWindow = new BrowserWindow({ webPreferences: { experimentalFeatures: true } }) ``` ```js title='main.js (Main Process)' // Good const mainWindow = new BrowserWindow({}) ``` ### 10. Do not use `enableBlinkFeatures` :::info This recommendation is Electron's default. ::: Blink is the name of the rendering engine behind Chromium. As with `experimentalFeatures`, the `enableBlinkFeatures` property allows developers to enable features that have been disabled by default. #### Why? Generally speaking, there are likely good reasons if a feature was not enabled by default. Legitimate use cases for enabling specific features exist. As a developer, you should know exactly why you need to enable a feature, what the ramifications are, and how it impacts the security of your application. Under no circumstances should you enable features speculatively. #### How? ```js title='main.js (Main Process)' // Bad const mainWindow = new BrowserWindow({ webPreferences: { enableBlinkFeatures: 'ExecCommandInJavaScript' } }) ``` ```js title='main.js (Main Process)' // Good const mainWindow = new BrowserWindow() ``` ### 11. Do not use `allowpopups` for WebViews :::info This recommendation is Electron's default. ::: If you are using [`<webview>`][webview-tag], you might need the pages and scripts loaded in your `<webview>` tag to open new windows. The `allowpopups` attribute enables them to create new [`BrowserWindows`][browser-window] using the `window.open()` method. `<webview>` tags are otherwise not allowed to create new windows. #### Why? If you do not need popups, you are better off not allowing the creation of new [`BrowserWindows`][browser-window] by default. This follows the principle of minimally required access: Don't let a website create new popups unless you know it needs that feature. #### How? ```html title='index.html (Renderer Process)' <!-- Bad --> <webview allowpopups src="page.html"></webview> <!-- Good --> <webview src="page.html"></webview> ``` ### 12. Verify WebView options before creation A WebView created in a renderer process that does not have Node.js integration enabled will not be able to enable integration itself. However, a WebView will always create an independent renderer process with its own `webPreferences`. It is a good idea to control the creation of new [`<webview>`][webview-tag] tags from the main process and to verify that their webPreferences do not disable security features. #### Why? Since `<webview>` live in the DOM, they can be created by a script running on your website even if Node.js integration is otherwise disabled. Electron enables developers to disable various security features that control a renderer process. In most cases, developers do not need to disable any of those features - and you should therefore not allow different configurations for newly created [`<webview>`][webview-tag] tags. #### How? Before a [`<webview>`][webview-tag] tag is attached, Electron will fire the `will-attach-webview` event on the hosting `webContents`. Use the event to prevent the creation of `webViews` with possibly insecure options. ```js title='main.js (Main Process)' app.on('web-contents-created', (event, contents) => { contents.on('will-attach-webview', (event, webPreferences, params) => { // Strip away preload scripts if unused or verify their location is legitimate delete webPreferences.preload // Disable Node.js integration webPreferences.nodeIntegration = false // Verify URL being loaded if (!params.src.startsWith('https://example.com/')) { event.preventDefault() } }) }) ``` Again, this list merely minimizes the risk, but does not remove it. If your goal is to display a website, a browser will be a more secure option. ### 13. Disable or limit navigation If your app has no need to navigate or only needs to navigate to known pages, it is a good idea to limit navigation outright to that known scope, disallowing any other kinds of navigation. #### Why? Navigation is a common attack vector. If an attacker can convince your app to navigate away from its current page, they can possibly force your app to open web sites on the Internet. Even if your `webContents` are configured to be more secure (like having `nodeIntegration` disabled or `contextIsolation` enabled), getting your app to open a random web site will make the work of exploiting your app a lot easier. A common attack pattern is that the attacker convinces your app's users to interact with the app in such a way that it navigates to one of the attacker's pages. This is usually done via links, plugins, or other user-generated content. #### How? If your app has no need for navigation, you can call `event.preventDefault()` in a [`will-navigate`][will-navigate] handler. If you know which pages your app might navigate to, check the URL in the event handler and only let navigation occur if it matches the URLs you're expecting. We recommend that you use Node's parser for URLs. Simple string comparisons can sometimes be fooled - a `startsWith('https://example.com')` test would let `https://example.com.attacker.com` through. ```js title='main.js (Main Process)' const URL = require('url').URL app.on('web-contents-created', (event, contents) => { contents.on('will-navigate', (event, navigationUrl) => { const parsedUrl = new URL(navigationUrl) if (parsedUrl.origin !== 'https://example.com') { event.preventDefault() } }) }) ``` ### 14. Disable or limit creation of new windows If you have a known set of windows, it's a good idea to limit the creation of additional windows in your app. #### Why? Much like navigation, the creation of new `webContents` is a common attack vector. Attackers attempt to convince your app to create new windows, frames, or other renderer processes with more privileges than they had before; or with pages opened that they couldn't open before. If you have no need to create windows in addition to the ones you know you'll need to create, disabling the creation buys you a little bit of extra security at no cost. This is commonly the case for apps that open one `BrowserWindow` and do not need to open an arbitrary number of additional windows at runtime. #### How? [`webContents`][web-contents] will delegate to its [window open handler][window-open-handler] before creating new windows. The handler will receive, amongst other parameters, the `url` the window was requested to open and the options used to create it. We recommend that you register a handler to monitor the creation of windows, and deny any unexpected window creation. ```js title='main.js (Main Process)' const { shell } = require('electron') app.on('web-contents-created', (event, contents) => { contents.setWindowOpenHandler(({ url }) => { // In this example, we'll ask the operating system // to open this event's url in the default browser. // // See the following item for considerations regarding what // URLs should be allowed through to shell.openExternal. if (isSafeForExternalOpen(url)) { setImmediate(() => { shell.openExternal(url) }) } return { action: 'deny' } }) }) ``` ### 15. Do not use `shell.openExternal` with untrusted content The shell module's [`openExternal`][open-external] API allows opening a given protocol URI with the desktop's native utilities. On macOS, for instance, this function is similar to the `open` terminal command utility and will open the specific application based on the URI and filetype association. #### Why? Improper use of [`openExternal`][open-external] can be leveraged to compromise the user's host. When openExternal is used with untrusted content, it can be leveraged to execute arbitrary commands. #### How? ```js title='main.js (Main Process)' // Bad const { shell } = require('electron') shell.openExternal(USER_CONTROLLED_DATA_HERE) ``` ```js title='main.js (Main Process)' // Good const { shell } = require('electron') shell.openExternal('https://example.com/index.html') ``` ### 16. Use a current version of Electron You should strive for always using the latest available version of Electron. Whenever a new major version is released, you should attempt to update your app as quickly as possible. #### Why? An application built with an older version of Electron, Chromium, and Node.js is an easier target than an application that is using more recent versions of those components. Generally speaking, security issues and exploits for older versions of Chromium and Node.js are more widely available. Both Chromium and Node.js are impressive feats of engineering built by thousands of talented developers. Given their popularity, their security is carefully tested and analyzed by equally skilled security researchers. Many of those researchers [disclose vulnerabilities responsibly][responsible-disclosure], which generally means that researchers will give Chromium and Node.js some time to fix issues before publishing them. Your application will be more secure if it is running a recent version of Electron (and thus, Chromium and Node.js) for which potential security issues are not as widely known. #### How? Migrate your app one major version at a time, while referring to Electron's [Breaking Changes][breaking-changes] document to see if any code needs to be updated. ### 17. Validate the `sender` of all IPC messages You should always validate incoming IPC messages `sender` property to ensure you aren't performing actions or sending information to untrusted renderers. #### Why? All Web Frames can in theory send IPC messages to the main process, including iframes and child windows in some scenarios. If you have an IPC message that returns user data to the sender via `event.reply` or performs privileged actions that the renderer can't natively, you should ensure you aren't listening to third party web frames. You should be validating the `sender` of **all** IPC messages by default. #### How? ```js title='main.js (Main Process)' // Bad ipcMain.handle('get-secrets', () => { return getSecrets(); }); // Good ipcMain.handle('get-secrets', (e) => { if (!validateSender(e.senderFrame)) return null; return getSecrets(); }); function validateSender(frame) { // Value the host of the URL using an actual URL parser and an allowlist if ((new URL(frame.url)).host === 'electronjs.org') return true; return false; } ``` [breaking-changes]: ../breaking-changes.md [browser-window]: ../api/browser-window.md [browser-view]: ../api/browser-view.md [webview-tag]: ../api/webview-tag.md [web-contents]: ../api/web-contents.md [window-open-handler]: ../api/web-contents.md#contentssetwindowopenhandlerhandler [will-navigate]: ../api/web-contents.md#event-will-navigate [open-external]: ../api/shell.md#shellopenexternalurl-options [responsible-disclosure]: https://en.wikipedia.org/wiki/Responsible_disclosure
closed
electron/electron
https://github.com/electron/electron
33,693
[Bug]: Electron crashes if Narrator is open and <img> without alt= is shown
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 18.0.3 (also 18.0.0-beta.1, 19.0.0-alpha.1, 20.0.0-nightly.20220411) ### What operating system are you using? Windows ### Operating System Version Windows 11 Pro version 21H2 build 22000.593 ### What arch are you using? x64 ### Last Known Working Electron version 17.4.0 (also 18.0.0-alpha.5) ### Expected Behavior 1. Press <kbd>⊞ Win</kbd>+<kbd>Ctrl</kbd>+<kbd>Enter</kbd> to start Windows Narrator. 2. Start [this fiddle](https://gist.github.com/4d0c8b4e45baa84cc152ef7a545dcd98), which just displays `<img src="https://…/icon.png" />`. 3. Electron should not crash. ### Actual Behavior 3. Electron crashes on start. ### Testcase Gist URL https://gist.github.com/4d0c8b4e45baa84cc152ef7a545dcd98 ### Additional Information I believe this is the crash that was supposed to be fixed by - #33614 but although that was backported in 18.0.2 (#33616), the crash is evidently not fixed. Cc @MarshallOfSound.
https://github.com/electron/electron/issues/33693
https://github.com/electron/electron/pull/33840
31c2b5703a75a5ff2bf0e68f472d9002fe866bfb
841e0a4e0ccae2b9fdac3944f7db1f23cb6a3c0a
2022-04-10T07:32:10Z
c++
2022-04-20T03:00:51Z
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/content/app/resources/content_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", "//content/app/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/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/content/dev_ui_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", "$root_gen_dir/ui/resources/webui_resources.pak", "$target_gen_dir/electron_resources.pak", ] deps = [ "//chrome/browser:dev_ui_browser_resources", "//chrome/browser:resources", "//chrome/common:resources", "//components/resources", "//content:content_resources", "//content:dev_ui_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_generated_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/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}/services/strings/services_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: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", "//services/strings", "//third_party/blink/public/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
33,693
[Bug]: Electron crashes if Narrator is open and <img> without alt= is shown
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 18.0.3 (also 18.0.0-beta.1, 19.0.0-alpha.1, 20.0.0-nightly.20220411) ### What operating system are you using? Windows ### Operating System Version Windows 11 Pro version 21H2 build 22000.593 ### What arch are you using? x64 ### Last Known Working Electron version 17.4.0 (also 18.0.0-alpha.5) ### Expected Behavior 1. Press <kbd>⊞ Win</kbd>+<kbd>Ctrl</kbd>+<kbd>Enter</kbd> to start Windows Narrator. 2. Start [this fiddle](https://gist.github.com/4d0c8b4e45baa84cc152ef7a545dcd98), which just displays `<img src="https://…/icon.png" />`. 3. Electron should not crash. ### Actual Behavior 3. Electron crashes on start. ### Testcase Gist URL https://gist.github.com/4d0c8b4e45baa84cc152ef7a545dcd98 ### Additional Information I believe this is the crash that was supposed to be fixed by - #33614 but although that was backported in 18.0.2 (#33616), the crash is evidently not fixed. Cc @MarshallOfSound.
https://github.com/electron/electron/issues/33693
https://github.com/electron/electron/pull/33840
31c2b5703a75a5ff2bf0e68f472d9002fe866bfb
841e0a4e0ccae2b9fdac3944f7db1f23cb6a3c0a
2022-04-10T07:32:10Z
c++
2022-04-20T03:00:51Z
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/content/app/resources/content_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", "//content/app/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/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/content/dev_ui_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", "$root_gen_dir/ui/resources/webui_resources.pak", "$target_gen_dir/electron_resources.pak", ] deps = [ "//chrome/browser:dev_ui_browser_resources", "//chrome/browser:resources", "//chrome/common:resources", "//components/resources", "//content:content_resources", "//content:dev_ui_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_generated_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/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}/services/strings/services_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: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", "//services/strings", "//third_party/blink/public/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
33,725
[Bug]: child_process.spawn error with cwd option
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.0.0-alpha.1 ### What operating system are you using? macOS ### Operating System Version 12.3.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version seems no ### Expected Behavior the code on below shold not throw ENOENT error because the `ping` command is in `/sbin/ping` ```js require("child_process").spawn(`./ping`, ["google.com"], { cwd: "/sbin", }); ``` ### Actual Behavior ```js equire("child_process").spawn(`./ping`, ["google.com"], { cwd: "/sbin", }); ``` the code above failed and the `ping` process is running in background.. then I try to join cwd with command like this: ```js require("child_process").spawn(`/sbin/ping`, ["google.com"]); ``` and it works ### Testcase Gist URL https://gist.github.com/Fndroid/346e81548c2e59510f53794538fcefd4 ### Additional Information Testcase output in devtool <img width="839" alt="image" src="https://user-images.githubusercontent.com/16091562/162930759-51be1189-2505-49cb-ad83-3cde5746e913.png">
https://github.com/electron/electron/issues/33725
https://github.com/electron/electron/pull/33815
b53118ca28bcc9dcff3304f33d7c576a82b3f298
00021a41b1905cbee93e775958c4fb50d473cda4
2022-04-12T09:40:42Z
c++
2022-04-21T01: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 chore_read_nobrowserglobals_from_global_not_process.patch enable_31_bit_smis_on_64bit_arch_and_ptr_compression.patch fix_handle_boringssl_and_openssl_incompatibilities.patch fix_add_v8_enable_reverse_jsargs_defines_in_common_gypi.patch fix_allow_preventing_initializeinspector_in_env.patch src_allow_embedders_to_provide_a_custom_pageallocator_to.patch fix_crypto_tests_to_run_with_bssl.patch fix_account_for_debugger_agent_race_condition.patch repl_fix_crash_when_sharedarraybuffer_disabled.patch fix_readbarrier_undefined_symbol_error_on_woa_arm64.patch chore_fix_-wimplicit-fallthrough.patch fix_crash_caused_by_gethostnamew_on_windows_7.patch fix_suppress_clang_-wdeprecated-declarations_in_libuv.patch fix_don_t_create_console_window_when_creating_process.patch fix_serdes_test.patch darwin_remove_eprototype_error_workaround_3405.patch darwin_translate_eprototype_to_econnreset_3413.patch darwin_bump_minimum_supported_version_to_10_15_3406.patch fix_failing_node_js_test_on_outdated.patch be_compatible_with_cppgc.patch feat_add_knostartdebugsignalhandler_to_environment_to_prevent.patch worker_thread_add_asar_support.patch process_monitor_for_exit_with_kqueue_on_bsds_3441.patch process_bsd_handle_kevent_note_exit_failure_3451.patch reland_macos_use_posix_spawn_instead_of_fork_3257.patch process_reset_the_signal_mask_if_the_fork_fails_3537.patch process_only_use_f_dupfd_cloexec_if_it_is_defined_3512.patch unix_simplify_uv_cloexec_fcntl_3492.patch unix_remove_uv_cloexec_ioctl_3515.patch process_simplify_uv_write_int_calls_3519.patch macos_don_t_use_thread-unsafe_strtok_3524.patch process_fix_hang_after_note_exit_3521.patch feat_add_uv_loop_interrupt_on_io_change_option_to_uv_loop_configure.patch fix_preserve_proper_method_names_as-is_in_error_stack.patch
closed
electron/electron
https://github.com/electron/electron
33,725
[Bug]: child_process.spawn error with cwd option
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.0.0-alpha.1 ### What operating system are you using? macOS ### Operating System Version 12.3.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version seems no ### Expected Behavior the code on below shold not throw ENOENT error because the `ping` command is in `/sbin/ping` ```js require("child_process").spawn(`./ping`, ["google.com"], { cwd: "/sbin", }); ``` ### Actual Behavior ```js equire("child_process").spawn(`./ping`, ["google.com"], { cwd: "/sbin", }); ``` the code above failed and the `ping` process is running in background.. then I try to join cwd with command like this: ```js require("child_process").spawn(`/sbin/ping`, ["google.com"]); ``` and it works ### Testcase Gist URL https://gist.github.com/Fndroid/346e81548c2e59510f53794538fcefd4 ### Additional Information Testcase output in devtool <img width="839" alt="image" src="https://user-images.githubusercontent.com/16091562/162930759-51be1189-2505-49cb-ad83-3cde5746e913.png">
https://github.com/electron/electron/issues/33725
https://github.com/electron/electron/pull/33815
b53118ca28bcc9dcff3304f33d7c576a82b3f298
00021a41b1905cbee93e775958c4fb50d473cda4
2022-04-12T09:40:42Z
c++
2022-04-21T01:38:47Z
patches/node/macos_avoid_posix_spawnp_cwd_bug_3597.patch
closed
electron/electron
https://github.com/electron/electron
33,725
[Bug]: child_process.spawn error with cwd option
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.0.0-alpha.1 ### What operating system are you using? macOS ### Operating System Version 12.3.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version seems no ### Expected Behavior the code on below shold not throw ENOENT error because the `ping` command is in `/sbin/ping` ```js require("child_process").spawn(`./ping`, ["google.com"], { cwd: "/sbin", }); ``` ### Actual Behavior ```js equire("child_process").spawn(`./ping`, ["google.com"], { cwd: "/sbin", }); ``` the code above failed and the `ping` process is running in background.. then I try to join cwd with command like this: ```js require("child_process").spawn(`/sbin/ping`, ["google.com"]); ``` and it works ### Testcase Gist URL https://gist.github.com/Fndroid/346e81548c2e59510f53794538fcefd4 ### Additional Information Testcase output in devtool <img width="839" alt="image" src="https://user-images.githubusercontent.com/16091562/162930759-51be1189-2505-49cb-ad83-3cde5746e913.png">
https://github.com/electron/electron/issues/33725
https://github.com/electron/electron/pull/33815
b53118ca28bcc9dcff3304f33d7c576a82b3f298
00021a41b1905cbee93e775958c4fb50d473cda4
2022-04-12T09:40:42Z
c++
2022-04-21T01: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 chore_read_nobrowserglobals_from_global_not_process.patch enable_31_bit_smis_on_64bit_arch_and_ptr_compression.patch fix_handle_boringssl_and_openssl_incompatibilities.patch fix_add_v8_enable_reverse_jsargs_defines_in_common_gypi.patch fix_allow_preventing_initializeinspector_in_env.patch src_allow_embedders_to_provide_a_custom_pageallocator_to.patch fix_crypto_tests_to_run_with_bssl.patch fix_account_for_debugger_agent_race_condition.patch repl_fix_crash_when_sharedarraybuffer_disabled.patch fix_readbarrier_undefined_symbol_error_on_woa_arm64.patch chore_fix_-wimplicit-fallthrough.patch fix_crash_caused_by_gethostnamew_on_windows_7.patch fix_suppress_clang_-wdeprecated-declarations_in_libuv.patch fix_don_t_create_console_window_when_creating_process.patch fix_serdes_test.patch darwin_remove_eprototype_error_workaround_3405.patch darwin_translate_eprototype_to_econnreset_3413.patch darwin_bump_minimum_supported_version_to_10_15_3406.patch fix_failing_node_js_test_on_outdated.patch be_compatible_with_cppgc.patch feat_add_knostartdebugsignalhandler_to_environment_to_prevent.patch worker_thread_add_asar_support.patch process_monitor_for_exit_with_kqueue_on_bsds_3441.patch process_bsd_handle_kevent_note_exit_failure_3451.patch reland_macos_use_posix_spawn_instead_of_fork_3257.patch process_reset_the_signal_mask_if_the_fork_fails_3537.patch process_only_use_f_dupfd_cloexec_if_it_is_defined_3512.patch unix_simplify_uv_cloexec_fcntl_3492.patch unix_remove_uv_cloexec_ioctl_3515.patch process_simplify_uv_write_int_calls_3519.patch macos_don_t_use_thread-unsafe_strtok_3524.patch process_fix_hang_after_note_exit_3521.patch feat_add_uv_loop_interrupt_on_io_change_option_to_uv_loop_configure.patch fix_preserve_proper_method_names_as-is_in_error_stack.patch
closed
electron/electron
https://github.com/electron/electron
33,725
[Bug]: child_process.spawn error with cwd option
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.0.0-alpha.1 ### What operating system are you using? macOS ### Operating System Version 12.3.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version seems no ### Expected Behavior the code on below shold not throw ENOENT error because the `ping` command is in `/sbin/ping` ```js require("child_process").spawn(`./ping`, ["google.com"], { cwd: "/sbin", }); ``` ### Actual Behavior ```js equire("child_process").spawn(`./ping`, ["google.com"], { cwd: "/sbin", }); ``` the code above failed and the `ping` process is running in background.. then I try to join cwd with command like this: ```js require("child_process").spawn(`/sbin/ping`, ["google.com"]); ``` and it works ### Testcase Gist URL https://gist.github.com/Fndroid/346e81548c2e59510f53794538fcefd4 ### Additional Information Testcase output in devtool <img width="839" alt="image" src="https://user-images.githubusercontent.com/16091562/162930759-51be1189-2505-49cb-ad83-3cde5746e913.png">
https://github.com/electron/electron/issues/33725
https://github.com/electron/electron/pull/33815
b53118ca28bcc9dcff3304f33d7c576a82b3f298
00021a41b1905cbee93e775958c4fb50d473cda4
2022-04-12T09:40:42Z
c++
2022-04-21T01:38:47Z
patches/node/macos_avoid_posix_spawnp_cwd_bug_3597.patch
closed
electron/electron
https://github.com/electron/electron
33,909
[Bug]: `setJumpList` declares `void` return type but should be `string`?
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.x ### 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 The docs of https://github.com/electron/electron/blob/17-x-y/docs/api/app.md#appsetjumplistcategories-windows say: > Sets or removes a custom Jump List for the application, and returns one of the following strings... However in the `electron.d.ts`, the return type is `void`: ```ts setJumpList(categories: (JumpListCategory[]) | (null)): void; ``` The expected signature is: ```ts setJumpList(categories: (JumpListCategory[]) | (null)): 'ok' | 'error' | 'invalidSeparatorError' | 'fileTypeRegistrationError' | 'customCategoryAccessDeniedError'; ``` ### Actual Behavior The `void` type is the wrong return type. ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/33909
https://github.com/electron/electron/pull/33910
15c931201ab880de84009baa59b9bc5923e1ef67
b5297ea8e2380b9174c26d5a35b1a73c2c9566d0
2022-04-25T04:46:01Z
c++
2022-04-28T10:15:23Z
docs/api/app.md
# app > Control your application's event lifecycle. Process: [Main](../glossary.md#main-process) The following example shows how to quit the application when the last window is closed: ```javascript const { app } = require('electron') app.on('window-all-closed', () => { app.quit() }) ``` ## Events The `app` object emits the following events: ### Event: 'will-finish-launching' Emitted when the application has finished basic startup. On Windows and Linux, the `will-finish-launching` event is the same as the `ready` event; on macOS, this event represents the `applicationWillFinishLaunching` notification of `NSApplication`. You would usually set up listeners for the `open-file` and `open-url` events here, and start the crash reporter and auto updater. In most cases, you should do everything in the `ready` event handler. ### Event: 'ready' Returns: * `event` Event * `launchInfo` Record<string, any> | [NotificationResponse](structures/notification-response.md) _macOS_ Emitted once, when Electron has finished initializing. On macOS, `launchInfo` holds the `userInfo` of the [`NSUserNotification`](https://developer.apple.com/documentation/foundation/nsusernotification) or information from [`UNNotificationResponse`](https://developer.apple.com/documentation/usernotifications/unnotificationresponse) that was used to open the application, if it was launched from Notification Center. You can also call `app.isReady()` to check if this event has already fired and `app.whenReady()` to get a Promise that is fulfilled when Electron is initialized. ### Event: 'window-all-closed' Emitted when all windows have been closed. If you do not subscribe to this event and all windows are closed, the default behavior is to quit the app; however, if you subscribe, you control whether the app quits or not. If the user pressed `Cmd + Q`, or the developer called `app.quit()`, Electron will first try to close all the windows and then emit the `will-quit` event, and in this case the `window-all-closed` event would not be emitted. ### Event: 'before-quit' Returns: * `event` Event Emitted before the application starts closing its windows. Calling `event.preventDefault()` will prevent the default behavior, which is terminating the application. **Note:** If application quit was initiated by `autoUpdater.quitAndInstall()`, then `before-quit` is emitted *after* emitting `close` event on all windows and closing them. **Note:** On Windows, this event will not be emitted if the app is closed due to a shutdown/restart of the system or a user logout. ### Event: 'will-quit' Returns: * `event` Event Emitted when all windows have been closed and the application will quit. Calling `event.preventDefault()` will prevent the default behavior, which is terminating the application. See the description of the `window-all-closed` event for the differences between the `will-quit` and `window-all-closed` events. **Note:** On Windows, this event will not be emitted if the app is closed due to a shutdown/restart of the system or a user logout. ### Event: 'quit' Returns: * `event` Event * `exitCode` Integer Emitted when the application is quitting. **Note:** On Windows, this event will not be emitted if the app is closed due to a shutdown/restart of the system or a user logout. ### Event: 'open-file' _macOS_ Returns: * `event` Event * `path` string Emitted when the user wants to open a file with the application. The `open-file` event is usually emitted when the application is already open and the OS wants to reuse the application to open the file. `open-file` is also emitted when a file is dropped onto the dock and the application is not yet running. Make sure to listen for the `open-file` event very early in your application startup to handle this case (even before the `ready` event is emitted). You should call `event.preventDefault()` if you want to handle this event. On Windows, you have to parse `process.argv` (in the main process) to get the filepath. ### Event: 'open-url' _macOS_ Returns: * `event` Event * `url` string Emitted when the user wants to open a URL with the application. Your application's `Info.plist` file must define the URL scheme within the `CFBundleURLTypes` key, and set `NSPrincipalClass` to `AtomApplication`. You should call `event.preventDefault()` if you want to handle this event. ### Event: 'activate' _macOS_ Returns: * `event` Event * `hasVisibleWindows` boolean Emitted when the application is activated. Various actions can trigger this event, such as launching the application for the first time, attempting to re-launch the application when it's already running, or clicking on the application's dock or taskbar icon. ### Event: 'did-become-active' _macOS_ Returns: * `event` Event Emitted when mac application become active. Difference from `activate` event is that `did-become-active` is emitted every time the app becomes active, not only when Dock icon is clicked or application is re-launched. ### Event: 'continue-activity' _macOS_ Returns: * `event` Event * `type` string - A string identifying the activity. Maps to [`NSUserActivity.activityType`][activity-type]. * `userInfo` unknown - Contains app-specific state stored by the activity on another device. * `details` Object * `webpageURL` string (optional) - A string identifying the URL of the webpage accessed by the activity on another device, if available. Emitted during [Handoff][handoff] when an activity from a different device wants to be resumed. You should call `event.preventDefault()` if you want to handle this event. A user activity can be continued only in an app that has the same developer Team ID as the activity's source app and that supports the activity's type. Supported activity types are specified in the app's `Info.plist` under the `NSUserActivityTypes` key. ### Event: 'will-continue-activity' _macOS_ Returns: * `event` Event * `type` string - A string identifying the activity. Maps to [`NSUserActivity.activityType`][activity-type]. Emitted during [Handoff][handoff] before an activity from a different device wants to be resumed. You should call `event.preventDefault()` if you want to handle this event. ### Event: 'continue-activity-error' _macOS_ Returns: * `event` Event * `type` string - A string identifying the activity. Maps to [`NSUserActivity.activityType`][activity-type]. * `error` string - A string with the error's localized description. Emitted during [Handoff][handoff] when an activity from a different device fails to be resumed. ### Event: 'activity-was-continued' _macOS_ Returns: * `event` Event * `type` string - A string identifying the activity. Maps to [`NSUserActivity.activityType`][activity-type]. * `userInfo` unknown - Contains app-specific state stored by the activity. Emitted during [Handoff][handoff] after an activity from this device was successfully resumed on another one. ### Event: 'update-activity-state' _macOS_ Returns: * `event` Event * `type` string - A string identifying the activity. Maps to [`NSUserActivity.activityType`][activity-type]. * `userInfo` unknown - Contains app-specific state stored by the activity. Emitted when [Handoff][handoff] is about to be resumed on another device. If you need to update the state to be transferred, you should call `event.preventDefault()` immediately, construct a new `userInfo` dictionary and call `app.updateCurrentActivity()` in a timely manner. Otherwise, the operation will fail and `continue-activity-error` will be called. ### Event: 'new-window-for-tab' _macOS_ Returns: * `event` Event Emitted when the user clicks the native macOS new tab button. The new tab button is only visible if the current `BrowserWindow` has a `tabbingIdentifier` ### Event: 'browser-window-blur' Returns: * `event` Event * `window` [BrowserWindow](browser-window.md) Emitted when a [browserWindow](browser-window.md) gets blurred. ### Event: 'browser-window-focus' Returns: * `event` Event * `window` [BrowserWindow](browser-window.md) Emitted when a [browserWindow](browser-window.md) gets focused. ### Event: 'browser-window-created' Returns: * `event` Event * `window` [BrowserWindow](browser-window.md) Emitted when a new [browserWindow](browser-window.md) is created. ### Event: 'web-contents-created' Returns: * `event` Event * `webContents` [WebContents](web-contents.md) Emitted when a new [webContents](web-contents.md) is created. ### Event: 'certificate-error' Returns: * `event` Event * `webContents` [WebContents](web-contents.md) * `url` string * `error` string - The error code * `certificate` [Certificate](structures/certificate.md) * `callback` Function * `isTrusted` boolean - Whether to consider the certificate as trusted * `isMainFrame` boolean Emitted when failed to verify the `certificate` for `url`, to trust the certificate you should prevent the default behavior with `event.preventDefault()` and call `callback(true)`. ```javascript const { app } = require('electron') app.on('certificate-error', (event, webContents, url, error, certificate, callback) => { if (url === 'https://github.com') { // Verification logic. event.preventDefault() callback(true) } else { callback(false) } }) ``` ### Event: 'select-client-certificate' Returns: * `event` Event * `webContents` [WebContents](web-contents.md) * `url` URL * `certificateList` [Certificate[]](structures/certificate.md) * `callback` Function * `certificate` [Certificate](structures/certificate.md) (optional) Emitted when a client certificate is requested. The `url` corresponds to the navigation entry requesting the client certificate and `callback` can be called with an entry filtered from the list. Using `event.preventDefault()` prevents the application from using the first certificate from the store. ```javascript const { app } = require('electron') app.on('select-client-certificate', (event, webContents, url, list, callback) => { event.preventDefault() callback(list[0]) }) ``` ### Event: 'login' Returns: * `event` Event * `webContents` [WebContents](web-contents.md) * `authenticationResponseDetails` Object * `url` URL * `authInfo` Object * `isProxy` boolean * `scheme` string * `host` string * `port` Integer * `realm` string * `callback` Function * `username` string (optional) * `password` string (optional) Emitted when `webContents` wants to do basic auth. The default behavior is to cancel all authentications. To override this you should prevent the default behavior with `event.preventDefault()` and call `callback(username, password)` with the credentials. ```javascript const { app } = require('electron') app.on('login', (event, webContents, details, authInfo, callback) => { event.preventDefault() callback('username', 'secret') }) ``` If `callback` is called without a username or password, the authentication request will be cancelled and the authentication error will be returned to the page. ### Event: 'gpu-info-update' Emitted whenever there is a GPU info update. ### Event: 'gpu-process-crashed' _Deprecated_ Returns: * `event` Event * `killed` boolean Emitted when the GPU process crashes or is killed. **Deprecated:** This event is superceded by the `child-process-gone` event which contains more information about why the child process disappeared. It isn't always because it crashed. The `killed` boolean can be replaced by checking `reason === 'killed'` when you switch to that event. ### Event: 'renderer-process-crashed' _Deprecated_ Returns: * `event` Event * `webContents` [WebContents](web-contents.md) * `killed` boolean Emitted when the renderer process of `webContents` crashes or is killed. **Deprecated:** This event is superceded by the `render-process-gone` event which contains more information about why the render process disappeared. It isn't always because it crashed. The `killed` boolean can be replaced by checking `reason === 'killed'` when you switch to that event. ### Event: 'render-process-gone' Returns: * `event` Event * `webContents` [WebContents](web-contents.md) * `details` Object * `reason` string - The reason the render process is gone. Possible values: * `clean-exit` - Process exited with an exit code of zero * `abnormal-exit` - Process exited with a non-zero exit code * `killed` - Process was sent a SIGTERM or otherwise killed externally * `crashed` - Process crashed * `oom` - Process ran out of memory * `launch-failed` - Process never successfully launched * `integrity-failure` - Windows code integrity checks failed * `exitCode` Integer - The exit code of the process, unless `reason` is `launch-failed`, in which case `exitCode` will be a platform-specific launch failure error code. Emitted when the renderer process unexpectedly disappears. This is normally because it was crashed or killed. ### Event: 'child-process-gone' Returns: * `event` Event * `details` Object * `type` string - Process type. One of the following values: * `Utility` * `Zygote` * `Sandbox helper` * `GPU` * `Pepper Plugin` * `Pepper Plugin Broker` * `Unknown` * `reason` string - The reason the child process is gone. Possible values: * `clean-exit` - Process exited with an exit code of zero * `abnormal-exit` - Process exited with a non-zero exit code * `killed` - Process was sent a SIGTERM or otherwise killed externally * `crashed` - Process crashed * `oom` - Process ran out of memory * `launch-failed` - Process never successfully launched * `integrity-failure` - Windows code integrity checks failed * `exitCode` number - The exit code for the process (e.g. status from waitpid if on posix, from GetExitCodeProcess on Windows). * `serviceName` string (optional) - The non-localized name of the process. * `name` string (optional) - The name of the process. Examples for utility: `Audio Service`, `Content Decryption Module Service`, `Network Service`, `Video Capture`, etc. Emitted when the child process unexpectedly disappears. This is normally because it was crashed or killed. It does not include renderer processes. ### Event: 'accessibility-support-changed' _macOS_ _Windows_ Returns: * `event` Event * `accessibilitySupportEnabled` boolean - `true` when Chrome's accessibility support is enabled, `false` otherwise. Emitted when Chrome's accessibility support changes. This event fires when assistive technologies, such as screen readers, are enabled or disabled. See https://www.chromium.org/developers/design-documents/accessibility for more details. ### Event: 'session-created' Returns: * `session` [Session](session.md) Emitted when Electron has created a new `session`. ```javascript const { app } = require('electron') app.on('session-created', (session) => { console.log(session) }) ``` ### Event: 'second-instance' Returns: * `event` Event * `argv` string[] - An array of the second instance's command line arguments * `workingDirectory` string - The second instance's working directory * `additionalData` unknown - A JSON object of additional data passed from the second instance * `ackCallback` unknown - A function that can be used to send data back to the second instance This event will be emitted inside the primary instance of your application when a second instance has been executed and calls `app.requestSingleInstanceLock()`. `argv` is an Array of the second instance's command line arguments, and `workingDirectory` is its current working directory. Usually applications respond to this by making their primary window focused and non-minimized. **Note:** If the second instance is started by a different user than the first, the `argv` array will not include the arguments. **Note:** `ackCallback` allows the user to send data back to the second instance during the `app.requestSingleInstanceLock()` flow. This callback can be used for cases where the second instance needs to obtain additional information from the first instance before quitting. Currently, the limit on the message size is kMaxMessageLength, or around 32kB. To be safe, keep the amount of data passed to 31kB at most. In order to call the callback, `event.preventDefault()` must be called, first. If the callback is not called in either case, `null` will be sent back. If `event.preventDefault()` is not called, but `ackCallback` is called by the user in the event, then the behaviour is undefined. This event is guaranteed to be emitted after the `ready` event of `app` gets emitted. **Note:** Extra command line arguments might be added by Chromium, such as `--original-process-start-time`. ### Event: 'first-instance-ack' Returns: * `event` Event * `additionalData` unknown - A JSON object of additional data passed from the first instance, in response to the first instance's `second-instance` event. This event will be emitted within the second instance during the call to `app.requestSingleInstanceLock()`, when the first instance calls the `ackCallback` provided by the `second-instance` event handler. ## Methods The `app` object has the following methods: **Note:** Some methods are only available on specific operating systems and are labeled as such. ### `app.quit()` Try to close all windows. The `before-quit` event will be emitted first. If all windows are successfully closed, the `will-quit` event will be emitted and by default the application will terminate. This method guarantees that all `beforeunload` and `unload` event handlers are correctly executed. It is possible that a window cancels the quitting by returning `false` in the `beforeunload` event handler. ### `app.exit([exitCode])` * `exitCode` Integer (optional) Exits immediately with `exitCode`. `exitCode` defaults to 0. All windows will be closed immediately without asking the user, and the `before-quit` and `will-quit` events will not be emitted. ### `app.relaunch([options])` * `options` Object (optional) * `args` string[] (optional) * `execPath` string (optional) Relaunches the app when current instance exits. By default, the new instance will use the same working directory and command line arguments with current instance. When `args` is specified, the `args` will be passed as command line arguments instead. When `execPath` is specified, the `execPath` will be executed for relaunch instead of current app. Note that this method does not quit the app when executed, you have to call `app.quit` or `app.exit` after calling `app.relaunch` to make the app restart. When `app.relaunch` is called for multiple times, multiple instances will be started after current instance exited. An example of restarting current instance immediately and adding a new command line argument to the new instance: ```javascript const { app } = require('electron') app.relaunch({ args: process.argv.slice(1).concat(['--relaunch']) }) app.exit(0) ``` ### `app.isReady()` Returns `boolean` - `true` if Electron has finished initializing, `false` otherwise. See also `app.whenReady()`. ### `app.whenReady()` Returns `Promise<void>` - fulfilled when Electron is initialized. May be used as a convenient alternative to checking `app.isReady()` and subscribing to the `ready` event if the app is not ready yet. ### `app.focus([options])` * `options` Object (optional) * `steal` boolean _macOS_ - Make the receiver the active app even if another app is currently active. On Linux, focuses on the first visible window. On macOS, makes the application the active app. On Windows, focuses on the application's first window. You should seek to use the `steal` option as sparingly as possible. ### `app.hide()` _macOS_ Hides all application windows without minimizing them. ### `app.isHidden()` _macOS_ Returns `boolean` - `true` if the application—including all of its windows—is hidden (e.g. with `Command-H`), `false` otherwise. ### `app.show()` _macOS_ Shows application windows after they were hidden. Does not automatically focus them. ### `app.setAppLogsPath([path])` * `path` string (optional) - A custom path for your logs. Must be absolute. Sets or creates a directory your app's logs which can then be manipulated with `app.getPath()` or `app.setPath(pathName, newPath)`. Calling `app.setAppLogsPath()` without a `path` parameter will result in this directory being set to `~/Library/Logs/YourAppName` on _macOS_, and inside the `userData` directory on _Linux_ and _Windows_. ### `app.getAppPath()` Returns `string` - The current application directory. ### `app.getPath(name)` * `name` string - You can request the following paths by the name: * `home` User's home directory. * `appData` Per-user application data directory, which by default points to: * `%APPDATA%` on Windows * `$XDG_CONFIG_HOME` or `~/.config` on Linux * `~/Library/Application Support` on macOS * `userData` The directory for storing your app's configuration files, which by default it is the `appData` directory appended with your app's name. * `temp` Temporary directory. * `exe` The current executable file. * `module` The `libchromiumcontent` library. * `desktop` The current user's Desktop directory. * `documents` Directory for a user's "My Documents". * `downloads` Directory for a user's downloads. * `music` Directory for a user's music. * `pictures` Directory for a user's pictures. * `videos` Directory for a user's videos. * `recent` Directory for the user's recent files (Windows only). * `logs` Directory for your app's log folder. * `crashDumps` Directory where crash dumps are stored. Returns `string` - A path to a special directory or file associated with `name`. On failure, an `Error` is thrown. If `app.getPath('logs')` is called without called `app.setAppLogsPath()` being called first, a default log directory will be created equivalent to calling `app.setAppLogsPath()` without a `path` parameter. ### `app.getFileIcon(path[, options])` * `path` string * `options` Object (optional) * `size` string * `small` - 16x16 * `normal` - 32x32 * `large` - 48x48 on _Linux_, 32x32 on _Windows_, unsupported on _macOS_. Returns `Promise<NativeImage>` - fulfilled with the app's icon, which is a [NativeImage](native-image.md). Fetches a path's associated icon. On _Windows_, there a 2 kinds of icons: * Icons associated with certain file extensions, like `.mp3`, `.png`, etc. * Icons inside the file itself, like `.exe`, `.dll`, `.ico`. On _Linux_ and _macOS_, icons depend on the application associated with file mime type. ### `app.setPath(name, path)` * `name` string * `path` string Overrides the `path` to a special directory or file associated with `name`. If the path specifies a directory that does not exist, an `Error` is thrown. In that case, the directory should be created with `fs.mkdirSync` or similar. You can only override paths of a `name` defined in `app.getPath`. By default, web pages' cookies and caches will be stored under the `userData` directory. If you want to change this location, you have to override the `userData` path before the `ready` event of the `app` module is emitted. ### `app.getVersion()` Returns `string` - The version of the loaded application. If no version is found in the application's `package.json` file, the version of the current bundle or executable is returned. ### `app.getName()` Returns `string` - The current application's name, which is the name in the application's `package.json` file. Usually the `name` field of `package.json` is a short lowercase name, according to the npm modules spec. You should usually also specify a `productName` field, which is your application's full capitalized name, and which will be preferred over `name` by Electron. ### `app.setName(name)` * `name` string Overrides the current application's name. **Note:** This function overrides the name used internally by Electron; it does not affect the name that the OS uses. ### `app.getLocale()` Returns `string` - The current application locale, fetched using Chromium's `l10n_util` library. Possible return values are documented [here](https://source.chromium.org/chromium/chromium/src/+/main:ui/base/l10n/l10n_util.cc). To set the locale, you'll want to use a command line switch at app startup, which may be found [here](command-line-switches.md). **Note:** When distributing your packaged app, you have to also ship the `locales` folder. **Note:** On Windows, you have to call it after the `ready` events gets emitted. ### `app.getLocaleCountryCode()` Returns `string` - User operating system's locale two-letter [ISO 3166](https://www.iso.org/iso-3166-country-codes.html) country code. The value is taken from native OS APIs. **Note:** When unable to detect locale country code, it returns empty string. ### `app.addRecentDocument(path)` _macOS_ _Windows_ * `path` string Adds `path` to the recent documents list. This list is managed by the OS. On Windows, you can visit the list from the task bar, and on macOS, you can visit it from dock menu. ### `app.clearRecentDocuments()` _macOS_ _Windows_ Clears the recent documents list. ### `app.setAsDefaultProtocolClient(protocol[, path, args])` * `protocol` string - The name of your protocol, without `://`. For example, if you want your app to handle `electron://` links, call this method with `electron` as the parameter. * `path` string (optional) _Windows_ - The path to the Electron executable. Defaults to `process.execPath` * `args` string[] (optional) _Windows_ - Arguments passed to the executable. Defaults to an empty array Returns `boolean` - Whether the call succeeded. Sets the current executable as the default handler for a protocol (aka URI scheme). It allows you to integrate your app deeper into the operating system. Once registered, all links with `your-protocol://` will be opened with the current executable. The whole link, including protocol, will be passed to your application as a parameter. **Note:** On macOS, you can only register protocols that have been added to your app's `info.plist`, which cannot be modified at runtime. However, you can change the file during build time via [Electron Forge][electron-forge], [Electron Packager][electron-packager], or by editing `info.plist` with a text editor. Please refer to [Apple's documentation][CFBundleURLTypes] for details. **Note:** In a Windows Store environment (when packaged as an `appx`) this API will return `true` for all calls but the registry key it sets won't be accessible by other applications. In order to register your Windows Store application as a default protocol handler you must [declare the protocol in your manifest](https://docs.microsoft.com/en-us/uwp/schemas/appxpackage/uapmanifestschema/element-uap-protocol). The API uses the Windows Registry and `LSSetDefaultHandlerForURLScheme` internally. ### `app.removeAsDefaultProtocolClient(protocol[, path, args])` _macOS_ _Windows_ * `protocol` string - The name of your protocol, without `://`. * `path` string (optional) _Windows_ - Defaults to `process.execPath` * `args` string[] (optional) _Windows_ - Defaults to an empty array Returns `boolean` - Whether the call succeeded. This method checks if the current executable as the default handler for a protocol (aka URI scheme). If so, it will remove the app as the default handler. ### `app.isDefaultProtocolClient(protocol[, path, args])` * `protocol` string - The name of your protocol, without `://`. * `path` string (optional) _Windows_ - Defaults to `process.execPath` * `args` string[] (optional) _Windows_ - Defaults to an empty array Returns `boolean` - Whether the current executable is the default handler for a protocol (aka URI scheme). **Note:** On macOS, you can use this method to check if the app has been registered as the default protocol handler for a protocol. You can also verify this by checking `~/Library/Preferences/com.apple.LaunchServices.plist` on the macOS machine. Please refer to [Apple's documentation][LSCopyDefaultHandlerForURLScheme] for details. The API uses the Windows Registry and `LSCopyDefaultHandlerForURLScheme` internally. ### `app.getApplicationNameForProtocol(url)` * `url` string - a URL with the protocol name to check. Unlike the other methods in this family, this accepts an entire URL, including `://` at a minimum (e.g. `https://`). Returns `string` - Name of the application handling the protocol, or an empty string if there is no handler. For instance, if Electron is the default handler of the URL, this could be `Electron` on Windows and Mac. However, don't rely on the precise format which is not guaranteed to remain unchanged. Expect a different format on Linux, possibly with a `.desktop` suffix. This method returns the application name of the default handler for the protocol (aka URI scheme) of a URL. ### `app.getApplicationInfoForProtocol(url)` _macOS_ _Windows_ * `url` string - a URL with the protocol name to check. Unlike the other methods in this family, this accepts an entire URL, including `://` at a minimum (e.g. `https://`). Returns `Promise<Object>` - Resolve with an object containing the following: * `icon` NativeImage - the display icon of the app handling the protocol. * `path` string - installation path of the app handling the protocol. * `name` string - display name of the app handling the protocol. This method returns a promise that contains the application name, icon and path of the default handler for the protocol (aka URI scheme) of a URL. ### `app.setUserTasks(tasks)` _Windows_ * `tasks` [Task[]](structures/task.md) - Array of `Task` objects Adds `tasks` to the [Tasks][tasks] category of the Jump List on Windows. `tasks` is an array of [`Task`](structures/task.md) objects. Returns `boolean` - Whether the call succeeded. **Note:** If you'd like to customize the Jump List even more use `app.setJumpList(categories)` instead. ### `app.getJumpListSettings()` _Windows_ Returns `Object`: * `minItems` Integer - The minimum number of items that will be shown in the Jump List (for a more detailed description of this value see the [MSDN docs][JumpListBeginListMSDN]). * `removedItems` [JumpListItem[]](structures/jump-list-item.md) - Array of `JumpListItem` objects that correspond to items that the user has explicitly removed from custom categories in the Jump List. These items must not be re-added to the Jump List in the **next** call to `app.setJumpList()`, Windows will not display any custom category that contains any of the removed items. ### `app.setJumpList(categories)` _Windows_ * `categories` [JumpListCategory[]](structures/jump-list-category.md) | `null` - Array of `JumpListCategory` objects. Sets or removes a custom Jump List for the application, and returns one of the following strings: * `ok` - Nothing went wrong. * `error` - One or more errors occurred, enable runtime logging to figure out the likely cause. * `invalidSeparatorError` - An attempt was made to add a separator to a custom category in the Jump List. Separators are only allowed in the standard `Tasks` category. * `fileTypeRegistrationError` - An attempt was made to add a file link to the Jump List for a file type the app isn't registered to handle. * `customCategoryAccessDeniedError` - Custom categories can't be added to the Jump List due to user privacy or group policy settings. If `categories` is `null` the previously set custom Jump List (if any) will be replaced by the standard Jump List for the app (managed by Windows). **Note:** If a `JumpListCategory` object has neither the `type` nor the `name` property set then its `type` is assumed to be `tasks`. If the `name` property is set but the `type` property is omitted then the `type` is assumed to be `custom`. **Note:** Users can remove items from custom categories, and Windows will not allow a removed item to be added back into a custom category until **after** the next successful call to `app.setJumpList(categories)`. Any attempt to re-add a removed item to a custom category earlier than that will result in the entire custom category being omitted from the Jump List. The list of removed items can be obtained using `app.getJumpListSettings()`. **Note:** The maximum length of a Jump List item's `description` property is 260 characters. Beyond this limit, the item will not be added to the Jump List, nor will it be displayed. Here's a very simple example of creating a custom Jump List: ```javascript const { app } = require('electron') app.setJumpList([ { type: 'custom', name: 'Recent Projects', items: [ { type: 'file', path: 'C:\\Projects\\project1.proj' }, { type: 'file', path: 'C:\\Projects\\project2.proj' } ] }, { // has a name so `type` is assumed to be "custom" name: 'Tools', items: [ { type: 'task', title: 'Tool A', program: process.execPath, args: '--run-tool-a', icon: process.execPath, iconIndex: 0, description: 'Runs Tool A' }, { type: 'task', title: 'Tool B', program: process.execPath, args: '--run-tool-b', icon: process.execPath, iconIndex: 0, description: 'Runs Tool B' } ] }, { type: 'frequent' }, { // has no name and no type so `type` is assumed to be "tasks" items: [ { type: 'task', title: 'New Project', program: process.execPath, args: '--new-project', description: 'Create a new project.' }, { type: 'separator' }, { type: 'task', title: 'Recover Project', program: process.execPath, args: '--recover-project', description: 'Recover Project' } ] } ]) ``` ### `app.requestSingleInstanceLock([additionalData])` * `additionalData` Record<any, any> (optional) - A JSON object containing additional data to send to the first instance. Returns `boolean` The return value of this method indicates whether or not this instance of your application successfully obtained the lock. If it failed to obtain the lock, you can assume that another instance of your application is already running with the lock and exit immediately. I.e. This method returns `true` if your process is the primary instance of your application and your app should continue loading. It returns `false` if your process should immediately quit as it has sent its parameters to another instance that has already acquired the lock. On macOS, the system enforces single instance automatically when users try to open a second instance of your app in Finder, and the `open-file` and `open-url` events will be emitted for that. However when users start your app in command line, the system's single instance mechanism will be bypassed, and you have to use this method to ensure single instance. An example of activating the window of primary instance when a second instance starts: ```javascript const { app } = require('electron') let myWindow = null app.on('first-instance-ack', (event, additionalData) => { // Print out the ack received from the first instance. // Note this event handler must come before the requestSingleInstanceLock call. // Expected output: '{"myAckKey":"myAckValue"}' console.log(JSON.stringify(additionalData)) }) const additionalData = { myKey: 'myValue' } const gotTheLock = app.requestSingleInstanceLock(additionalData) if (!gotTheLock) { app.quit() } else { app.on('second-instance', (event, commandLine, workingDirectory, additionalData) => { // We must call preventDefault if we're sending back data. event.preventDefault() // Print out data received from the second instance. // Expected output: '{"myKey":"myValue"}' console.log(JSON.stringify(additionalData)) // Someone tried to run a second instance, we should focus our window. if (myWindow) { if (myWindow.isMinimized()) myWindow.restore() myWindow.focus() } const ackData = { myAckKey: 'myAckValue' } ackCallback(ackData) }) // Create myWindow, load the rest of the app, etc... app.whenReady().then(() => { myWindow = createWindow() }) } ``` ### `app.hasSingleInstanceLock()` Returns `boolean` This method returns whether or not this instance of your app is currently holding the single instance lock. You can request the lock with `app.requestSingleInstanceLock()` and release with `app.releaseSingleInstanceLock()` ### `app.releaseSingleInstanceLock()` Releases all locks that were created by `requestSingleInstanceLock`. This will allow multiple instances of the application to once again run side by side. ### `app.setUserActivity(type, userInfo[, webpageURL])` _macOS_ * `type` string - Uniquely identifies the activity. Maps to [`NSUserActivity.activityType`][activity-type]. * `userInfo` any - App-specific state to store for use by another device. * `webpageURL` string (optional) - The webpage to load in a browser if no suitable app is installed on the resuming device. The scheme must be `http` or `https`. Creates an `NSUserActivity` and sets it as the current activity. The activity is eligible for [Handoff][handoff] to another device afterward. ### `app.getCurrentActivityType()` _macOS_ Returns `string` - The type of the currently running activity. ### `app.invalidateCurrentActivity()` _macOS_ Invalidates the current [Handoff][handoff] user activity. ### `app.resignCurrentActivity()` _macOS_ Marks the current [Handoff][handoff] user activity as inactive without invalidating it. ### `app.updateCurrentActivity(type, userInfo)` _macOS_ * `type` string - Uniquely identifies the activity. Maps to [`NSUserActivity.activityType`][activity-type]. * `userInfo` any - App-specific state to store for use by another device. Updates the current activity if its type matches `type`, merging the entries from `userInfo` into its current `userInfo` dictionary. ### `app.setAppUserModelId(id)` _Windows_ * `id` string Changes the [Application User Model ID][app-user-model-id] to `id`. ### `app.setActivationPolicy(policy)` _macOS_ * `policy` string - Can be 'regular', 'accessory', or 'prohibited'. Sets the activation policy for a given app. Activation policy types: * 'regular' - The application is an ordinary app that appears in the Dock and may have a user interface. * 'accessory' - The application doesn’t appear in the Dock and doesn’t have a menu bar, but it may be activated programmatically or by clicking on one of its windows. * 'prohibited' - The application doesn’t appear in the Dock and may not create windows or be activated. ### `app.importCertificate(options, callback)` _Linux_ * `options` Object * `certificate` string - Path for the pkcs12 file. * `password` string - Passphrase for the certificate. * `callback` Function * `result` Integer - Result of import. Imports the certificate in pkcs12 format into the platform certificate store. `callback` is called with the `result` of import operation, a value of `0` indicates success while any other value indicates failure according to Chromium [net_error_list](https://source.chromium.org/chromium/chromium/src/+/main:net/base/net_error_list.h). ### `app.configureHostResolver(options)` * `options` Object * `enableBuiltInResolver` boolean (optional) - Whether the built-in host resolver is used in preference to getaddrinfo. When enabled, the built-in resolver will attempt to use the system's DNS settings to do DNS lookups itself. Enabled by default on macOS, disabled by default on Windows and Linux. * `secureDnsMode` string (optional) - Can be "off", "automatic" or "secure". Configures the DNS-over-HTTP mode. When "off", no DoH lookups will be performed. When "automatic", DoH lookups will be performed first if DoH is available, and insecure DNS lookups will be performed as a fallback. When "secure", only DoH lookups will be performed. Defaults to "automatic". * `secureDnsServers` string[]&#32;(optional) - A list of DNS-over-HTTP server templates. See [RFC8484 § 3][] for details on the template format. Most servers support the POST method; the template for such servers is simply a URI. Note that for [some DNS providers][doh-providers], the resolver will automatically upgrade to DoH unless DoH is explicitly disabled, even if there are no DoH servers provided in this list. * `enableAdditionalDnsQueryTypes` boolean (optional) - Controls whether additional DNS query types, e.g. HTTPS (DNS type 65) will be allowed besides the traditional A and AAAA queries when a request is being made via insecure DNS. Has no effect on Secure DNS which always allows additional types. Defaults to true. Configures host resolution (DNS and DNS-over-HTTPS). By default, the following resolvers will be used, in order: 1. DNS-over-HTTPS, if the [DNS provider supports it][doh-providers], then 2. the built-in resolver (enabled on macOS only by default), then 3. the system's resolver (e.g. `getaddrinfo`). This can be configured to either restrict usage of non-encrypted DNS (`secureDnsMode: "secure"`), or disable DNS-over-HTTPS (`secureDnsMode: "off"`). It is also possible to enable or disable the built-in resolver. To disable insecure DNS, you can specify a `secureDnsMode` of `"secure"`. If you do so, you should make sure to provide a list of DNS-over-HTTPS servers to use, in case the user's DNS configuration does not include a provider that supports DoH. ```js app.configureHostResolver({ secureDnsMode: 'secure', secureDnsServers: [ 'https://cloudflare-dns.com/dns-query' ] }) ``` This API must be called after the `ready` event is emitted. [doh-providers]: https://source.chromium.org/chromium/chromium/src/+/main:net/dns/public/doh_provider_entry.cc;l=31?q=%22DohProviderEntry::GetList()%22&ss=chromium%2Fchromium%2Fsrc [RFC8484 § 3]: https://datatracker.ietf.org/doc/html/rfc8484#section-3 ### `app.disableHardwareAcceleration()` Disables hardware acceleration for current app. This method can only be called before app is ready. ### `app.disableDomainBlockingFor3DAPIs()` By default, Chromium disables 3D APIs (e.g. WebGL) until restart on a per domain basis if the GPU processes crashes too frequently. This function disables that behavior. This method can only be called before app is ready. ### `app.getAppMetrics()` Returns [`ProcessMetric[]`](structures/process-metric.md): Array of `ProcessMetric` objects that correspond to memory and CPU usage statistics of all the processes associated with the app. ### `app.getGPUFeatureStatus()` Returns [`GPUFeatureStatus`](structures/gpu-feature-status.md) - The Graphics Feature Status from `chrome://gpu/`. **Note:** This information is only usable after the `gpu-info-update` event is emitted. ### `app.getGPUInfo(infoType)` * `infoType` string - Can be `basic` or `complete`. Returns `Promise<unknown>` For `infoType` equal to `complete`: Promise is fulfilled with `Object` containing all the GPU Information as in [chromium's GPUInfo object](https://chromium.googlesource.com/chromium/src/+/4178e190e9da409b055e5dff469911ec6f6b716f/gpu/config/gpu_info.cc). This includes the version and driver information that's shown on `chrome://gpu` page. For `infoType` equal to `basic`: Promise is fulfilled with `Object` containing fewer attributes than when requested with `complete`. Here's an example of basic response: ```js { auxAttributes: { amdSwitchable: true, canSupportThreadedTextureMailbox: false, directComposition: false, directRendering: true, glResetNotificationStrategy: 0, inProcessGpu: true, initializationTime: 0, jpegDecodeAcceleratorSupported: false, optimus: false, passthroughCmdDecoder: false, sandboxed: false, softwareRendering: false, supportsOverlays: false, videoDecodeAcceleratorFlags: 0 }, gpuDevice: [{ active: true, deviceId: 26657, vendorId: 4098 }, { active: false, deviceId: 3366, vendorId: 32902 }], machineModelName: 'MacBookPro', machineModelVersion: '11.5' } ``` Using `basic` should be preferred if only basic information like `vendorId` or `driverId` is needed. ### `app.setBadgeCount([count])` _Linux_ _macOS_ * `count` Integer (optional) - If a value is provided, set the badge to the provided value otherwise, on macOS, display a plain white dot (e.g. unknown number of notifications). On Linux, if a value is not provided the badge will not display. Returns `boolean` - Whether the call succeeded. Sets the counter badge for current app. Setting the count to `0` will hide the badge. On macOS, it shows on the dock icon. On Linux, it only works for Unity launcher. **Note:** Unity launcher requires a `.desktop` file to work. For more information, please read the [Unity integration documentation][unity-requirement]. ### `app.getBadgeCount()` _Linux_ _macOS_ Returns `Integer` - The current value displayed in the counter badge. ### `app.isUnityRunning()` _Linux_ Returns `boolean` - Whether the current desktop environment is Unity launcher. ### `app.getLoginItemSettings([options])` _macOS_ _Windows_ * `options` Object (optional) * `path` string (optional) _Windows_ - The executable path to compare against. Defaults to `process.execPath`. * `args` string[] (optional) _Windows_ - The command-line arguments to compare against. Defaults to an empty array. If you provided `path` and `args` options to `app.setLoginItemSettings`, then you need to pass the same arguments here for `openAtLogin` to be set correctly. Returns `Object`: * `openAtLogin` boolean - `true` if the app is set to open at login. * `openAsHidden` boolean _macOS_ - `true` if the app is set to open as hidden at login. This setting is not available on [MAS builds][mas-builds]. * `wasOpenedAtLogin` boolean _macOS_ - `true` if the app was opened at login automatically. This setting is not available on [MAS builds][mas-builds]. * `wasOpenedAsHidden` boolean _macOS_ - `true` if the app was opened as a hidden login item. This indicates that the app should not open any windows at startup. This setting is not available on [MAS builds][mas-builds]. * `restoreState` boolean _macOS_ - `true` if the app was opened as a login item that should restore the state from the previous session. This indicates that the app should restore the windows that were open the last time the app was closed. This setting is not available on [MAS builds][mas-builds]. * `executableWillLaunchAtLogin` boolean _Windows_ - `true` if app is set to open at login and its run key is not deactivated. This differs from `openAtLogin` as it ignores the `args` option, this property will be true if the given executable would be launched at login with **any** arguments. * `launchItems` Object[] _Windows_ * `name` string _Windows_ - name value of a registry entry. * `path` string _Windows_ - The executable to an app that corresponds to a registry entry. * `args` string[] _Windows_ - the command-line arguments to pass to the executable. * `scope` string _Windows_ - one of `user` or `machine`. Indicates whether the registry entry is under `HKEY_CURRENT USER` or `HKEY_LOCAL_MACHINE`. * `enabled` boolean _Windows_ - `true` if the app registry key is startup approved and therefore shows as `enabled` in Task Manager and Windows settings. ### `app.setLoginItemSettings(settings)` _macOS_ _Windows_ * `settings` Object * `openAtLogin` boolean (optional) - `true` to open the app at login, `false` to remove the app as a login item. Defaults to `false`. * `openAsHidden` boolean (optional) _macOS_ - `true` to open the app as hidden. Defaults to `false`. The user can edit this setting from the System Preferences so `app.getLoginItemSettings().wasOpenedAsHidden` should be checked when the app is opened to know the current value. This setting is not available on [MAS builds][mas-builds]. * `path` string (optional) _Windows_ - The executable to launch at login. Defaults to `process.execPath`. * `args` string[] (optional) _Windows_ - The command-line arguments to pass to the executable. Defaults to an empty array. Take care to wrap paths in quotes. * `enabled` boolean (optional) _Windows_ - `true` will change the startup approved registry key and `enable / disable` the App in Task Manager and Windows Settings. Defaults to `true`. * `name` string (optional) _Windows_ - value name to write into registry. Defaults to the app's AppUserModelId(). Set the app's login item settings. To work with Electron's `autoUpdater` on Windows, which uses [Squirrel][Squirrel-Windows], you'll want to set the launch path to Update.exe, and pass arguments that specify your application name. For example: ``` javascript const appFolder = path.dirname(process.execPath) const updateExe = path.resolve(appFolder, '..', 'Update.exe') const exeName = path.basename(process.execPath) app.setLoginItemSettings({ openAtLogin: true, path: updateExe, args: [ '--processStart', `"${exeName}"`, '--process-start-args', `"--hidden"` ] }) ``` ### `app.isAccessibilitySupportEnabled()` _macOS_ _Windows_ Returns `boolean` - `true` if Chrome's accessibility support is enabled, `false` otherwise. This API will return `true` if the use of assistive technologies, such as screen readers, has been detected. See https://www.chromium.org/developers/design-documents/accessibility for more details. ### `app.setAccessibilitySupportEnabled(enabled)` _macOS_ _Windows_ * `enabled` boolean - Enable or disable [accessibility tree](https://developers.google.com/web/fundamentals/accessibility/semantics-builtin/the-accessibility-tree) rendering Manually enables Chrome's accessibility support, allowing to expose accessibility switch to users in application settings. See [Chromium's accessibility docs](https://www.chromium.org/developers/design-documents/accessibility) for more details. Disabled by default. This API must be called after the `ready` event is emitted. **Note:** Rendering accessibility tree can significantly affect the performance of your app. It should not be enabled by default. ### `app.showAboutPanel()` Show the app's about panel options. These options can be overridden with `app.setAboutPanelOptions(options)`. ### `app.setAboutPanelOptions(options)` * `options` Object * `applicationName` string (optional) - The app's name. * `applicationVersion` string (optional) - The app's version. * `copyright` string (optional) - Copyright information. * `version` string (optional) _macOS_ - The app's build version number. * `credits` string (optional) _macOS_ _Windows_ - Credit information. * `authors` string[] (optional) _Linux_ - List of app authors. * `website` string (optional) _Linux_ - The app's website. * `iconPath` string (optional) _Linux_ _Windows_ - Path to the app's icon in a JPEG or PNG file format. On Linux, will be shown as 64x64 pixels while retaining aspect ratio. Set the about panel options. This will override the values defined in the app's `.plist` file on macOS. See the [Apple docs][about-panel-options] for more details. On Linux, values must be set in order to be shown; there are no defaults. If you do not set `credits` but still wish to surface them in your app, AppKit will look for a file named "Credits.html", "Credits.rtf", and "Credits.rtfd", in that order, in the bundle returned by the NSBundle class method main. The first file found is used, and if none is found, the info area is left blank. See Apple [documentation](https://developer.apple.com/documentation/appkit/nsaboutpaneloptioncredits?language=objc) for more information. ### `app.isEmojiPanelSupported()` Returns `boolean` - whether or not the current OS version allows for native emoji pickers. ### `app.showEmojiPanel()` _macOS_ _Windows_ Show the platform's native emoji picker. ### `app.startAccessingSecurityScopedResource(bookmarkData)` _mas_ * `bookmarkData` string - The base64 encoded security scoped bookmark data returned by the `dialog.showOpenDialog` or `dialog.showSaveDialog` methods. Returns `Function` - This function **must** be called once you have finished accessing the security scoped file. If you do not remember to stop accessing the bookmark, [kernel resources will be leaked](https://developer.apple.com/reference/foundation/nsurl/1417051-startaccessingsecurityscopedreso?language=objc) and your app will lose its ability to reach outside the sandbox completely, until your app is restarted. ```js // Start accessing the file. const stopAccessingSecurityScopedResource = app.startAccessingSecurityScopedResource(data) // You can now access the file outside of the sandbox 🎉 // Remember to stop accessing the file once you've finished with it. stopAccessingSecurityScopedResource() ``` Start accessing a security scoped resource. With this method Electron applications that are packaged for the Mac App Store may reach outside their sandbox to access files chosen by the user. See [Apple's documentation](https://developer.apple.com/library/content/documentation/Security/Conceptual/AppSandboxDesignGuide/AppSandboxInDepth/AppSandboxInDepth.html#//apple_ref/doc/uid/TP40011183-CH3-SW16) for a description of how this system works. ### `app.enableSandbox()` Enables full sandbox mode on the app. This means that all renderers will be launched sandboxed, regardless of the value of the `sandbox` flag in WebPreferences. This method can only be called before app is ready. ### `app.isInApplicationsFolder()` _macOS_ Returns `boolean` - Whether the application is currently running from the systems Application folder. Use in combination with `app.moveToApplicationsFolder()` ### `app.moveToApplicationsFolder([options])` _macOS_ * `options` Object (optional) * `conflictHandler` Function\<boolean> (optional) - A handler for potential conflict in move failure. * `conflictType` string - The type of move conflict encountered by the handler; can be `exists` or `existsAndRunning`, where `exists` means that an app of the same name is present in the Applications directory and `existsAndRunning` means both that it exists and that it's presently running. Returns `boolean` - Whether the move was successful. Please note that if the move is successful, your application will quit and relaunch. No confirmation dialog will be presented by default. If you wish to allow the user to confirm the operation, you may do so using the [`dialog`](dialog.md) API. **NOTE:** This method throws errors if anything other than the user causes the move to fail. For instance if the user cancels the authorization dialog, this method returns false. If we fail to perform the copy, then this method will throw an error. The message in the error should be informative and tell you exactly what went wrong. By default, if an app of the same name as the one being moved exists in the Applications directory and is _not_ running, the existing app will be trashed and the active app moved into its place. If it _is_ running, the pre-existing running app will assume focus and the previously active app will quit itself. This behavior can be changed by providing the optional conflict handler, where the boolean returned by the handler determines whether or not the move conflict is resolved with default behavior. i.e. returning `false` will ensure no further action is taken, returning `true` will result in the default behavior and the method continuing. For example: ```js app.moveToApplicationsFolder({ conflictHandler: (conflictType) => { if (conflictType === 'exists') { return dialog.showMessageBoxSync({ type: 'question', buttons: ['Halt Move', 'Continue Move'], defaultId: 0, message: 'An app of this name already exists' }) === 1 } } }) ``` Would mean that if an app already exists in the user directory, if the user chooses to 'Continue Move' then the function would continue with its default behavior and the existing app will be trashed and the active app moved into its place. ### `app.isSecureKeyboardEntryEnabled()` _macOS_ Returns `boolean` - whether `Secure Keyboard Entry` is enabled. By default this API will return `false`. ### `app.setSecureKeyboardEntryEnabled(enabled)` _macOS_ * `enabled` boolean - Enable or disable `Secure Keyboard Entry` Set the `Secure Keyboard Entry` is enabled in your application. By using this API, important information such as password and other sensitive information can be prevented from being intercepted by other processes. See [Apple's documentation](https://developer.apple.com/library/archive/technotes/tn2150/_index.html) for more details. **Note:** Enable `Secure Keyboard Entry` only when it is needed and disable it when it is no longer needed. ## Properties ### `app.accessibilitySupportEnabled` _macOS_ _Windows_ A `boolean` property that's `true` if Chrome's accessibility support is enabled, `false` otherwise. This property will be `true` if the use of assistive technologies, such as screen readers, has been detected. Setting this property to `true` manually enables Chrome's accessibility support, allowing developers to expose accessibility switch to users in application settings. See [Chromium's accessibility docs](https://www.chromium.org/developers/design-documents/accessibility) for more details. Disabled by default. This API must be called after the `ready` event is emitted. **Note:** Rendering accessibility tree can significantly affect the performance of your app. It should not be enabled by default. ### `app.applicationMenu` A `Menu | null` property that returns [`Menu`](menu.md) if one has been set and `null` otherwise. Users can pass a [Menu](menu.md) to set this property. ### `app.badgeCount` _Linux_ _macOS_ An `Integer` property that returns the badge count for current app. Setting the count to `0` will hide the badge. On macOS, setting this with any nonzero integer shows on the dock icon. On Linux, this property only works for Unity launcher. **Note:** Unity launcher requires a `.desktop` file to work. For more information, please read the [Unity integration documentation][unity-requirement]. **Note:** On macOS, you need to ensure that your application has the permission to display notifications for this property to take effect. ### `app.commandLine` _Readonly_ A [`CommandLine`](./command-line.md) object that allows you to read and manipulate the command line arguments that Chromium uses. ### `app.dock` _macOS_ _Readonly_ A [`Dock`](./dock.md) `| undefined` object that allows you to perform actions on your app icon in the user's dock on macOS. ### `app.isPackaged` _Readonly_ A `boolean` property that returns `true` if the app is packaged, `false` otherwise. For many apps, this property can be used to distinguish development and production environments. [dock-menu]:https://developer.apple.com/macos/human-interface-guidelines/menus/dock-menus/ [tasks]:https://msdn.microsoft.com/en-us/library/windows/desktop/dd378460(v=vs.85).aspx#tasks [app-user-model-id]: https://msdn.microsoft.com/en-us/library/windows/desktop/dd378459(v=vs.85).aspx [electron-forge]: https://www.electronforge.io/ [electron-packager]: https://github.com/electron/electron-packager [CFBundleURLTypes]: https://developer.apple.com/library/ios/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html#//apple_ref/doc/uid/TP40009249-102207-TPXREF115 [LSCopyDefaultHandlerForURLScheme]: https://developer.apple.com/library/mac/documentation/Carbon/Reference/LaunchServicesReference/#//apple_ref/c/func/LSCopyDefaultHandlerForURLScheme [handoff]: https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/Handoff/HandoffFundamentals/HandoffFundamentals.html [activity-type]: https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSUserActivity_Class/index.html#//apple_ref/occ/instp/NSUserActivity/activityType [unity-requirement]: https://help.ubuntu.com/community/UnityLaunchersAndDesktopFiles#Adding_shortcuts_to_a_launcher [mas-builds]: ../tutorial/mac-app-store-submission-guide.md [Squirrel-Windows]: https://github.com/Squirrel/Squirrel.Windows [JumpListBeginListMSDN]: https://msdn.microsoft.com/en-us/library/windows/desktop/dd378398(v=vs.85).aspx [about-panel-options]: https://developer.apple.com/reference/appkit/nsapplication/1428479-orderfrontstandardaboutpanelwith?language=objc ### `app.name` A `string` property that indicates the current application's name, which is the name in the application's `package.json` file. Usually the `name` field of `package.json` is a short lowercase name, according to the npm modules spec. You should usually also specify a `productName` field, which is your application's full capitalized name, and which will be preferred over `name` by Electron. ### `app.userAgentFallback` A `string` which is the user agent string Electron will use as a global fallback. This is the user agent that will be used when no user agent is set at the `webContents` or `session` level. It is useful for ensuring that your entire app has the same user agent. Set to a custom value as early as possible in your app's initialization to ensure that your overridden value is used. ### `app.runningUnderRosettaTranslation` _macOS_ _Readonly_ _Deprecated_ A `boolean` which when `true` indicates that the app is currently running under the [Rosetta Translator Environment](https://en.wikipedia.org/wiki/Rosetta_(software)). You can use this property to prompt users to download the arm64 version of your application when they are running the x64 version under Rosetta incorrectly. **Deprecated:** This property is superceded by the `runningUnderARM64Translation` property which detects when the app is being translated to ARM64 in both macOS and Windows. ### `app.runningUnderARM64Translation` _Readonly_ _macOS_ _Windows_ A `boolean` which when `true` indicates that the app is currently running under an ARM64 translator (like the macOS [Rosetta Translator Environment](https://en.wikipedia.org/wiki/Rosetta_(software)) or Windows [WOW](https://en.wikipedia.org/wiki/Windows_on_Windows)). You can use this property to prompt users to download the arm64 version of your application when they are running the x64 version under Rosetta incorrectly.
closed
electron/electron
https://github.com/electron/electron
33,909
[Bug]: `setJumpList` declares `void` return type but should be `string`?
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.x ### 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 The docs of https://github.com/electron/electron/blob/17-x-y/docs/api/app.md#appsetjumplistcategories-windows say: > Sets or removes a custom Jump List for the application, and returns one of the following strings... However in the `electron.d.ts`, the return type is `void`: ```ts setJumpList(categories: (JumpListCategory[]) | (null)): void; ``` The expected signature is: ```ts setJumpList(categories: (JumpListCategory[]) | (null)): 'ok' | 'error' | 'invalidSeparatorError' | 'fileTypeRegistrationError' | 'customCategoryAccessDeniedError'; ``` ### Actual Behavior The `void` type is the wrong return type. ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/33909
https://github.com/electron/electron/pull/33910
15c931201ab880de84009baa59b9bc5923e1ef67
b5297ea8e2380b9174c26d5a35b1a73c2c9566d0
2022-04-25T04:46:01Z
c++
2022-04-28T10:15:23Z
docs/api/app.md
# app > Control your application's event lifecycle. Process: [Main](../glossary.md#main-process) The following example shows how to quit the application when the last window is closed: ```javascript const { app } = require('electron') app.on('window-all-closed', () => { app.quit() }) ``` ## Events The `app` object emits the following events: ### Event: 'will-finish-launching' Emitted when the application has finished basic startup. On Windows and Linux, the `will-finish-launching` event is the same as the `ready` event; on macOS, this event represents the `applicationWillFinishLaunching` notification of `NSApplication`. You would usually set up listeners for the `open-file` and `open-url` events here, and start the crash reporter and auto updater. In most cases, you should do everything in the `ready` event handler. ### Event: 'ready' Returns: * `event` Event * `launchInfo` Record<string, any> | [NotificationResponse](structures/notification-response.md) _macOS_ Emitted once, when Electron has finished initializing. On macOS, `launchInfo` holds the `userInfo` of the [`NSUserNotification`](https://developer.apple.com/documentation/foundation/nsusernotification) or information from [`UNNotificationResponse`](https://developer.apple.com/documentation/usernotifications/unnotificationresponse) that was used to open the application, if it was launched from Notification Center. You can also call `app.isReady()` to check if this event has already fired and `app.whenReady()` to get a Promise that is fulfilled when Electron is initialized. ### Event: 'window-all-closed' Emitted when all windows have been closed. If you do not subscribe to this event and all windows are closed, the default behavior is to quit the app; however, if you subscribe, you control whether the app quits or not. If the user pressed `Cmd + Q`, or the developer called `app.quit()`, Electron will first try to close all the windows and then emit the `will-quit` event, and in this case the `window-all-closed` event would not be emitted. ### Event: 'before-quit' Returns: * `event` Event Emitted before the application starts closing its windows. Calling `event.preventDefault()` will prevent the default behavior, which is terminating the application. **Note:** If application quit was initiated by `autoUpdater.quitAndInstall()`, then `before-quit` is emitted *after* emitting `close` event on all windows and closing them. **Note:** On Windows, this event will not be emitted if the app is closed due to a shutdown/restart of the system or a user logout. ### Event: 'will-quit' Returns: * `event` Event Emitted when all windows have been closed and the application will quit. Calling `event.preventDefault()` will prevent the default behavior, which is terminating the application. See the description of the `window-all-closed` event for the differences between the `will-quit` and `window-all-closed` events. **Note:** On Windows, this event will not be emitted if the app is closed due to a shutdown/restart of the system or a user logout. ### Event: 'quit' Returns: * `event` Event * `exitCode` Integer Emitted when the application is quitting. **Note:** On Windows, this event will not be emitted if the app is closed due to a shutdown/restart of the system or a user logout. ### Event: 'open-file' _macOS_ Returns: * `event` Event * `path` string Emitted when the user wants to open a file with the application. The `open-file` event is usually emitted when the application is already open and the OS wants to reuse the application to open the file. `open-file` is also emitted when a file is dropped onto the dock and the application is not yet running. Make sure to listen for the `open-file` event very early in your application startup to handle this case (even before the `ready` event is emitted). You should call `event.preventDefault()` if you want to handle this event. On Windows, you have to parse `process.argv` (in the main process) to get the filepath. ### Event: 'open-url' _macOS_ Returns: * `event` Event * `url` string Emitted when the user wants to open a URL with the application. Your application's `Info.plist` file must define the URL scheme within the `CFBundleURLTypes` key, and set `NSPrincipalClass` to `AtomApplication`. You should call `event.preventDefault()` if you want to handle this event. ### Event: 'activate' _macOS_ Returns: * `event` Event * `hasVisibleWindows` boolean Emitted when the application is activated. Various actions can trigger this event, such as launching the application for the first time, attempting to re-launch the application when it's already running, or clicking on the application's dock or taskbar icon. ### Event: 'did-become-active' _macOS_ Returns: * `event` Event Emitted when mac application become active. Difference from `activate` event is that `did-become-active` is emitted every time the app becomes active, not only when Dock icon is clicked or application is re-launched. ### Event: 'continue-activity' _macOS_ Returns: * `event` Event * `type` string - A string identifying the activity. Maps to [`NSUserActivity.activityType`][activity-type]. * `userInfo` unknown - Contains app-specific state stored by the activity on another device. * `details` Object * `webpageURL` string (optional) - A string identifying the URL of the webpage accessed by the activity on another device, if available. Emitted during [Handoff][handoff] when an activity from a different device wants to be resumed. You should call `event.preventDefault()` if you want to handle this event. A user activity can be continued only in an app that has the same developer Team ID as the activity's source app and that supports the activity's type. Supported activity types are specified in the app's `Info.plist` under the `NSUserActivityTypes` key. ### Event: 'will-continue-activity' _macOS_ Returns: * `event` Event * `type` string - A string identifying the activity. Maps to [`NSUserActivity.activityType`][activity-type]. Emitted during [Handoff][handoff] before an activity from a different device wants to be resumed. You should call `event.preventDefault()` if you want to handle this event. ### Event: 'continue-activity-error' _macOS_ Returns: * `event` Event * `type` string - A string identifying the activity. Maps to [`NSUserActivity.activityType`][activity-type]. * `error` string - A string with the error's localized description. Emitted during [Handoff][handoff] when an activity from a different device fails to be resumed. ### Event: 'activity-was-continued' _macOS_ Returns: * `event` Event * `type` string - A string identifying the activity. Maps to [`NSUserActivity.activityType`][activity-type]. * `userInfo` unknown - Contains app-specific state stored by the activity. Emitted during [Handoff][handoff] after an activity from this device was successfully resumed on another one. ### Event: 'update-activity-state' _macOS_ Returns: * `event` Event * `type` string - A string identifying the activity. Maps to [`NSUserActivity.activityType`][activity-type]. * `userInfo` unknown - Contains app-specific state stored by the activity. Emitted when [Handoff][handoff] is about to be resumed on another device. If you need to update the state to be transferred, you should call `event.preventDefault()` immediately, construct a new `userInfo` dictionary and call `app.updateCurrentActivity()` in a timely manner. Otherwise, the operation will fail and `continue-activity-error` will be called. ### Event: 'new-window-for-tab' _macOS_ Returns: * `event` Event Emitted when the user clicks the native macOS new tab button. The new tab button is only visible if the current `BrowserWindow` has a `tabbingIdentifier` ### Event: 'browser-window-blur' Returns: * `event` Event * `window` [BrowserWindow](browser-window.md) Emitted when a [browserWindow](browser-window.md) gets blurred. ### Event: 'browser-window-focus' Returns: * `event` Event * `window` [BrowserWindow](browser-window.md) Emitted when a [browserWindow](browser-window.md) gets focused. ### Event: 'browser-window-created' Returns: * `event` Event * `window` [BrowserWindow](browser-window.md) Emitted when a new [browserWindow](browser-window.md) is created. ### Event: 'web-contents-created' Returns: * `event` Event * `webContents` [WebContents](web-contents.md) Emitted when a new [webContents](web-contents.md) is created. ### Event: 'certificate-error' Returns: * `event` Event * `webContents` [WebContents](web-contents.md) * `url` string * `error` string - The error code * `certificate` [Certificate](structures/certificate.md) * `callback` Function * `isTrusted` boolean - Whether to consider the certificate as trusted * `isMainFrame` boolean Emitted when failed to verify the `certificate` for `url`, to trust the certificate you should prevent the default behavior with `event.preventDefault()` and call `callback(true)`. ```javascript const { app } = require('electron') app.on('certificate-error', (event, webContents, url, error, certificate, callback) => { if (url === 'https://github.com') { // Verification logic. event.preventDefault() callback(true) } else { callback(false) } }) ``` ### Event: 'select-client-certificate' Returns: * `event` Event * `webContents` [WebContents](web-contents.md) * `url` URL * `certificateList` [Certificate[]](structures/certificate.md) * `callback` Function * `certificate` [Certificate](structures/certificate.md) (optional) Emitted when a client certificate is requested. The `url` corresponds to the navigation entry requesting the client certificate and `callback` can be called with an entry filtered from the list. Using `event.preventDefault()` prevents the application from using the first certificate from the store. ```javascript const { app } = require('electron') app.on('select-client-certificate', (event, webContents, url, list, callback) => { event.preventDefault() callback(list[0]) }) ``` ### Event: 'login' Returns: * `event` Event * `webContents` [WebContents](web-contents.md) * `authenticationResponseDetails` Object * `url` URL * `authInfo` Object * `isProxy` boolean * `scheme` string * `host` string * `port` Integer * `realm` string * `callback` Function * `username` string (optional) * `password` string (optional) Emitted when `webContents` wants to do basic auth. The default behavior is to cancel all authentications. To override this you should prevent the default behavior with `event.preventDefault()` and call `callback(username, password)` with the credentials. ```javascript const { app } = require('electron') app.on('login', (event, webContents, details, authInfo, callback) => { event.preventDefault() callback('username', 'secret') }) ``` If `callback` is called without a username or password, the authentication request will be cancelled and the authentication error will be returned to the page. ### Event: 'gpu-info-update' Emitted whenever there is a GPU info update. ### Event: 'gpu-process-crashed' _Deprecated_ Returns: * `event` Event * `killed` boolean Emitted when the GPU process crashes or is killed. **Deprecated:** This event is superceded by the `child-process-gone` event which contains more information about why the child process disappeared. It isn't always because it crashed. The `killed` boolean can be replaced by checking `reason === 'killed'` when you switch to that event. ### Event: 'renderer-process-crashed' _Deprecated_ Returns: * `event` Event * `webContents` [WebContents](web-contents.md) * `killed` boolean Emitted when the renderer process of `webContents` crashes or is killed. **Deprecated:** This event is superceded by the `render-process-gone` event which contains more information about why the render process disappeared. It isn't always because it crashed. The `killed` boolean can be replaced by checking `reason === 'killed'` when you switch to that event. ### Event: 'render-process-gone' Returns: * `event` Event * `webContents` [WebContents](web-contents.md) * `details` Object * `reason` string - The reason the render process is gone. Possible values: * `clean-exit` - Process exited with an exit code of zero * `abnormal-exit` - Process exited with a non-zero exit code * `killed` - Process was sent a SIGTERM or otherwise killed externally * `crashed` - Process crashed * `oom` - Process ran out of memory * `launch-failed` - Process never successfully launched * `integrity-failure` - Windows code integrity checks failed * `exitCode` Integer - The exit code of the process, unless `reason` is `launch-failed`, in which case `exitCode` will be a platform-specific launch failure error code. Emitted when the renderer process unexpectedly disappears. This is normally because it was crashed or killed. ### Event: 'child-process-gone' Returns: * `event` Event * `details` Object * `type` string - Process type. One of the following values: * `Utility` * `Zygote` * `Sandbox helper` * `GPU` * `Pepper Plugin` * `Pepper Plugin Broker` * `Unknown` * `reason` string - The reason the child process is gone. Possible values: * `clean-exit` - Process exited with an exit code of zero * `abnormal-exit` - Process exited with a non-zero exit code * `killed` - Process was sent a SIGTERM or otherwise killed externally * `crashed` - Process crashed * `oom` - Process ran out of memory * `launch-failed` - Process never successfully launched * `integrity-failure` - Windows code integrity checks failed * `exitCode` number - The exit code for the process (e.g. status from waitpid if on posix, from GetExitCodeProcess on Windows). * `serviceName` string (optional) - The non-localized name of the process. * `name` string (optional) - The name of the process. Examples for utility: `Audio Service`, `Content Decryption Module Service`, `Network Service`, `Video Capture`, etc. Emitted when the child process unexpectedly disappears. This is normally because it was crashed or killed. It does not include renderer processes. ### Event: 'accessibility-support-changed' _macOS_ _Windows_ Returns: * `event` Event * `accessibilitySupportEnabled` boolean - `true` when Chrome's accessibility support is enabled, `false` otherwise. Emitted when Chrome's accessibility support changes. This event fires when assistive technologies, such as screen readers, are enabled or disabled. See https://www.chromium.org/developers/design-documents/accessibility for more details. ### Event: 'session-created' Returns: * `session` [Session](session.md) Emitted when Electron has created a new `session`. ```javascript const { app } = require('electron') app.on('session-created', (session) => { console.log(session) }) ``` ### Event: 'second-instance' Returns: * `event` Event * `argv` string[] - An array of the second instance's command line arguments * `workingDirectory` string - The second instance's working directory * `additionalData` unknown - A JSON object of additional data passed from the second instance * `ackCallback` unknown - A function that can be used to send data back to the second instance This event will be emitted inside the primary instance of your application when a second instance has been executed and calls `app.requestSingleInstanceLock()`. `argv` is an Array of the second instance's command line arguments, and `workingDirectory` is its current working directory. Usually applications respond to this by making their primary window focused and non-minimized. **Note:** If the second instance is started by a different user than the first, the `argv` array will not include the arguments. **Note:** `ackCallback` allows the user to send data back to the second instance during the `app.requestSingleInstanceLock()` flow. This callback can be used for cases where the second instance needs to obtain additional information from the first instance before quitting. Currently, the limit on the message size is kMaxMessageLength, or around 32kB. To be safe, keep the amount of data passed to 31kB at most. In order to call the callback, `event.preventDefault()` must be called, first. If the callback is not called in either case, `null` will be sent back. If `event.preventDefault()` is not called, but `ackCallback` is called by the user in the event, then the behaviour is undefined. This event is guaranteed to be emitted after the `ready` event of `app` gets emitted. **Note:** Extra command line arguments might be added by Chromium, such as `--original-process-start-time`. ### Event: 'first-instance-ack' Returns: * `event` Event * `additionalData` unknown - A JSON object of additional data passed from the first instance, in response to the first instance's `second-instance` event. This event will be emitted within the second instance during the call to `app.requestSingleInstanceLock()`, when the first instance calls the `ackCallback` provided by the `second-instance` event handler. ## Methods The `app` object has the following methods: **Note:** Some methods are only available on specific operating systems and are labeled as such. ### `app.quit()` Try to close all windows. The `before-quit` event will be emitted first. If all windows are successfully closed, the `will-quit` event will be emitted and by default the application will terminate. This method guarantees that all `beforeunload` and `unload` event handlers are correctly executed. It is possible that a window cancels the quitting by returning `false` in the `beforeunload` event handler. ### `app.exit([exitCode])` * `exitCode` Integer (optional) Exits immediately with `exitCode`. `exitCode` defaults to 0. All windows will be closed immediately without asking the user, and the `before-quit` and `will-quit` events will not be emitted. ### `app.relaunch([options])` * `options` Object (optional) * `args` string[] (optional) * `execPath` string (optional) Relaunches the app when current instance exits. By default, the new instance will use the same working directory and command line arguments with current instance. When `args` is specified, the `args` will be passed as command line arguments instead. When `execPath` is specified, the `execPath` will be executed for relaunch instead of current app. Note that this method does not quit the app when executed, you have to call `app.quit` or `app.exit` after calling `app.relaunch` to make the app restart. When `app.relaunch` is called for multiple times, multiple instances will be started after current instance exited. An example of restarting current instance immediately and adding a new command line argument to the new instance: ```javascript const { app } = require('electron') app.relaunch({ args: process.argv.slice(1).concat(['--relaunch']) }) app.exit(0) ``` ### `app.isReady()` Returns `boolean` - `true` if Electron has finished initializing, `false` otherwise. See also `app.whenReady()`. ### `app.whenReady()` Returns `Promise<void>` - fulfilled when Electron is initialized. May be used as a convenient alternative to checking `app.isReady()` and subscribing to the `ready` event if the app is not ready yet. ### `app.focus([options])` * `options` Object (optional) * `steal` boolean _macOS_ - Make the receiver the active app even if another app is currently active. On Linux, focuses on the first visible window. On macOS, makes the application the active app. On Windows, focuses on the application's first window. You should seek to use the `steal` option as sparingly as possible. ### `app.hide()` _macOS_ Hides all application windows without minimizing them. ### `app.isHidden()` _macOS_ Returns `boolean` - `true` if the application—including all of its windows—is hidden (e.g. with `Command-H`), `false` otherwise. ### `app.show()` _macOS_ Shows application windows after they were hidden. Does not automatically focus them. ### `app.setAppLogsPath([path])` * `path` string (optional) - A custom path for your logs. Must be absolute. Sets or creates a directory your app's logs which can then be manipulated with `app.getPath()` or `app.setPath(pathName, newPath)`. Calling `app.setAppLogsPath()` without a `path` parameter will result in this directory being set to `~/Library/Logs/YourAppName` on _macOS_, and inside the `userData` directory on _Linux_ and _Windows_. ### `app.getAppPath()` Returns `string` - The current application directory. ### `app.getPath(name)` * `name` string - You can request the following paths by the name: * `home` User's home directory. * `appData` Per-user application data directory, which by default points to: * `%APPDATA%` on Windows * `$XDG_CONFIG_HOME` or `~/.config` on Linux * `~/Library/Application Support` on macOS * `userData` The directory for storing your app's configuration files, which by default it is the `appData` directory appended with your app's name. * `temp` Temporary directory. * `exe` The current executable file. * `module` The `libchromiumcontent` library. * `desktop` The current user's Desktop directory. * `documents` Directory for a user's "My Documents". * `downloads` Directory for a user's downloads. * `music` Directory for a user's music. * `pictures` Directory for a user's pictures. * `videos` Directory for a user's videos. * `recent` Directory for the user's recent files (Windows only). * `logs` Directory for your app's log folder. * `crashDumps` Directory where crash dumps are stored. Returns `string` - A path to a special directory or file associated with `name`. On failure, an `Error` is thrown. If `app.getPath('logs')` is called without called `app.setAppLogsPath()` being called first, a default log directory will be created equivalent to calling `app.setAppLogsPath()` without a `path` parameter. ### `app.getFileIcon(path[, options])` * `path` string * `options` Object (optional) * `size` string * `small` - 16x16 * `normal` - 32x32 * `large` - 48x48 on _Linux_, 32x32 on _Windows_, unsupported on _macOS_. Returns `Promise<NativeImage>` - fulfilled with the app's icon, which is a [NativeImage](native-image.md). Fetches a path's associated icon. On _Windows_, there a 2 kinds of icons: * Icons associated with certain file extensions, like `.mp3`, `.png`, etc. * Icons inside the file itself, like `.exe`, `.dll`, `.ico`. On _Linux_ and _macOS_, icons depend on the application associated with file mime type. ### `app.setPath(name, path)` * `name` string * `path` string Overrides the `path` to a special directory or file associated with `name`. If the path specifies a directory that does not exist, an `Error` is thrown. In that case, the directory should be created with `fs.mkdirSync` or similar. You can only override paths of a `name` defined in `app.getPath`. By default, web pages' cookies and caches will be stored under the `userData` directory. If you want to change this location, you have to override the `userData` path before the `ready` event of the `app` module is emitted. ### `app.getVersion()` Returns `string` - The version of the loaded application. If no version is found in the application's `package.json` file, the version of the current bundle or executable is returned. ### `app.getName()` Returns `string` - The current application's name, which is the name in the application's `package.json` file. Usually the `name` field of `package.json` is a short lowercase name, according to the npm modules spec. You should usually also specify a `productName` field, which is your application's full capitalized name, and which will be preferred over `name` by Electron. ### `app.setName(name)` * `name` string Overrides the current application's name. **Note:** This function overrides the name used internally by Electron; it does not affect the name that the OS uses. ### `app.getLocale()` Returns `string` - The current application locale, fetched using Chromium's `l10n_util` library. Possible return values are documented [here](https://source.chromium.org/chromium/chromium/src/+/main:ui/base/l10n/l10n_util.cc). To set the locale, you'll want to use a command line switch at app startup, which may be found [here](command-line-switches.md). **Note:** When distributing your packaged app, you have to also ship the `locales` folder. **Note:** On Windows, you have to call it after the `ready` events gets emitted. ### `app.getLocaleCountryCode()` Returns `string` - User operating system's locale two-letter [ISO 3166](https://www.iso.org/iso-3166-country-codes.html) country code. The value is taken from native OS APIs. **Note:** When unable to detect locale country code, it returns empty string. ### `app.addRecentDocument(path)` _macOS_ _Windows_ * `path` string Adds `path` to the recent documents list. This list is managed by the OS. On Windows, you can visit the list from the task bar, and on macOS, you can visit it from dock menu. ### `app.clearRecentDocuments()` _macOS_ _Windows_ Clears the recent documents list. ### `app.setAsDefaultProtocolClient(protocol[, path, args])` * `protocol` string - The name of your protocol, without `://`. For example, if you want your app to handle `electron://` links, call this method with `electron` as the parameter. * `path` string (optional) _Windows_ - The path to the Electron executable. Defaults to `process.execPath` * `args` string[] (optional) _Windows_ - Arguments passed to the executable. Defaults to an empty array Returns `boolean` - Whether the call succeeded. Sets the current executable as the default handler for a protocol (aka URI scheme). It allows you to integrate your app deeper into the operating system. Once registered, all links with `your-protocol://` will be opened with the current executable. The whole link, including protocol, will be passed to your application as a parameter. **Note:** On macOS, you can only register protocols that have been added to your app's `info.plist`, which cannot be modified at runtime. However, you can change the file during build time via [Electron Forge][electron-forge], [Electron Packager][electron-packager], or by editing `info.plist` with a text editor. Please refer to [Apple's documentation][CFBundleURLTypes] for details. **Note:** In a Windows Store environment (when packaged as an `appx`) this API will return `true` for all calls but the registry key it sets won't be accessible by other applications. In order to register your Windows Store application as a default protocol handler you must [declare the protocol in your manifest](https://docs.microsoft.com/en-us/uwp/schemas/appxpackage/uapmanifestschema/element-uap-protocol). The API uses the Windows Registry and `LSSetDefaultHandlerForURLScheme` internally. ### `app.removeAsDefaultProtocolClient(protocol[, path, args])` _macOS_ _Windows_ * `protocol` string - The name of your protocol, without `://`. * `path` string (optional) _Windows_ - Defaults to `process.execPath` * `args` string[] (optional) _Windows_ - Defaults to an empty array Returns `boolean` - Whether the call succeeded. This method checks if the current executable as the default handler for a protocol (aka URI scheme). If so, it will remove the app as the default handler. ### `app.isDefaultProtocolClient(protocol[, path, args])` * `protocol` string - The name of your protocol, without `://`. * `path` string (optional) _Windows_ - Defaults to `process.execPath` * `args` string[] (optional) _Windows_ - Defaults to an empty array Returns `boolean` - Whether the current executable is the default handler for a protocol (aka URI scheme). **Note:** On macOS, you can use this method to check if the app has been registered as the default protocol handler for a protocol. You can also verify this by checking `~/Library/Preferences/com.apple.LaunchServices.plist` on the macOS machine. Please refer to [Apple's documentation][LSCopyDefaultHandlerForURLScheme] for details. The API uses the Windows Registry and `LSCopyDefaultHandlerForURLScheme` internally. ### `app.getApplicationNameForProtocol(url)` * `url` string - a URL with the protocol name to check. Unlike the other methods in this family, this accepts an entire URL, including `://` at a minimum (e.g. `https://`). Returns `string` - Name of the application handling the protocol, or an empty string if there is no handler. For instance, if Electron is the default handler of the URL, this could be `Electron` on Windows and Mac. However, don't rely on the precise format which is not guaranteed to remain unchanged. Expect a different format on Linux, possibly with a `.desktop` suffix. This method returns the application name of the default handler for the protocol (aka URI scheme) of a URL. ### `app.getApplicationInfoForProtocol(url)` _macOS_ _Windows_ * `url` string - a URL with the protocol name to check. Unlike the other methods in this family, this accepts an entire URL, including `://` at a minimum (e.g. `https://`). Returns `Promise<Object>` - Resolve with an object containing the following: * `icon` NativeImage - the display icon of the app handling the protocol. * `path` string - installation path of the app handling the protocol. * `name` string - display name of the app handling the protocol. This method returns a promise that contains the application name, icon and path of the default handler for the protocol (aka URI scheme) of a URL. ### `app.setUserTasks(tasks)` _Windows_ * `tasks` [Task[]](structures/task.md) - Array of `Task` objects Adds `tasks` to the [Tasks][tasks] category of the Jump List on Windows. `tasks` is an array of [`Task`](structures/task.md) objects. Returns `boolean` - Whether the call succeeded. **Note:** If you'd like to customize the Jump List even more use `app.setJumpList(categories)` instead. ### `app.getJumpListSettings()` _Windows_ Returns `Object`: * `minItems` Integer - The minimum number of items that will be shown in the Jump List (for a more detailed description of this value see the [MSDN docs][JumpListBeginListMSDN]). * `removedItems` [JumpListItem[]](structures/jump-list-item.md) - Array of `JumpListItem` objects that correspond to items that the user has explicitly removed from custom categories in the Jump List. These items must not be re-added to the Jump List in the **next** call to `app.setJumpList()`, Windows will not display any custom category that contains any of the removed items. ### `app.setJumpList(categories)` _Windows_ * `categories` [JumpListCategory[]](structures/jump-list-category.md) | `null` - Array of `JumpListCategory` objects. Sets or removes a custom Jump List for the application, and returns one of the following strings: * `ok` - Nothing went wrong. * `error` - One or more errors occurred, enable runtime logging to figure out the likely cause. * `invalidSeparatorError` - An attempt was made to add a separator to a custom category in the Jump List. Separators are only allowed in the standard `Tasks` category. * `fileTypeRegistrationError` - An attempt was made to add a file link to the Jump List for a file type the app isn't registered to handle. * `customCategoryAccessDeniedError` - Custom categories can't be added to the Jump List due to user privacy or group policy settings. If `categories` is `null` the previously set custom Jump List (if any) will be replaced by the standard Jump List for the app (managed by Windows). **Note:** If a `JumpListCategory` object has neither the `type` nor the `name` property set then its `type` is assumed to be `tasks`. If the `name` property is set but the `type` property is omitted then the `type` is assumed to be `custom`. **Note:** Users can remove items from custom categories, and Windows will not allow a removed item to be added back into a custom category until **after** the next successful call to `app.setJumpList(categories)`. Any attempt to re-add a removed item to a custom category earlier than that will result in the entire custom category being omitted from the Jump List. The list of removed items can be obtained using `app.getJumpListSettings()`. **Note:** The maximum length of a Jump List item's `description` property is 260 characters. Beyond this limit, the item will not be added to the Jump List, nor will it be displayed. Here's a very simple example of creating a custom Jump List: ```javascript const { app } = require('electron') app.setJumpList([ { type: 'custom', name: 'Recent Projects', items: [ { type: 'file', path: 'C:\\Projects\\project1.proj' }, { type: 'file', path: 'C:\\Projects\\project2.proj' } ] }, { // has a name so `type` is assumed to be "custom" name: 'Tools', items: [ { type: 'task', title: 'Tool A', program: process.execPath, args: '--run-tool-a', icon: process.execPath, iconIndex: 0, description: 'Runs Tool A' }, { type: 'task', title: 'Tool B', program: process.execPath, args: '--run-tool-b', icon: process.execPath, iconIndex: 0, description: 'Runs Tool B' } ] }, { type: 'frequent' }, { // has no name and no type so `type` is assumed to be "tasks" items: [ { type: 'task', title: 'New Project', program: process.execPath, args: '--new-project', description: 'Create a new project.' }, { type: 'separator' }, { type: 'task', title: 'Recover Project', program: process.execPath, args: '--recover-project', description: 'Recover Project' } ] } ]) ``` ### `app.requestSingleInstanceLock([additionalData])` * `additionalData` Record<any, any> (optional) - A JSON object containing additional data to send to the first instance. Returns `boolean` The return value of this method indicates whether or not this instance of your application successfully obtained the lock. If it failed to obtain the lock, you can assume that another instance of your application is already running with the lock and exit immediately. I.e. This method returns `true` if your process is the primary instance of your application and your app should continue loading. It returns `false` if your process should immediately quit as it has sent its parameters to another instance that has already acquired the lock. On macOS, the system enforces single instance automatically when users try to open a second instance of your app in Finder, and the `open-file` and `open-url` events will be emitted for that. However when users start your app in command line, the system's single instance mechanism will be bypassed, and you have to use this method to ensure single instance. An example of activating the window of primary instance when a second instance starts: ```javascript const { app } = require('electron') let myWindow = null app.on('first-instance-ack', (event, additionalData) => { // Print out the ack received from the first instance. // Note this event handler must come before the requestSingleInstanceLock call. // Expected output: '{"myAckKey":"myAckValue"}' console.log(JSON.stringify(additionalData)) }) const additionalData = { myKey: 'myValue' } const gotTheLock = app.requestSingleInstanceLock(additionalData) if (!gotTheLock) { app.quit() } else { app.on('second-instance', (event, commandLine, workingDirectory, additionalData) => { // We must call preventDefault if we're sending back data. event.preventDefault() // Print out data received from the second instance. // Expected output: '{"myKey":"myValue"}' console.log(JSON.stringify(additionalData)) // Someone tried to run a second instance, we should focus our window. if (myWindow) { if (myWindow.isMinimized()) myWindow.restore() myWindow.focus() } const ackData = { myAckKey: 'myAckValue' } ackCallback(ackData) }) // Create myWindow, load the rest of the app, etc... app.whenReady().then(() => { myWindow = createWindow() }) } ``` ### `app.hasSingleInstanceLock()` Returns `boolean` This method returns whether or not this instance of your app is currently holding the single instance lock. You can request the lock with `app.requestSingleInstanceLock()` and release with `app.releaseSingleInstanceLock()` ### `app.releaseSingleInstanceLock()` Releases all locks that were created by `requestSingleInstanceLock`. This will allow multiple instances of the application to once again run side by side. ### `app.setUserActivity(type, userInfo[, webpageURL])` _macOS_ * `type` string - Uniquely identifies the activity. Maps to [`NSUserActivity.activityType`][activity-type]. * `userInfo` any - App-specific state to store for use by another device. * `webpageURL` string (optional) - The webpage to load in a browser if no suitable app is installed on the resuming device. The scheme must be `http` or `https`. Creates an `NSUserActivity` and sets it as the current activity. The activity is eligible for [Handoff][handoff] to another device afterward. ### `app.getCurrentActivityType()` _macOS_ Returns `string` - The type of the currently running activity. ### `app.invalidateCurrentActivity()` _macOS_ Invalidates the current [Handoff][handoff] user activity. ### `app.resignCurrentActivity()` _macOS_ Marks the current [Handoff][handoff] user activity as inactive without invalidating it. ### `app.updateCurrentActivity(type, userInfo)` _macOS_ * `type` string - Uniquely identifies the activity. Maps to [`NSUserActivity.activityType`][activity-type]. * `userInfo` any - App-specific state to store for use by another device. Updates the current activity if its type matches `type`, merging the entries from `userInfo` into its current `userInfo` dictionary. ### `app.setAppUserModelId(id)` _Windows_ * `id` string Changes the [Application User Model ID][app-user-model-id] to `id`. ### `app.setActivationPolicy(policy)` _macOS_ * `policy` string - Can be 'regular', 'accessory', or 'prohibited'. Sets the activation policy for a given app. Activation policy types: * 'regular' - The application is an ordinary app that appears in the Dock and may have a user interface. * 'accessory' - The application doesn’t appear in the Dock and doesn’t have a menu bar, but it may be activated programmatically or by clicking on one of its windows. * 'prohibited' - The application doesn’t appear in the Dock and may not create windows or be activated. ### `app.importCertificate(options, callback)` _Linux_ * `options` Object * `certificate` string - Path for the pkcs12 file. * `password` string - Passphrase for the certificate. * `callback` Function * `result` Integer - Result of import. Imports the certificate in pkcs12 format into the platform certificate store. `callback` is called with the `result` of import operation, a value of `0` indicates success while any other value indicates failure according to Chromium [net_error_list](https://source.chromium.org/chromium/chromium/src/+/main:net/base/net_error_list.h). ### `app.configureHostResolver(options)` * `options` Object * `enableBuiltInResolver` boolean (optional) - Whether the built-in host resolver is used in preference to getaddrinfo. When enabled, the built-in resolver will attempt to use the system's DNS settings to do DNS lookups itself. Enabled by default on macOS, disabled by default on Windows and Linux. * `secureDnsMode` string (optional) - Can be "off", "automatic" or "secure". Configures the DNS-over-HTTP mode. When "off", no DoH lookups will be performed. When "automatic", DoH lookups will be performed first if DoH is available, and insecure DNS lookups will be performed as a fallback. When "secure", only DoH lookups will be performed. Defaults to "automatic". * `secureDnsServers` string[]&#32;(optional) - A list of DNS-over-HTTP server templates. See [RFC8484 § 3][] for details on the template format. Most servers support the POST method; the template for such servers is simply a URI. Note that for [some DNS providers][doh-providers], the resolver will automatically upgrade to DoH unless DoH is explicitly disabled, even if there are no DoH servers provided in this list. * `enableAdditionalDnsQueryTypes` boolean (optional) - Controls whether additional DNS query types, e.g. HTTPS (DNS type 65) will be allowed besides the traditional A and AAAA queries when a request is being made via insecure DNS. Has no effect on Secure DNS which always allows additional types. Defaults to true. Configures host resolution (DNS and DNS-over-HTTPS). By default, the following resolvers will be used, in order: 1. DNS-over-HTTPS, if the [DNS provider supports it][doh-providers], then 2. the built-in resolver (enabled on macOS only by default), then 3. the system's resolver (e.g. `getaddrinfo`). This can be configured to either restrict usage of non-encrypted DNS (`secureDnsMode: "secure"`), or disable DNS-over-HTTPS (`secureDnsMode: "off"`). It is also possible to enable or disable the built-in resolver. To disable insecure DNS, you can specify a `secureDnsMode` of `"secure"`. If you do so, you should make sure to provide a list of DNS-over-HTTPS servers to use, in case the user's DNS configuration does not include a provider that supports DoH. ```js app.configureHostResolver({ secureDnsMode: 'secure', secureDnsServers: [ 'https://cloudflare-dns.com/dns-query' ] }) ``` This API must be called after the `ready` event is emitted. [doh-providers]: https://source.chromium.org/chromium/chromium/src/+/main:net/dns/public/doh_provider_entry.cc;l=31?q=%22DohProviderEntry::GetList()%22&ss=chromium%2Fchromium%2Fsrc [RFC8484 § 3]: https://datatracker.ietf.org/doc/html/rfc8484#section-3 ### `app.disableHardwareAcceleration()` Disables hardware acceleration for current app. This method can only be called before app is ready. ### `app.disableDomainBlockingFor3DAPIs()` By default, Chromium disables 3D APIs (e.g. WebGL) until restart on a per domain basis if the GPU processes crashes too frequently. This function disables that behavior. This method can only be called before app is ready. ### `app.getAppMetrics()` Returns [`ProcessMetric[]`](structures/process-metric.md): Array of `ProcessMetric` objects that correspond to memory and CPU usage statistics of all the processes associated with the app. ### `app.getGPUFeatureStatus()` Returns [`GPUFeatureStatus`](structures/gpu-feature-status.md) - The Graphics Feature Status from `chrome://gpu/`. **Note:** This information is only usable after the `gpu-info-update` event is emitted. ### `app.getGPUInfo(infoType)` * `infoType` string - Can be `basic` or `complete`. Returns `Promise<unknown>` For `infoType` equal to `complete`: Promise is fulfilled with `Object` containing all the GPU Information as in [chromium's GPUInfo object](https://chromium.googlesource.com/chromium/src/+/4178e190e9da409b055e5dff469911ec6f6b716f/gpu/config/gpu_info.cc). This includes the version and driver information that's shown on `chrome://gpu` page. For `infoType` equal to `basic`: Promise is fulfilled with `Object` containing fewer attributes than when requested with `complete`. Here's an example of basic response: ```js { auxAttributes: { amdSwitchable: true, canSupportThreadedTextureMailbox: false, directComposition: false, directRendering: true, glResetNotificationStrategy: 0, inProcessGpu: true, initializationTime: 0, jpegDecodeAcceleratorSupported: false, optimus: false, passthroughCmdDecoder: false, sandboxed: false, softwareRendering: false, supportsOverlays: false, videoDecodeAcceleratorFlags: 0 }, gpuDevice: [{ active: true, deviceId: 26657, vendorId: 4098 }, { active: false, deviceId: 3366, vendorId: 32902 }], machineModelName: 'MacBookPro', machineModelVersion: '11.5' } ``` Using `basic` should be preferred if only basic information like `vendorId` or `driverId` is needed. ### `app.setBadgeCount([count])` _Linux_ _macOS_ * `count` Integer (optional) - If a value is provided, set the badge to the provided value otherwise, on macOS, display a plain white dot (e.g. unknown number of notifications). On Linux, if a value is not provided the badge will not display. Returns `boolean` - Whether the call succeeded. Sets the counter badge for current app. Setting the count to `0` will hide the badge. On macOS, it shows on the dock icon. On Linux, it only works for Unity launcher. **Note:** Unity launcher requires a `.desktop` file to work. For more information, please read the [Unity integration documentation][unity-requirement]. ### `app.getBadgeCount()` _Linux_ _macOS_ Returns `Integer` - The current value displayed in the counter badge. ### `app.isUnityRunning()` _Linux_ Returns `boolean` - Whether the current desktop environment is Unity launcher. ### `app.getLoginItemSettings([options])` _macOS_ _Windows_ * `options` Object (optional) * `path` string (optional) _Windows_ - The executable path to compare against. Defaults to `process.execPath`. * `args` string[] (optional) _Windows_ - The command-line arguments to compare against. Defaults to an empty array. If you provided `path` and `args` options to `app.setLoginItemSettings`, then you need to pass the same arguments here for `openAtLogin` to be set correctly. Returns `Object`: * `openAtLogin` boolean - `true` if the app is set to open at login. * `openAsHidden` boolean _macOS_ - `true` if the app is set to open as hidden at login. This setting is not available on [MAS builds][mas-builds]. * `wasOpenedAtLogin` boolean _macOS_ - `true` if the app was opened at login automatically. This setting is not available on [MAS builds][mas-builds]. * `wasOpenedAsHidden` boolean _macOS_ - `true` if the app was opened as a hidden login item. This indicates that the app should not open any windows at startup. This setting is not available on [MAS builds][mas-builds]. * `restoreState` boolean _macOS_ - `true` if the app was opened as a login item that should restore the state from the previous session. This indicates that the app should restore the windows that were open the last time the app was closed. This setting is not available on [MAS builds][mas-builds]. * `executableWillLaunchAtLogin` boolean _Windows_ - `true` if app is set to open at login and its run key is not deactivated. This differs from `openAtLogin` as it ignores the `args` option, this property will be true if the given executable would be launched at login with **any** arguments. * `launchItems` Object[] _Windows_ * `name` string _Windows_ - name value of a registry entry. * `path` string _Windows_ - The executable to an app that corresponds to a registry entry. * `args` string[] _Windows_ - the command-line arguments to pass to the executable. * `scope` string _Windows_ - one of `user` or `machine`. Indicates whether the registry entry is under `HKEY_CURRENT USER` or `HKEY_LOCAL_MACHINE`. * `enabled` boolean _Windows_ - `true` if the app registry key is startup approved and therefore shows as `enabled` in Task Manager and Windows settings. ### `app.setLoginItemSettings(settings)` _macOS_ _Windows_ * `settings` Object * `openAtLogin` boolean (optional) - `true` to open the app at login, `false` to remove the app as a login item. Defaults to `false`. * `openAsHidden` boolean (optional) _macOS_ - `true` to open the app as hidden. Defaults to `false`. The user can edit this setting from the System Preferences so `app.getLoginItemSettings().wasOpenedAsHidden` should be checked when the app is opened to know the current value. This setting is not available on [MAS builds][mas-builds]. * `path` string (optional) _Windows_ - The executable to launch at login. Defaults to `process.execPath`. * `args` string[] (optional) _Windows_ - The command-line arguments to pass to the executable. Defaults to an empty array. Take care to wrap paths in quotes. * `enabled` boolean (optional) _Windows_ - `true` will change the startup approved registry key and `enable / disable` the App in Task Manager and Windows Settings. Defaults to `true`. * `name` string (optional) _Windows_ - value name to write into registry. Defaults to the app's AppUserModelId(). Set the app's login item settings. To work with Electron's `autoUpdater` on Windows, which uses [Squirrel][Squirrel-Windows], you'll want to set the launch path to Update.exe, and pass arguments that specify your application name. For example: ``` javascript const appFolder = path.dirname(process.execPath) const updateExe = path.resolve(appFolder, '..', 'Update.exe') const exeName = path.basename(process.execPath) app.setLoginItemSettings({ openAtLogin: true, path: updateExe, args: [ '--processStart', `"${exeName}"`, '--process-start-args', `"--hidden"` ] }) ``` ### `app.isAccessibilitySupportEnabled()` _macOS_ _Windows_ Returns `boolean` - `true` if Chrome's accessibility support is enabled, `false` otherwise. This API will return `true` if the use of assistive technologies, such as screen readers, has been detected. See https://www.chromium.org/developers/design-documents/accessibility for more details. ### `app.setAccessibilitySupportEnabled(enabled)` _macOS_ _Windows_ * `enabled` boolean - Enable or disable [accessibility tree](https://developers.google.com/web/fundamentals/accessibility/semantics-builtin/the-accessibility-tree) rendering Manually enables Chrome's accessibility support, allowing to expose accessibility switch to users in application settings. See [Chromium's accessibility docs](https://www.chromium.org/developers/design-documents/accessibility) for more details. Disabled by default. This API must be called after the `ready` event is emitted. **Note:** Rendering accessibility tree can significantly affect the performance of your app. It should not be enabled by default. ### `app.showAboutPanel()` Show the app's about panel options. These options can be overridden with `app.setAboutPanelOptions(options)`. ### `app.setAboutPanelOptions(options)` * `options` Object * `applicationName` string (optional) - The app's name. * `applicationVersion` string (optional) - The app's version. * `copyright` string (optional) - Copyright information. * `version` string (optional) _macOS_ - The app's build version number. * `credits` string (optional) _macOS_ _Windows_ - Credit information. * `authors` string[] (optional) _Linux_ - List of app authors. * `website` string (optional) _Linux_ - The app's website. * `iconPath` string (optional) _Linux_ _Windows_ - Path to the app's icon in a JPEG or PNG file format. On Linux, will be shown as 64x64 pixels while retaining aspect ratio. Set the about panel options. This will override the values defined in the app's `.plist` file on macOS. See the [Apple docs][about-panel-options] for more details. On Linux, values must be set in order to be shown; there are no defaults. If you do not set `credits` but still wish to surface them in your app, AppKit will look for a file named "Credits.html", "Credits.rtf", and "Credits.rtfd", in that order, in the bundle returned by the NSBundle class method main. The first file found is used, and if none is found, the info area is left blank. See Apple [documentation](https://developer.apple.com/documentation/appkit/nsaboutpaneloptioncredits?language=objc) for more information. ### `app.isEmojiPanelSupported()` Returns `boolean` - whether or not the current OS version allows for native emoji pickers. ### `app.showEmojiPanel()` _macOS_ _Windows_ Show the platform's native emoji picker. ### `app.startAccessingSecurityScopedResource(bookmarkData)` _mas_ * `bookmarkData` string - The base64 encoded security scoped bookmark data returned by the `dialog.showOpenDialog` or `dialog.showSaveDialog` methods. Returns `Function` - This function **must** be called once you have finished accessing the security scoped file. If you do not remember to stop accessing the bookmark, [kernel resources will be leaked](https://developer.apple.com/reference/foundation/nsurl/1417051-startaccessingsecurityscopedreso?language=objc) and your app will lose its ability to reach outside the sandbox completely, until your app is restarted. ```js // Start accessing the file. const stopAccessingSecurityScopedResource = app.startAccessingSecurityScopedResource(data) // You can now access the file outside of the sandbox 🎉 // Remember to stop accessing the file once you've finished with it. stopAccessingSecurityScopedResource() ``` Start accessing a security scoped resource. With this method Electron applications that are packaged for the Mac App Store may reach outside their sandbox to access files chosen by the user. See [Apple's documentation](https://developer.apple.com/library/content/documentation/Security/Conceptual/AppSandboxDesignGuide/AppSandboxInDepth/AppSandboxInDepth.html#//apple_ref/doc/uid/TP40011183-CH3-SW16) for a description of how this system works. ### `app.enableSandbox()` Enables full sandbox mode on the app. This means that all renderers will be launched sandboxed, regardless of the value of the `sandbox` flag in WebPreferences. This method can only be called before app is ready. ### `app.isInApplicationsFolder()` _macOS_ Returns `boolean` - Whether the application is currently running from the systems Application folder. Use in combination with `app.moveToApplicationsFolder()` ### `app.moveToApplicationsFolder([options])` _macOS_ * `options` Object (optional) * `conflictHandler` Function\<boolean> (optional) - A handler for potential conflict in move failure. * `conflictType` string - The type of move conflict encountered by the handler; can be `exists` or `existsAndRunning`, where `exists` means that an app of the same name is present in the Applications directory and `existsAndRunning` means both that it exists and that it's presently running. Returns `boolean` - Whether the move was successful. Please note that if the move is successful, your application will quit and relaunch. No confirmation dialog will be presented by default. If you wish to allow the user to confirm the operation, you may do so using the [`dialog`](dialog.md) API. **NOTE:** This method throws errors if anything other than the user causes the move to fail. For instance if the user cancels the authorization dialog, this method returns false. If we fail to perform the copy, then this method will throw an error. The message in the error should be informative and tell you exactly what went wrong. By default, if an app of the same name as the one being moved exists in the Applications directory and is _not_ running, the existing app will be trashed and the active app moved into its place. If it _is_ running, the pre-existing running app will assume focus and the previously active app will quit itself. This behavior can be changed by providing the optional conflict handler, where the boolean returned by the handler determines whether or not the move conflict is resolved with default behavior. i.e. returning `false` will ensure no further action is taken, returning `true` will result in the default behavior and the method continuing. For example: ```js app.moveToApplicationsFolder({ conflictHandler: (conflictType) => { if (conflictType === 'exists') { return dialog.showMessageBoxSync({ type: 'question', buttons: ['Halt Move', 'Continue Move'], defaultId: 0, message: 'An app of this name already exists' }) === 1 } } }) ``` Would mean that if an app already exists in the user directory, if the user chooses to 'Continue Move' then the function would continue with its default behavior and the existing app will be trashed and the active app moved into its place. ### `app.isSecureKeyboardEntryEnabled()` _macOS_ Returns `boolean` - whether `Secure Keyboard Entry` is enabled. By default this API will return `false`. ### `app.setSecureKeyboardEntryEnabled(enabled)` _macOS_ * `enabled` boolean - Enable or disable `Secure Keyboard Entry` Set the `Secure Keyboard Entry` is enabled in your application. By using this API, important information such as password and other sensitive information can be prevented from being intercepted by other processes. See [Apple's documentation](https://developer.apple.com/library/archive/technotes/tn2150/_index.html) for more details. **Note:** Enable `Secure Keyboard Entry` only when it is needed and disable it when it is no longer needed. ## Properties ### `app.accessibilitySupportEnabled` _macOS_ _Windows_ A `boolean` property that's `true` if Chrome's accessibility support is enabled, `false` otherwise. This property will be `true` if the use of assistive technologies, such as screen readers, has been detected. Setting this property to `true` manually enables Chrome's accessibility support, allowing developers to expose accessibility switch to users in application settings. See [Chromium's accessibility docs](https://www.chromium.org/developers/design-documents/accessibility) for more details. Disabled by default. This API must be called after the `ready` event is emitted. **Note:** Rendering accessibility tree can significantly affect the performance of your app. It should not be enabled by default. ### `app.applicationMenu` A `Menu | null` property that returns [`Menu`](menu.md) if one has been set and `null` otherwise. Users can pass a [Menu](menu.md) to set this property. ### `app.badgeCount` _Linux_ _macOS_ An `Integer` property that returns the badge count for current app. Setting the count to `0` will hide the badge. On macOS, setting this with any nonzero integer shows on the dock icon. On Linux, this property only works for Unity launcher. **Note:** Unity launcher requires a `.desktop` file to work. For more information, please read the [Unity integration documentation][unity-requirement]. **Note:** On macOS, you need to ensure that your application has the permission to display notifications for this property to take effect. ### `app.commandLine` _Readonly_ A [`CommandLine`](./command-line.md) object that allows you to read and manipulate the command line arguments that Chromium uses. ### `app.dock` _macOS_ _Readonly_ A [`Dock`](./dock.md) `| undefined` object that allows you to perform actions on your app icon in the user's dock on macOS. ### `app.isPackaged` _Readonly_ A `boolean` property that returns `true` if the app is packaged, `false` otherwise. For many apps, this property can be used to distinguish development and production environments. [dock-menu]:https://developer.apple.com/macos/human-interface-guidelines/menus/dock-menus/ [tasks]:https://msdn.microsoft.com/en-us/library/windows/desktop/dd378460(v=vs.85).aspx#tasks [app-user-model-id]: https://msdn.microsoft.com/en-us/library/windows/desktop/dd378459(v=vs.85).aspx [electron-forge]: https://www.electronforge.io/ [electron-packager]: https://github.com/electron/electron-packager [CFBundleURLTypes]: https://developer.apple.com/library/ios/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html#//apple_ref/doc/uid/TP40009249-102207-TPXREF115 [LSCopyDefaultHandlerForURLScheme]: https://developer.apple.com/library/mac/documentation/Carbon/Reference/LaunchServicesReference/#//apple_ref/c/func/LSCopyDefaultHandlerForURLScheme [handoff]: https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/Handoff/HandoffFundamentals/HandoffFundamentals.html [activity-type]: https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSUserActivity_Class/index.html#//apple_ref/occ/instp/NSUserActivity/activityType [unity-requirement]: https://help.ubuntu.com/community/UnityLaunchersAndDesktopFiles#Adding_shortcuts_to_a_launcher [mas-builds]: ../tutorial/mac-app-store-submission-guide.md [Squirrel-Windows]: https://github.com/Squirrel/Squirrel.Windows [JumpListBeginListMSDN]: https://msdn.microsoft.com/en-us/library/windows/desktop/dd378398(v=vs.85).aspx [about-panel-options]: https://developer.apple.com/reference/appkit/nsapplication/1428479-orderfrontstandardaboutpanelwith?language=objc ### `app.name` A `string` property that indicates the current application's name, which is the name in the application's `package.json` file. Usually the `name` field of `package.json` is a short lowercase name, according to the npm modules spec. You should usually also specify a `productName` field, which is your application's full capitalized name, and which will be preferred over `name` by Electron. ### `app.userAgentFallback` A `string` which is the user agent string Electron will use as a global fallback. This is the user agent that will be used when no user agent is set at the `webContents` or `session` level. It is useful for ensuring that your entire app has the same user agent. Set to a custom value as early as possible in your app's initialization to ensure that your overridden value is used. ### `app.runningUnderRosettaTranslation` _macOS_ _Readonly_ _Deprecated_ A `boolean` which when `true` indicates that the app is currently running under the [Rosetta Translator Environment](https://en.wikipedia.org/wiki/Rosetta_(software)). You can use this property to prompt users to download the arm64 version of your application when they are running the x64 version under Rosetta incorrectly. **Deprecated:** This property is superceded by the `runningUnderARM64Translation` property which detects when the app is being translated to ARM64 in both macOS and Windows. ### `app.runningUnderARM64Translation` _Readonly_ _macOS_ _Windows_ A `boolean` which when `true` indicates that the app is currently running under an ARM64 translator (like the macOS [Rosetta Translator Environment](https://en.wikipedia.org/wiki/Rosetta_(software)) or Windows [WOW](https://en.wikipedia.org/wiki/Windows_on_Windows)). You can use this property to prompt users to download the arm64 version of your application when they are running the x64 version under Rosetta incorrectly.
closed
electron/electron
https://github.com/electron/electron
32,718
[Bug]: Segmentation fault in uv_spawn with Electron 17.0.0
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.0.0 ### What operating system are you using? macOS ### Operating System Version macOS Catalina 10.15.7 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior No segmentation fault <img width="993" alt="Crash Report Screenshot" src="https://user-images.githubusercontent.com/2145849/152179191-ed2cec68-5eb9-46b4-981f-4deedec06abc.png"> [Text version of crash report](https://github.com/electron/electron/files/7987634/crash.report.txt) ### Actual Behavior Sometimes, after working for a while, the app crashes giving the Apple Problem Report attached. ### Testcase Gist URL _No response_ ### Additional Information We're hoping to move to Electron 17 ASAP to pick up some Chromium bug fixes. I built an alpha of our application with the new 17.0.0 release yesterday. The crash behavior isn't predictably reproducible that I know of, although it has happened a few times to this user who is one of the employees of our company. I haven't see in at all in my arm64 version or for the 15 minutes I used our x64 version on my old laptop.
https://github.com/electron/electron/issues/32718
https://github.com/electron/electron/pull/33704
097da1d4ba79a78215eb324a23c0ac0cfcae29d5
192a7fad0d548d1883c58bdf95ab7a2ff1391881
2022-02-02T15:07:57Z
c++
2022-04-28T14:28:27Z
shell/browser/resources/mac/Info.plist
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>CFBundleDisplayName</key> <string>${PRODUCT_NAME}</string> <key>CFBundleExecutable</key> <string>${PRODUCT_NAME}</string> <key>CFBundleIdentifier</key> <string>${ELECTRON_BUNDLE_ID}</string> <key>CFBundleInfoDictionaryVersion</key> <string>6.0</string> <key>CFBundleName</key> <string>${PRODUCT_NAME}</string> <key>CFBundlePackageType</key> <string>APPL</string> <key>CFBundleIconFile</key> <string>electron.icns</string> <key>CFBundleVersion</key> <string>${ELECTRON_VERSION}</string> <key>CFBundleShortVersionString</key> <string>${ELECTRON_VERSION}</string> <key>LSApplicationCategoryType</key> <string>public.app-category.developer-tools</string> <key>LSMinimumSystemVersion</key> <string>${MACOSX_DEPLOYMENT_TARGET}</string> <key>NSMainNibFile</key> <string>MainMenu</string> <key>NSPrincipalClass</key> <string>AtomApplication</string> <key>NSAppTransportSecurity</key> <dict> <key>NSAllowsArbitraryLoads</key> <true/> </dict> <key>NSSupportsAutomaticGraphicsSwitching</key> <true/> <key>NSHighResolutionCapable</key> <true/> <key>NSRequiresAquaSystemAppearance</key> <false/> <key>NSQuitAlwaysKeepsWindows</key> <false/> <key>NSMicrophoneUsageDescription</key> <string>This app needs access to the microphone</string> <key>NSCameraUsageDescription</key> <string>This app needs access to the camera</string> <key>NSBluetoothAlwaysUsageDescription</key> <string>This app needs access to Bluetooth</string> <key>NSBluetoothPeripheralUsageDescription</key> <string>This app needs access to Bluetooth</string> <key>ElectronAsarIntegrity</key> <dict> <key>Resources/default_app.asar</key> <dict> <key>algorithm</key> <string>SHA256</string> <key>hash</key> <string>${DEFAULT_APP_ASAR_HEADER_SHA}</string> </dict> </dict> </dict> </plist>
closed
electron/electron
https://github.com/electron/electron
32,718
[Bug]: Segmentation fault in uv_spawn with Electron 17.0.0
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.0.0 ### What operating system are you using? macOS ### Operating System Version macOS Catalina 10.15.7 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior No segmentation fault <img width="993" alt="Crash Report Screenshot" src="https://user-images.githubusercontent.com/2145849/152179191-ed2cec68-5eb9-46b4-981f-4deedec06abc.png"> [Text version of crash report](https://github.com/electron/electron/files/7987634/crash.report.txt) ### Actual Behavior Sometimes, after working for a while, the app crashes giving the Apple Problem Report attached. ### Testcase Gist URL _No response_ ### Additional Information We're hoping to move to Electron 17 ASAP to pick up some Chromium bug fixes. I built an alpha of our application with the new 17.0.0 release yesterday. The crash behavior isn't predictably reproducible that I know of, although it has happened a few times to this user who is one of the employees of our company. I haven't see in at all in my arm64 version or for the 15 minutes I used our x64 version on my old laptop.
https://github.com/electron/electron/issues/32718
https://github.com/electron/electron/pull/33704
097da1d4ba79a78215eb324a23c0ac0cfcae29d5
192a7fad0d548d1883c58bdf95ab7a2ff1391881
2022-02-02T15:07:57Z
c++
2022-04-28T14:28:27Z
shell/common/resources/mac/Info.plist
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>CFBundleIdentifier</key> <string>${ELECTRON_BUNDLE_ID}</string> <key>CFBundleName</key> <string>${PRODUCT_NAME}</string> <key>CFBundleExecutable</key> <string>${PRODUCT_NAME}</string> <key>CFBundlePackageType</key> <string>FMWK</string> <key>NSSupportsAutomaticGraphicsSwitching</key> <true/> <key>CFBundleVersion</key> <string>${ELECTRON_VERSION}</string> </dict> </plist>
closed
electron/electron
https://github.com/electron/electron
32,718
[Bug]: Segmentation fault in uv_spawn with Electron 17.0.0
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.0.0 ### What operating system are you using? macOS ### Operating System Version macOS Catalina 10.15.7 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior No segmentation fault <img width="993" alt="Crash Report Screenshot" src="https://user-images.githubusercontent.com/2145849/152179191-ed2cec68-5eb9-46b4-981f-4deedec06abc.png"> [Text version of crash report](https://github.com/electron/electron/files/7987634/crash.report.txt) ### Actual Behavior Sometimes, after working for a while, the app crashes giving the Apple Problem Report attached. ### Testcase Gist URL _No response_ ### Additional Information We're hoping to move to Electron 17 ASAP to pick up some Chromium bug fixes. I built an alpha of our application with the new 17.0.0 release yesterday. The crash behavior isn't predictably reproducible that I know of, although it has happened a few times to this user who is one of the employees of our company. I haven't see in at all in my arm64 version or for the 15 minutes I used our x64 version on my old laptop.
https://github.com/electron/electron/issues/32718
https://github.com/electron/electron/pull/33704
097da1d4ba79a78215eb324a23c0ac0cfcae29d5
192a7fad0d548d1883c58bdf95ab7a2ff1391881
2022-02-02T15:07:57Z
c++
2022-04-28T14:28:27Z
shell/renderer/resources/mac/Info.plist
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>CFBundleIdentifier</key> <string>${ELECTRON_BUNDLE_ID}</string> <key>CFBundleName</key> <string>${PRODUCT_NAME}</string> <key>CFBundlePackageType</key> <string>APPL</string> <key>LSUIElement</key> <true/> <key>NSSupportsAutomaticGraphicsSwitching</key> <true/> </dict> </plist>
closed
electron/electron
https://github.com/electron/electron
32,718
[Bug]: Segmentation fault in uv_spawn with Electron 17.0.0
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.0.0 ### What operating system are you using? macOS ### Operating System Version macOS Catalina 10.15.7 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior No segmentation fault <img width="993" alt="Crash Report Screenshot" src="https://user-images.githubusercontent.com/2145849/152179191-ed2cec68-5eb9-46b4-981f-4deedec06abc.png"> [Text version of crash report](https://github.com/electron/electron/files/7987634/crash.report.txt) ### Actual Behavior Sometimes, after working for a while, the app crashes giving the Apple Problem Report attached. ### Testcase Gist URL _No response_ ### Additional Information We're hoping to move to Electron 17 ASAP to pick up some Chromium bug fixes. I built an alpha of our application with the new 17.0.0 release yesterday. The crash behavior isn't predictably reproducible that I know of, although it has happened a few times to this user who is one of the employees of our company. I haven't see in at all in my arm64 version or for the 15 minutes I used our x64 version on my old laptop.
https://github.com/electron/electron/issues/32718
https://github.com/electron/electron/pull/33704
097da1d4ba79a78215eb324a23c0ac0cfcae29d5
192a7fad0d548d1883c58bdf95ab7a2ff1391881
2022-02-02T15:07:57Z
c++
2022-04-28T14:28:27Z
shell/browser/resources/mac/Info.plist
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>CFBundleDisplayName</key> <string>${PRODUCT_NAME}</string> <key>CFBundleExecutable</key> <string>${PRODUCT_NAME}</string> <key>CFBundleIdentifier</key> <string>${ELECTRON_BUNDLE_ID}</string> <key>CFBundleInfoDictionaryVersion</key> <string>6.0</string> <key>CFBundleName</key> <string>${PRODUCT_NAME}</string> <key>CFBundlePackageType</key> <string>APPL</string> <key>CFBundleIconFile</key> <string>electron.icns</string> <key>CFBundleVersion</key> <string>${ELECTRON_VERSION}</string> <key>CFBundleShortVersionString</key> <string>${ELECTRON_VERSION}</string> <key>LSApplicationCategoryType</key> <string>public.app-category.developer-tools</string> <key>LSMinimumSystemVersion</key> <string>${MACOSX_DEPLOYMENT_TARGET}</string> <key>NSMainNibFile</key> <string>MainMenu</string> <key>NSPrincipalClass</key> <string>AtomApplication</string> <key>NSAppTransportSecurity</key> <dict> <key>NSAllowsArbitraryLoads</key> <true/> </dict> <key>NSSupportsAutomaticGraphicsSwitching</key> <true/> <key>NSHighResolutionCapable</key> <true/> <key>NSRequiresAquaSystemAppearance</key> <false/> <key>NSQuitAlwaysKeepsWindows</key> <false/> <key>NSMicrophoneUsageDescription</key> <string>This app needs access to the microphone</string> <key>NSCameraUsageDescription</key> <string>This app needs access to the camera</string> <key>NSBluetoothAlwaysUsageDescription</key> <string>This app needs access to Bluetooth</string> <key>NSBluetoothPeripheralUsageDescription</key> <string>This app needs access to Bluetooth</string> <key>ElectronAsarIntegrity</key> <dict> <key>Resources/default_app.asar</key> <dict> <key>algorithm</key> <string>SHA256</string> <key>hash</key> <string>${DEFAULT_APP_ASAR_HEADER_SHA}</string> </dict> </dict> </dict> </plist>
closed
electron/electron
https://github.com/electron/electron
32,718
[Bug]: Segmentation fault in uv_spawn with Electron 17.0.0
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.0.0 ### What operating system are you using? macOS ### Operating System Version macOS Catalina 10.15.7 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior No segmentation fault <img width="993" alt="Crash Report Screenshot" src="https://user-images.githubusercontent.com/2145849/152179191-ed2cec68-5eb9-46b4-981f-4deedec06abc.png"> [Text version of crash report](https://github.com/electron/electron/files/7987634/crash.report.txt) ### Actual Behavior Sometimes, after working for a while, the app crashes giving the Apple Problem Report attached. ### Testcase Gist URL _No response_ ### Additional Information We're hoping to move to Electron 17 ASAP to pick up some Chromium bug fixes. I built an alpha of our application with the new 17.0.0 release yesterday. The crash behavior isn't predictably reproducible that I know of, although it has happened a few times to this user who is one of the employees of our company. I haven't see in at all in my arm64 version or for the 15 minutes I used our x64 version on my old laptop.
https://github.com/electron/electron/issues/32718
https://github.com/electron/electron/pull/33704
097da1d4ba79a78215eb324a23c0ac0cfcae29d5
192a7fad0d548d1883c58bdf95ab7a2ff1391881
2022-02-02T15:07:57Z
c++
2022-04-28T14:28:27Z
shell/common/resources/mac/Info.plist
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>CFBundleIdentifier</key> <string>${ELECTRON_BUNDLE_ID}</string> <key>CFBundleName</key> <string>${PRODUCT_NAME}</string> <key>CFBundleExecutable</key> <string>${PRODUCT_NAME}</string> <key>CFBundlePackageType</key> <string>FMWK</string> <key>NSSupportsAutomaticGraphicsSwitching</key> <true/> <key>CFBundleVersion</key> <string>${ELECTRON_VERSION}</string> </dict> </plist>
closed
electron/electron
https://github.com/electron/electron
32,718
[Bug]: Segmentation fault in uv_spawn with Electron 17.0.0
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.0.0 ### What operating system are you using? macOS ### Operating System Version macOS Catalina 10.15.7 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior No segmentation fault <img width="993" alt="Crash Report Screenshot" src="https://user-images.githubusercontent.com/2145849/152179191-ed2cec68-5eb9-46b4-981f-4deedec06abc.png"> [Text version of crash report](https://github.com/electron/electron/files/7987634/crash.report.txt) ### Actual Behavior Sometimes, after working for a while, the app crashes giving the Apple Problem Report attached. ### Testcase Gist URL _No response_ ### Additional Information We're hoping to move to Electron 17 ASAP to pick up some Chromium bug fixes. I built an alpha of our application with the new 17.0.0 release yesterday. The crash behavior isn't predictably reproducible that I know of, although it has happened a few times to this user who is one of the employees of our company. I haven't see in at all in my arm64 version or for the 15 minutes I used our x64 version on my old laptop.
https://github.com/electron/electron/issues/32718
https://github.com/electron/electron/pull/33704
097da1d4ba79a78215eb324a23c0ac0cfcae29d5
192a7fad0d548d1883c58bdf95ab7a2ff1391881
2022-02-02T15:07:57Z
c++
2022-04-28T14:28:27Z
shell/renderer/resources/mac/Info.plist
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>CFBundleIdentifier</key> <string>${ELECTRON_BUNDLE_ID}</string> <key>CFBundleName</key> <string>${PRODUCT_NAME}</string> <key>CFBundlePackageType</key> <string>APPL</string> <key>LSUIElement</key> <true/> <key>NSSupportsAutomaticGraphicsSwitching</key> <true/> </dict> </plist>
closed
electron/electron
https://github.com/electron/electron
33,844
[Bug]: File Selection Dialog Filter Issue 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 18.0.4 ### What operating system are you using? Ubuntu ### Operating System Version Ubuntu 20.0.4 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior File Selection Dialog should show files with the filtered extension, with no need for case match. ### Example: `*.Foo` files should show up if we set filters for `[{name: 'Foo Files', extensions: ['Foo']}]` or even ``[{name: 'Foo Files', extensions: ['foo']}]`. ### Actual Behavior File Selection Dialog does not show any files if the Filter contains a mixed case extension string. ### Example: `*.Foo` files do not show up if we set filters for `[{name: 'Foo Files', extensions: ['Foo']}]` or even ``[{name: 'Foo Files', extensions: ['foo']}]` and any case match setup. ### Testcase Gist URL https://gist.github.com/047baebf59014c18491c4efdfb75a5f8 ### Additional Information The issue probably come from this [function](https://github.com/electron/electron/blob/main/shell/browser/ui/file_dialog_gtk.cc#L250-L266) (https://github.com/electron/electron/blob/main/shell/browser/ui/file_dialog_gtk.cc#L250-L266) that seems to only check for lowercased or uppercased extensions. ### Example: `[{name: 'Foo Files', extensions: ['Foo']}]` will only show `*.foo` or `*.FOO` files. ### Gist In the provided gist, it will ask you to add a `aim-file.Js` file. Please add it. Then run the fiddle. It will open a File Selection Dialog and will not show the `aim-file.Js`. If you change the file type to `All`, that file will show up.
https://github.com/electron/electron/issues/33844
https://github.com/electron/electron/pull/33918
14f07d7814e3ffd64d18213129ff4a4cfa50e1e1
9901d2f28173d9df4286bf4aa0f8c0726b184ec0
2022-04-20T03:22:37Z
c++
2022-05-02T15:54:17Z
shell/browser/ui/file_dialog_gtk.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 <memory> #include <string> #include "base/callback.h" #include "base/files/file_util.h" #include "base/strings/string_util.h" #include "base/threading/thread_restrictions.h" #include "electron/electron_gtk_stubs.h" #include "shell/browser/javascript_environment.h" #include "shell/browser/native_window_views.h" #include "shell/browser/ui/file_dialog.h" #include "shell/browser/ui/gtk_util.h" #include "shell/browser/unresponsive_suppressor.h" #include "shell/common/gin_converters/file_path_converter.h" #include "ui/base/glib/glib_signal.h" #include "ui/gtk/gtk_ui.h" // nogncheck #include "ui/gtk/gtk_util.h" // nogncheck namespace file_dialog { DialogSettings::DialogSettings() = default; DialogSettings::DialogSettings(const DialogSettings&) = default; DialogSettings::~DialogSettings() = default; namespace { static const int kPreviewWidth = 256; static const int kPreviewHeight = 512; class FileChooserDialog { public: FileChooserDialog(GtkFileChooserAction action, const DialogSettings& settings) : parent_( static_cast<electron::NativeWindowViews*>(settings.parent_window)), filters_(settings.filters) { auto label = settings.button_label; if (electron::IsElectron_gtkInitialized()) { dialog_ = GTK_FILE_CHOOSER(gtk_file_chooser_native_new( settings.title.c_str(), NULL, action, label.empty() ? nullptr : label.c_str(), nullptr)); } else { const char* confirm_text = gtk_util::GetOkLabel(); if (!label.empty()) confirm_text = label.c_str(); else if (action == GTK_FILE_CHOOSER_ACTION_SAVE) confirm_text = gtk_util::GetSaveLabel(); else if (action == GTK_FILE_CHOOSER_ACTION_OPEN) confirm_text = gtk_util::GetOpenLabel(); dialog_ = GTK_FILE_CHOOSER(gtk_file_chooser_dialog_new( settings.title.c_str(), NULL, action, gtk_util::GetCancelLabel(), GTK_RESPONSE_CANCEL, confirm_text, GTK_RESPONSE_ACCEPT, NULL)); } if (parent_) { parent_->SetEnabled(false); if (electron::IsElectron_gtkInitialized()) { gtk_native_dialog_set_modal(GTK_NATIVE_DIALOG(dialog_), TRUE); } else { gtk::SetGtkTransientForAura(GTK_WIDGET(dialog_), parent_->GetNativeWindow()); gtk_window_set_modal(GTK_WINDOW(dialog_), TRUE); } } if (action == GTK_FILE_CHOOSER_ACTION_SAVE) gtk_file_chooser_set_do_overwrite_confirmation(dialog_, TRUE); if (action != GTK_FILE_CHOOSER_ACTION_OPEN) gtk_file_chooser_set_create_folders(dialog_, TRUE); if (!settings.default_path.empty()) { base::ThreadRestrictions::ScopedAllowIO allow_io; if (base::DirectoryExists(settings.default_path)) { gtk_file_chooser_set_current_folder( dialog_, settings.default_path.value().c_str()); } else { if (settings.default_path.IsAbsolute()) { gtk_file_chooser_set_current_folder( dialog_, settings.default_path.DirName().value().c_str()); } gtk_file_chooser_set_current_name( GTK_FILE_CHOOSER(dialog_), settings.default_path.BaseName().value().c_str()); } } if (!settings.filters.empty()) AddFilters(settings.filters); // GtkFileChooserNative does not support preview widgets through the // org.freedesktop.portal.FileChooser portal. In the case of running through // the org.freedesktop.portal.FileChooser portal, anything having to do with // the update-preview signal or the preview widget will just be ignored. if (!electron::IsElectron_gtkInitialized()) { preview_ = gtk_image_new(); g_signal_connect(dialog_, "update-preview", G_CALLBACK(OnUpdatePreviewThunk), this); gtk_file_chooser_set_preview_widget(dialog_, preview_); } } ~FileChooserDialog() { if (electron::IsElectron_gtkInitialized()) { gtk_native_dialog_destroy(GTK_NATIVE_DIALOG(dialog_)); } else { gtk_widget_destroy(GTK_WIDGET(dialog_)); } if (parent_) parent_->SetEnabled(true); } // disable copy FileChooserDialog(const FileChooserDialog&) = delete; FileChooserDialog& operator=(const FileChooserDialog&) = delete; void SetupOpenProperties(int properties) { const auto hasProp = [properties](OpenFileDialogProperty prop) { return gboolean((properties & prop) != 0); }; auto* file_chooser = dialog(); gtk_file_chooser_set_select_multiple(file_chooser, hasProp(OPEN_DIALOG_MULTI_SELECTIONS)); gtk_file_chooser_set_show_hidden(file_chooser, hasProp(OPEN_DIALOG_SHOW_HIDDEN_FILES)); } void SetupSaveProperties(int properties) { const auto hasProp = [properties](SaveFileDialogProperty prop) { return gboolean((properties & prop) != 0); }; auto* file_chooser = dialog(); gtk_file_chooser_set_show_hidden(file_chooser, hasProp(SAVE_DIALOG_SHOW_HIDDEN_FILES)); gtk_file_chooser_set_do_overwrite_confirmation( file_chooser, hasProp(SAVE_DIALOG_SHOW_OVERWRITE_CONFIRMATION)); } void RunAsynchronous() { g_signal_connect(dialog_, "response", G_CALLBACK(OnFileDialogResponseThunk), this); if (electron::IsElectron_gtkInitialized()) { gtk_native_dialog_show(GTK_NATIVE_DIALOG(dialog_)); } else { gtk_widget_show_all(GTK_WIDGET(dialog_)); gtk::GtkUi::GetPlatform()->ShowGtkWindow(GTK_WINDOW(dialog_)); } } void RunSaveAsynchronous( gin_helper::Promise<gin_helper::Dictionary> promise) { save_promise_ = std::make_unique<gin_helper::Promise<gin_helper::Dictionary>>( std::move(promise)); RunAsynchronous(); } void RunOpenAsynchronous( gin_helper::Promise<gin_helper::Dictionary> promise) { open_promise_ = std::make_unique<gin_helper::Promise<gin_helper::Dictionary>>( std::move(promise)); RunAsynchronous(); } base::FilePath GetFileName() const { gchar* filename = gtk_file_chooser_get_filename(dialog_); const base::FilePath path(filename); g_free(filename); return path; } std::vector<base::FilePath> GetFileNames() const { std::vector<base::FilePath> paths; auto* filenames = gtk_file_chooser_get_filenames(GTK_FILE_CHOOSER(dialog_)); for (auto* iter = filenames; iter != nullptr; iter = iter->next) { auto* filename = static_cast<char*>(iter->data); paths.emplace_back(filename); g_free(filename); } g_slist_free(filenames); return paths; } CHROMEG_CALLBACK_1(FileChooserDialog, void, OnFileDialogResponse, GtkWidget*, int); GtkFileChooser* dialog() const { return dialog_; } private: void AddFilters(const Filters& filters); electron::NativeWindowViews* parent_; electron::UnresponsiveSuppressor unresponsive_suppressor_; GtkFileChooser* dialog_; GtkWidget* preview_; Filters filters_; std::unique_ptr<gin_helper::Promise<gin_helper::Dictionary>> save_promise_; std::unique_ptr<gin_helper::Promise<gin_helper::Dictionary>> open_promise_; // Callback for when we update the preview for the selection. CHROMEG_CALLBACK_0(FileChooserDialog, void, OnUpdatePreview, GtkFileChooser*); }; void FileChooserDialog::OnFileDialogResponse(GtkWidget* widget, int response) { if (electron::IsElectron_gtkInitialized()) { gtk_native_dialog_hide(GTK_NATIVE_DIALOG(dialog_)); } else { gtk_widget_hide(GTK_WIDGET(dialog_)); } v8::Isolate* isolate = electron::JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); if (save_promise_) { gin_helper::Dictionary dict = gin::Dictionary::CreateEmpty(save_promise_->isolate()); if (response == GTK_RESPONSE_ACCEPT) { dict.Set("canceled", false); dict.Set("filePath", GetFileName()); } else { dict.Set("canceled", true); dict.Set("filePath", base::FilePath()); } save_promise_->Resolve(dict); } else if (open_promise_) { gin_helper::Dictionary dict = gin::Dictionary::CreateEmpty(open_promise_->isolate()); if (response == GTK_RESPONSE_ACCEPT) { dict.Set("canceled", false); dict.Set("filePaths", GetFileNames()); } else { dict.Set("canceled", true); dict.Set("filePaths", std::vector<base::FilePath>()); } open_promise_->Resolve(dict); } delete this; } void FileChooserDialog::AddFilters(const Filters& filters) { for (const auto& filter : filters) { GtkFileFilter* gtk_filter = gtk_file_filter_new(); for (const auto& extension : filter.second) { // guarantee a pure lowercase variant std::string file_extension = base::ToLowerASCII("*." + extension); gtk_file_filter_add_pattern(gtk_filter, file_extension.c_str()); // guarantee a pure uppercase variant file_extension = base::ToUpperASCII("*." + extension); gtk_file_filter_add_pattern(gtk_filter, file_extension.c_str()); } gtk_file_filter_set_name(gtk_filter, filter.first.c_str()); gtk_file_chooser_add_filter(dialog_, gtk_filter); } } bool CanPreview(const struct stat& st) { // Only preview regular files; pipes may hang. // See https://crbug.com/534754. if (!S_ISREG(st.st_mode)) { return false; } // Don't preview huge files; they may crash. // https://github.com/electron/electron/issues/31630 // Setting an arbitrary filesize max t at 100 MB here. constexpr off_t ArbitraryMax = 100000000ULL; return st.st_size < ArbitraryMax; } void FileChooserDialog::OnUpdatePreview(GtkFileChooser* chooser) { CHECK(!electron::IsElectron_gtkInitialized()); gchar* filename = gtk_file_chooser_get_preview_filename(chooser); if (!filename) { gtk_file_chooser_set_preview_widget_active(chooser, FALSE); return; } struct stat sb; if (stat(filename, &sb) != 0 || !CanPreview(sb)) { g_free(filename); gtk_file_chooser_set_preview_widget_active(chooser, FALSE); return; } // This will preserve the image's aspect ratio. GdkPixbuf* pixbuf = gdk_pixbuf_new_from_file_at_size(filename, kPreviewWidth, kPreviewHeight, nullptr); g_free(filename); if (pixbuf) { gtk_image_set_from_pixbuf(GTK_IMAGE(preview_), pixbuf); g_object_unref(pixbuf); } gtk_file_chooser_set_preview_widget_active(chooser, pixbuf ? TRUE : FALSE); } } // namespace void ShowFileDialog(const FileChooserDialog& dialog) { // gtk_native_dialog_run() will call gtk_native_dialog_show() for us. if (!electron::IsElectron_gtkInitialized()) { gtk_widget_show_all(GTK_WIDGET(dialog.dialog())); } } int RunFileDialog(const FileChooserDialog& dialog) { int response = 0; if (electron::IsElectron_gtkInitialized()) { response = gtk_native_dialog_run(GTK_NATIVE_DIALOG(dialog.dialog())); } else { response = gtk_dialog_run(GTK_DIALOG(dialog.dialog())); } return response; } bool ShowOpenDialogSync(const DialogSettings& settings, std::vector<base::FilePath>* paths) { GtkFileChooserAction action = GTK_FILE_CHOOSER_ACTION_OPEN; if (settings.properties & OPEN_DIALOG_OPEN_DIRECTORY) action = GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER; FileChooserDialog open_dialog(action, settings); open_dialog.SetupOpenProperties(settings.properties); ShowFileDialog(open_dialog); const int response = RunFileDialog(open_dialog); if (response == GTK_RESPONSE_ACCEPT) { *paths = open_dialog.GetFileNames(); return true; } return false; } void ShowOpenDialog(const DialogSettings& settings, gin_helper::Promise<gin_helper::Dictionary> promise) { GtkFileChooserAction action = GTK_FILE_CHOOSER_ACTION_OPEN; if (settings.properties & OPEN_DIALOG_OPEN_DIRECTORY) action = GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER; FileChooserDialog* open_dialog = new FileChooserDialog(action, settings); open_dialog->SetupOpenProperties(settings.properties); open_dialog->RunOpenAsynchronous(std::move(promise)); } bool ShowSaveDialogSync(const DialogSettings& settings, base::FilePath* path) { FileChooserDialog save_dialog(GTK_FILE_CHOOSER_ACTION_SAVE, settings); save_dialog.SetupSaveProperties(settings.properties); ShowFileDialog(save_dialog); const int response = RunFileDialog(save_dialog); if (response == GTK_RESPONSE_ACCEPT) { *path = save_dialog.GetFileName(); return true; } return false; } void ShowSaveDialog(const DialogSettings& settings, gin_helper::Promise<gin_helper::Dictionary> promise) { FileChooserDialog* save_dialog = new FileChooserDialog(GTK_FILE_CHOOSER_ACTION_SAVE, settings); save_dialog->RunSaveAsynchronous(std::move(promise)); } } // namespace file_dialog
closed
electron/electron
https://github.com/electron/electron
33,844
[Bug]: File Selection Dialog Filter Issue 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 18.0.4 ### What operating system are you using? Ubuntu ### Operating System Version Ubuntu 20.0.4 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior File Selection Dialog should show files with the filtered extension, with no need for case match. ### Example: `*.Foo` files should show up if we set filters for `[{name: 'Foo Files', extensions: ['Foo']}]` or even ``[{name: 'Foo Files', extensions: ['foo']}]`. ### Actual Behavior File Selection Dialog does not show any files if the Filter contains a mixed case extension string. ### Example: `*.Foo` files do not show up if we set filters for `[{name: 'Foo Files', extensions: ['Foo']}]` or even ``[{name: 'Foo Files', extensions: ['foo']}]` and any case match setup. ### Testcase Gist URL https://gist.github.com/047baebf59014c18491c4efdfb75a5f8 ### Additional Information The issue probably come from this [function](https://github.com/electron/electron/blob/main/shell/browser/ui/file_dialog_gtk.cc#L250-L266) (https://github.com/electron/electron/blob/main/shell/browser/ui/file_dialog_gtk.cc#L250-L266) that seems to only check for lowercased or uppercased extensions. ### Example: `[{name: 'Foo Files', extensions: ['Foo']}]` will only show `*.foo` or `*.FOO` files. ### Gist In the provided gist, it will ask you to add a `aim-file.Js` file. Please add it. Then run the fiddle. It will open a File Selection Dialog and will not show the `aim-file.Js`. If you change the file type to `All`, that file will show up.
https://github.com/electron/electron/issues/33844
https://github.com/electron/electron/pull/33918
14f07d7814e3ffd64d18213129ff4a4cfa50e1e1
9901d2f28173d9df4286bf4aa0f8c0726b184ec0
2022-04-20T03:22:37Z
c++
2022-05-02T15:54:17Z
shell/browser/ui/file_dialog_gtk.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 <memory> #include <string> #include "base/callback.h" #include "base/files/file_util.h" #include "base/strings/string_util.h" #include "base/threading/thread_restrictions.h" #include "electron/electron_gtk_stubs.h" #include "shell/browser/javascript_environment.h" #include "shell/browser/native_window_views.h" #include "shell/browser/ui/file_dialog.h" #include "shell/browser/ui/gtk_util.h" #include "shell/browser/unresponsive_suppressor.h" #include "shell/common/gin_converters/file_path_converter.h" #include "ui/base/glib/glib_signal.h" #include "ui/gtk/gtk_ui.h" // nogncheck #include "ui/gtk/gtk_util.h" // nogncheck namespace file_dialog { DialogSettings::DialogSettings() = default; DialogSettings::DialogSettings(const DialogSettings&) = default; DialogSettings::~DialogSettings() = default; namespace { static const int kPreviewWidth = 256; static const int kPreviewHeight = 512; class FileChooserDialog { public: FileChooserDialog(GtkFileChooserAction action, const DialogSettings& settings) : parent_( static_cast<electron::NativeWindowViews*>(settings.parent_window)), filters_(settings.filters) { auto label = settings.button_label; if (electron::IsElectron_gtkInitialized()) { dialog_ = GTK_FILE_CHOOSER(gtk_file_chooser_native_new( settings.title.c_str(), NULL, action, label.empty() ? nullptr : label.c_str(), nullptr)); } else { const char* confirm_text = gtk_util::GetOkLabel(); if (!label.empty()) confirm_text = label.c_str(); else if (action == GTK_FILE_CHOOSER_ACTION_SAVE) confirm_text = gtk_util::GetSaveLabel(); else if (action == GTK_FILE_CHOOSER_ACTION_OPEN) confirm_text = gtk_util::GetOpenLabel(); dialog_ = GTK_FILE_CHOOSER(gtk_file_chooser_dialog_new( settings.title.c_str(), NULL, action, gtk_util::GetCancelLabel(), GTK_RESPONSE_CANCEL, confirm_text, GTK_RESPONSE_ACCEPT, NULL)); } if (parent_) { parent_->SetEnabled(false); if (electron::IsElectron_gtkInitialized()) { gtk_native_dialog_set_modal(GTK_NATIVE_DIALOG(dialog_), TRUE); } else { gtk::SetGtkTransientForAura(GTK_WIDGET(dialog_), parent_->GetNativeWindow()); gtk_window_set_modal(GTK_WINDOW(dialog_), TRUE); } } if (action == GTK_FILE_CHOOSER_ACTION_SAVE) gtk_file_chooser_set_do_overwrite_confirmation(dialog_, TRUE); if (action != GTK_FILE_CHOOSER_ACTION_OPEN) gtk_file_chooser_set_create_folders(dialog_, TRUE); if (!settings.default_path.empty()) { base::ThreadRestrictions::ScopedAllowIO allow_io; if (base::DirectoryExists(settings.default_path)) { gtk_file_chooser_set_current_folder( dialog_, settings.default_path.value().c_str()); } else { if (settings.default_path.IsAbsolute()) { gtk_file_chooser_set_current_folder( dialog_, settings.default_path.DirName().value().c_str()); } gtk_file_chooser_set_current_name( GTK_FILE_CHOOSER(dialog_), settings.default_path.BaseName().value().c_str()); } } if (!settings.filters.empty()) AddFilters(settings.filters); // GtkFileChooserNative does not support preview widgets through the // org.freedesktop.portal.FileChooser portal. In the case of running through // the org.freedesktop.portal.FileChooser portal, anything having to do with // the update-preview signal or the preview widget will just be ignored. if (!electron::IsElectron_gtkInitialized()) { preview_ = gtk_image_new(); g_signal_connect(dialog_, "update-preview", G_CALLBACK(OnUpdatePreviewThunk), this); gtk_file_chooser_set_preview_widget(dialog_, preview_); } } ~FileChooserDialog() { if (electron::IsElectron_gtkInitialized()) { gtk_native_dialog_destroy(GTK_NATIVE_DIALOG(dialog_)); } else { gtk_widget_destroy(GTK_WIDGET(dialog_)); } if (parent_) parent_->SetEnabled(true); } // disable copy FileChooserDialog(const FileChooserDialog&) = delete; FileChooserDialog& operator=(const FileChooserDialog&) = delete; void SetupOpenProperties(int properties) { const auto hasProp = [properties](OpenFileDialogProperty prop) { return gboolean((properties & prop) != 0); }; auto* file_chooser = dialog(); gtk_file_chooser_set_select_multiple(file_chooser, hasProp(OPEN_DIALOG_MULTI_SELECTIONS)); gtk_file_chooser_set_show_hidden(file_chooser, hasProp(OPEN_DIALOG_SHOW_HIDDEN_FILES)); } void SetupSaveProperties(int properties) { const auto hasProp = [properties](SaveFileDialogProperty prop) { return gboolean((properties & prop) != 0); }; auto* file_chooser = dialog(); gtk_file_chooser_set_show_hidden(file_chooser, hasProp(SAVE_DIALOG_SHOW_HIDDEN_FILES)); gtk_file_chooser_set_do_overwrite_confirmation( file_chooser, hasProp(SAVE_DIALOG_SHOW_OVERWRITE_CONFIRMATION)); } void RunAsynchronous() { g_signal_connect(dialog_, "response", G_CALLBACK(OnFileDialogResponseThunk), this); if (electron::IsElectron_gtkInitialized()) { gtk_native_dialog_show(GTK_NATIVE_DIALOG(dialog_)); } else { gtk_widget_show_all(GTK_WIDGET(dialog_)); gtk::GtkUi::GetPlatform()->ShowGtkWindow(GTK_WINDOW(dialog_)); } } void RunSaveAsynchronous( gin_helper::Promise<gin_helper::Dictionary> promise) { save_promise_ = std::make_unique<gin_helper::Promise<gin_helper::Dictionary>>( std::move(promise)); RunAsynchronous(); } void RunOpenAsynchronous( gin_helper::Promise<gin_helper::Dictionary> promise) { open_promise_ = std::make_unique<gin_helper::Promise<gin_helper::Dictionary>>( std::move(promise)); RunAsynchronous(); } base::FilePath GetFileName() const { gchar* filename = gtk_file_chooser_get_filename(dialog_); const base::FilePath path(filename); g_free(filename); return path; } std::vector<base::FilePath> GetFileNames() const { std::vector<base::FilePath> paths; auto* filenames = gtk_file_chooser_get_filenames(GTK_FILE_CHOOSER(dialog_)); for (auto* iter = filenames; iter != nullptr; iter = iter->next) { auto* filename = static_cast<char*>(iter->data); paths.emplace_back(filename); g_free(filename); } g_slist_free(filenames); return paths; } CHROMEG_CALLBACK_1(FileChooserDialog, void, OnFileDialogResponse, GtkWidget*, int); GtkFileChooser* dialog() const { return dialog_; } private: void AddFilters(const Filters& filters); electron::NativeWindowViews* parent_; electron::UnresponsiveSuppressor unresponsive_suppressor_; GtkFileChooser* dialog_; GtkWidget* preview_; Filters filters_; std::unique_ptr<gin_helper::Promise<gin_helper::Dictionary>> save_promise_; std::unique_ptr<gin_helper::Promise<gin_helper::Dictionary>> open_promise_; // Callback for when we update the preview for the selection. CHROMEG_CALLBACK_0(FileChooserDialog, void, OnUpdatePreview, GtkFileChooser*); }; void FileChooserDialog::OnFileDialogResponse(GtkWidget* widget, int response) { if (electron::IsElectron_gtkInitialized()) { gtk_native_dialog_hide(GTK_NATIVE_DIALOG(dialog_)); } else { gtk_widget_hide(GTK_WIDGET(dialog_)); } v8::Isolate* isolate = electron::JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); if (save_promise_) { gin_helper::Dictionary dict = gin::Dictionary::CreateEmpty(save_promise_->isolate()); if (response == GTK_RESPONSE_ACCEPT) { dict.Set("canceled", false); dict.Set("filePath", GetFileName()); } else { dict.Set("canceled", true); dict.Set("filePath", base::FilePath()); } save_promise_->Resolve(dict); } else if (open_promise_) { gin_helper::Dictionary dict = gin::Dictionary::CreateEmpty(open_promise_->isolate()); if (response == GTK_RESPONSE_ACCEPT) { dict.Set("canceled", false); dict.Set("filePaths", GetFileNames()); } else { dict.Set("canceled", true); dict.Set("filePaths", std::vector<base::FilePath>()); } open_promise_->Resolve(dict); } delete this; } void FileChooserDialog::AddFilters(const Filters& filters) { for (const auto& filter : filters) { GtkFileFilter* gtk_filter = gtk_file_filter_new(); for (const auto& extension : filter.second) { // guarantee a pure lowercase variant std::string file_extension = base::ToLowerASCII("*." + extension); gtk_file_filter_add_pattern(gtk_filter, file_extension.c_str()); // guarantee a pure uppercase variant file_extension = base::ToUpperASCII("*." + extension); gtk_file_filter_add_pattern(gtk_filter, file_extension.c_str()); } gtk_file_filter_set_name(gtk_filter, filter.first.c_str()); gtk_file_chooser_add_filter(dialog_, gtk_filter); } } bool CanPreview(const struct stat& st) { // Only preview regular files; pipes may hang. // See https://crbug.com/534754. if (!S_ISREG(st.st_mode)) { return false; } // Don't preview huge files; they may crash. // https://github.com/electron/electron/issues/31630 // Setting an arbitrary filesize max t at 100 MB here. constexpr off_t ArbitraryMax = 100000000ULL; return st.st_size < ArbitraryMax; } void FileChooserDialog::OnUpdatePreview(GtkFileChooser* chooser) { CHECK(!electron::IsElectron_gtkInitialized()); gchar* filename = gtk_file_chooser_get_preview_filename(chooser); if (!filename) { gtk_file_chooser_set_preview_widget_active(chooser, FALSE); return; } struct stat sb; if (stat(filename, &sb) != 0 || !CanPreview(sb)) { g_free(filename); gtk_file_chooser_set_preview_widget_active(chooser, FALSE); return; } // This will preserve the image's aspect ratio. GdkPixbuf* pixbuf = gdk_pixbuf_new_from_file_at_size(filename, kPreviewWidth, kPreviewHeight, nullptr); g_free(filename); if (pixbuf) { gtk_image_set_from_pixbuf(GTK_IMAGE(preview_), pixbuf); g_object_unref(pixbuf); } gtk_file_chooser_set_preview_widget_active(chooser, pixbuf ? TRUE : FALSE); } } // namespace void ShowFileDialog(const FileChooserDialog& dialog) { // gtk_native_dialog_run() will call gtk_native_dialog_show() for us. if (!electron::IsElectron_gtkInitialized()) { gtk_widget_show_all(GTK_WIDGET(dialog.dialog())); } } int RunFileDialog(const FileChooserDialog& dialog) { int response = 0; if (electron::IsElectron_gtkInitialized()) { response = gtk_native_dialog_run(GTK_NATIVE_DIALOG(dialog.dialog())); } else { response = gtk_dialog_run(GTK_DIALOG(dialog.dialog())); } return response; } bool ShowOpenDialogSync(const DialogSettings& settings, std::vector<base::FilePath>* paths) { GtkFileChooserAction action = GTK_FILE_CHOOSER_ACTION_OPEN; if (settings.properties & OPEN_DIALOG_OPEN_DIRECTORY) action = GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER; FileChooserDialog open_dialog(action, settings); open_dialog.SetupOpenProperties(settings.properties); ShowFileDialog(open_dialog); const int response = RunFileDialog(open_dialog); if (response == GTK_RESPONSE_ACCEPT) { *paths = open_dialog.GetFileNames(); return true; } return false; } void ShowOpenDialog(const DialogSettings& settings, gin_helper::Promise<gin_helper::Dictionary> promise) { GtkFileChooserAction action = GTK_FILE_CHOOSER_ACTION_OPEN; if (settings.properties & OPEN_DIALOG_OPEN_DIRECTORY) action = GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER; FileChooserDialog* open_dialog = new FileChooserDialog(action, settings); open_dialog->SetupOpenProperties(settings.properties); open_dialog->RunOpenAsynchronous(std::move(promise)); } bool ShowSaveDialogSync(const DialogSettings& settings, base::FilePath* path) { FileChooserDialog save_dialog(GTK_FILE_CHOOSER_ACTION_SAVE, settings); save_dialog.SetupSaveProperties(settings.properties); ShowFileDialog(save_dialog); const int response = RunFileDialog(save_dialog); if (response == GTK_RESPONSE_ACCEPT) { *path = save_dialog.GetFileName(); return true; } return false; } void ShowSaveDialog(const DialogSettings& settings, gin_helper::Promise<gin_helper::Dictionary> promise) { FileChooserDialog* save_dialog = new FileChooserDialog(GTK_FILE_CHOOSER_ACTION_SAVE, settings); save_dialog->RunSaveAsynchronous(std::move(promise)); } } // namespace file_dialog
closed
electron/electron
https://github.com/electron/electron
33,732
[Bug]: `BrowserWindow`: `isFocused()` returns `true` even after calling `blur()` 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 18.0.3 ### What operating system are you using? macOS ### Operating System Version macOS Monterey 12.2.1 ### What arch are you using? x64 ### Last Known Working Electron version Unknown, reproduces back to v14. ### Expected Behavior `isFocused()` should return `false` after `blur()` has been called on it. ### Actual Behavior It returns `true` instead, hence the assertion error: ```sh $ npm test > [email protected] test > electron test.js AssertionError [ERR_ASSERTION]: Expected values to be strictly equal: true !== false at /Users/raisinten/Desktop/temp/project/electron/test.js:10:3 { generatedMessage: true, code: 'ERR_ASSERTION', actual: true, expected: false, operator: 'strictEqual' } $ echo $? 1 ``` ### Testcase Gist URL https://gist.github.com/RaisinTen/245976064623786f2276dd89d2df0185 ### Additional Information _No response_
https://github.com/electron/electron/issues/33732
https://github.com/electron/electron/pull/33734
7dee5179cb0f4a79056204a243aa3317fbe711a6
f887000d505cb6dbc4d195c03f38cef943f135fd
2022-04-12T12:42:24Z
c++
2022-05-03T07:39:18Z
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 <string> #include <utility> #include <vector> #include "base/cxx17_backports.h" #include "base/mac/mac_util.h" #include "base/mac/scoped_cftyperef.h" #include "base/strings/sys_string_conversions.h" #include "base/task/post_task.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/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/inspectable_web_contents.h" #include "shell/browser/ui/inspectable_web_contents_view.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/webrtc/modules/desktop_capture/mac/window_list_utils.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" // This view would inform Chromium to resize the hosted views::View. // // The overridden methods should behave the same with BridgedContentView. @interface ElectronAdaptedContentView : NSView { @private views::NativeWidgetMacNSWindowHost* bridge_host_; } @end @implementation ElectronAdaptedContentView - (id)initWithShell:(electron::NativeWindowMac*)shell { if ((self = [self init])) { bridge_host_ = views::NativeWidgetMacNSWindowHost::GetFromNativeWindow( shell->GetNativeWindow()); } return self; } - (void)viewDidMoveToWindow { // When this view is added to a window, AppKit calls setFrameSize before it is // added to the window, so the behavior in setFrameSize is not triggered. NSWindow* window = [self window]; if (window) [self setFrameSize:NSZeroSize]; } - (void)setFrameSize:(NSSize)newSize { // The size passed in here does not always use // -[NSWindow contentRectForFrameRect]. The following ensures that the // contentView for a frameless window can extend over the titlebar of the new // window containing it, since AppKit requires a titlebar to give frameless // windows correct shadows and rounded corners. NSWindow* window = [self window]; if (window && [window contentView] == self) { newSize = [window contentRectForFrameRect:[window frame]].size; // Ensure that the window geometry be updated on the host side before the // view size is updated. bridge_host_->GetInProcessNSWindowBridge()->UpdateWindowGeometry(); } [super setFrameSize:newSize]; // The OnViewSizeChanged is marked private in derived class. static_cast<remote_cocoa::mojom::NativeWidgetNSWindowHost*>(bridge_host_) ->OnViewSizeChanged(gfx::Size(newSize.width, newSize.height)); } @end // This view always takes the size of its superview. It is intended to be used // as a NSWindow's contentView. It is needed because NSWindow's implementation // explicitly resizes the contentView at inopportune times. @interface FullSizeContentView : NSView @end @implementation FullSizeContentView // 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:(NSSize)size { if ([self superview]) size = [[self superview] bounds].size; [super setFrameSize:size]; } // The contentView gets moved around during certain full-screen operations. // This is less than ideal, and should eventually be removed. - (void)viewDidMoveToSuperview { [self setFrame:[[self superview] bounds]]; } @end @interface ElectronProgressBar : NSProgressIndicator @end @implementation ElectronProgressBar - (void)drawRect:(NSRect)dirtyRect { if (self.style != NSProgressIndicatorBarStyle) 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]]; } } // 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 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; // Removing NSWindowStyleMaskTitled removes window title, which removes // rounded corners of window. bool rounded_corner = true; options.Get(options::kRoundedCorners, &rounded_corner); if (!rounded_corner && !has_frame()) styleMask = 0; if (minimizable) styleMask |= NSMiniaturizableWindowMask; if (closable) styleMask |= NSWindowStyleMaskClosable; if (resizable) styleMask |= NSResizableWindowMask; if (!useStandardWindow || transparent() || !has_frame()) styleMask |= NSTexturedBackgroundWindowMask; // 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, 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_.reset(); }, this)); [window_ setEnableLargerThanScreen:enable_larger_than_screen()]; window_delegate_.reset([[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)]; } 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_.reset([[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()) { if (@available(macOS 10.12, *)) { [window_ setTabbingMode:NSWindowTabbingModeDisallowed]; } } else { if (@available(macOS 10.12, *)) { [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]; // Use an NSEvent monitor to listen for the wheel event. BOOL __block began = NO; wheel_event_monitor_ = [NSEvent addLocalMonitorForEventsMatchingMask:NSEventMaskScrollWheel handler:^(NSEvent* event) { if ([[event window] windowNumber] != [window_ windowNumber]) return event; if (!began && (([event phase] == NSEventPhaseMayBegin) || ([event phase] == NSEventPhaseBegan))) { this->NotifyWindowScrollTouchBegin(); began = YES; } else if (began && (([event phase] == NSEventPhaseEnded) || ([event phase] == NSEventPhaseCancelled))) { this->NotifyWindowScrollTouchEnd(); began = NO; } return event; }]; // 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(); original_frame_ = [window_ frame]; 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 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]. SetEnabled(true); [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() { // Retain the child window before closing it. If the last reference to the // NSWindow goes away inside -[NSWindow close], then bad stuff can happen. // See e.g. http://crbug.com/616701. base::scoped_nsobject<NSWindow> child_window(window_, base::scoped_policy::RETAIN); [window_ close]; } void NativeWindowMac::Focus(bool focus) { if (!IsVisible()) return; if (focus) { [[NSApplication sharedApplication] activateIgnoringOtherApps:NO]; [window_ makeKeyAndOrderFront:nil]; } else { [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]. SetEnabled(true); if (is_modal() && parent()) { [window_ orderOut:nil]; [parent()->GetNativeWindow().GetNativeNSWindow() endSheet:window_]; return; } // Hide all children of the current window before hiding the window. // components/remote_cocoa/app_shim/native_widget_ns_window_bridge.mm // expects this when window visibility changes. if ([window_ childWindows]) { for (NSWindow* child in [window_ childWindows]) { [child orderOut:nil]; } } // Detach the window from the parent before. if (parent()) InternalSetParentWindow(parent(), false); [window_ orderOut:nil]; } bool NativeWindowMac::IsVisible() { bool occluded = [window_ occlusionState] == NSWindowOcclusionStateVisible; // For a window to be visible, it must be visible to the user in the // foreground of the app, which means that it should not be minimized or // occluded return [window_ isVisible] && !occluded && !IsMinimized(); } void NativeWindowMac::SetFullScreenTransitionState( FullScreenTransitionState state) { fullscreen_transition_state_ = state; } bool NativeWindowMac::IsEnabled() { return [window_ attachedSheet] == nil; } void NativeWindowMac::SetEnabled(bool enable) { if (!enable) { [window_ beginSheet:window_ completionHandler:^(NSModalResponse returnCode) { NSLog(@"modal enabled"); 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()) original_frame_ = [window_ frame]; [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() { if (([window_ styleMask] & 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()) original_frame_ = [window_ frame]; [window_ miniaturize:nil]; } void NativeWindowMac::Restore() { [window_ deminiaturize:nil]; } bool NativeWindowMac::IsMinimized() { return [window_ isMiniaturized]; } void NativeWindowMac::HandlePendingFullscreenTransitions() { if (pending_transitions_.empty()) return; bool next_transition = pending_transitions_.front(); pending_transitions_.pop(); SetFullScreen(next_transition); } 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::NONE) { 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()) return; // Take note of the current window size if (IsNormal()) original_frame_ = [window_ frame]; // 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::ENTERING : FullScreenTransitionState::EXITING; [window_ toggleFullScreenMode:nil]; } bool NativeWindowMac::IsFullscreen() const { return [window_ styleMask] & 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; } 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; [window_ orderWindow:NSWindowAbove relativeTo:id.id]; return true; } void NativeWindowMac::MoveTop() { [window_ orderWindow:NSWindowAbove relativeTo:0]; } void NativeWindowMac::SetResizable(bool resizable) { SetStyleMask(resizable, NSWindowStyleMaskResizable); SetCanResize(resizable); } bool NativeWindowMac::IsResizable() { return [window_ styleMask] & NSWindowStyleMaskResizable; } void NativeWindowMac::SetMovable(bool movable) { [window_ setMovable:movable]; } bool NativeWindowMac::IsMovable() { return [window_ isMovable]; } void NativeWindowMac::SetMinimizable(bool minimizable) { SetStyleMask(minimizable, NSMiniaturizableWindowMask); } bool NativeWindowMac::IsMinimizable() { return [window_ styleMask] & NSMiniaturizableWindowMask; } 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 [window_ styleMask] & 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; } else if (level_name == "dock") { // Deprecated by macOS, but kept for backwards compatibility level = NSDockWindowLevel; } 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"; } else if (level == NSDockWindowLevel) { level_name = "dock"; } 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_ flushWindow]; [[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; base::PostTask(FROM_HERE, {content::BrowserThread::UI}, 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()) { original_frame_ = [window_ frame]; 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; SetFullScreen(true); } else if (!kiosk && is_kiosk_) { [NSApp setPresentationOptions:kiosk_options_]; is_kiosk_ = false; SetFullScreen(false); } } 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::SetOpacity(const double opacity) { const double boundedOpacity = base::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)]; } 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]; } 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/+/master:chrome/browser/media/webrtc/native_desktop_media_list.cc;l=372?q=kWindowCaptureMacV2&ss=chromium // 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] autorelease]; [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] autorelease]; [progress_indicator setStyle:NSProgressIndicatorBarStyle]; [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 functionally // mimic 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) { ProcessSerialNumber psn = {0, kCurrentProcess}; if (visibleOnFullScreen) { [window_ setCanHide:NO]; TransformProcessType(&psn, kProcessTransformToUIElementApplication); } else { [window_ setCanHide:YES]; TransformProcessType(&psn, kProcessTransformToForegroundApplication); } } 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 = !([window_ styleMask] & 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::SetVibrancy(const std::string& type) { NSVisualEffectView* vibrantView = [window_ vibrantView]; if (type.empty()) { if (vibrantView == nil) return; [vibrantView removeFromSuperview]; [window_ setVibrantView:nil]; return; } std::string dep_warn = " has been deprecated and removed as of macOS 10.15."; node::Environment* env = node::Environment::GetCurrent(JavascriptEnvironment::GetIsolate()); NSVisualEffectMaterial vibrancyType{}; if (type == "appearance-based") { EmitWarning(env, "NSVisualEffectMaterialAppearanceBased" + dep_warn, "electron"); vibrancyType = NSVisualEffectMaterialAppearanceBased; } else if (type == "light") { EmitWarning(env, "NSVisualEffectMaterialLight" + dep_warn, "electron"); vibrancyType = NSVisualEffectMaterialLight; } else if (type == "dark") { EmitWarning(env, "NSVisualEffectMaterialDark" + dep_warn, "electron"); vibrancyType = NSVisualEffectMaterialDark; } else if (type == "titlebar") { vibrancyType = NSVisualEffectMaterialTitlebar; } 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 == "medium-light") { EmitWarning(env, "NSVisualEffectMaterialMediumLight" + dep_warn, "electron"); vibrancyType = NSVisualEffectMaterialMediumLight; } else if (type == "ultra-dark") { EmitWarning(env, "NSVisualEffectMaterialUltraDark" + dep_warn, "electron"); vibrancyType = NSVisualEffectMaterialUltraDark; } if (@available(macOS 10.14, *)) { 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]] autorelease]; [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; // The visibility of window buttons are managed by |buttons_proxy_| if the // style is customButtonsOnHover. if (title_bar_style_ == TitleBarStyle::kCustomButtonsOnHover) [buttons_proxy_ setVisible:visible]; else InternalSetWindowButtonVisibility(visible); NotifyLayoutWindowControlsOverlay(); } bool NativeWindowMac::GetWindowButtonVisibility() const { return ![window_ standardWindowButton:NSWindowZoomButton].hidden || ![window_ standardWindowButton:NSWindowMiniaturizeButton].hidden || ![window_ standardWindowButton:NSWindowCloseButton].hidden; } void NativeWindowMac::SetTrafficLightPosition( 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::GetTrafficLightPosition() 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) { if (@available(macOS 10.12.2, *)) { touch_bar_.reset([[ElectronTouchBar alloc] initWithDelegate:window_delegate_.get() window:this settings:std::move(items)]); [window_ setTouchBar:nil]; } } void NativeWindowMac::RefreshTouchBarItem(const std::string& item_id) { if (@available(macOS 10.12.2, *)) { if (touch_bar_ && [window_ touchBar]) [touch_bar_ refreshTouchBarItem:[window_ touchBar] id:item_id]; } } void NativeWindowMac::SetEscapeTouchBarItem( gin_helper::PersistentDictionary item) { if (@available(macOS 10.12.2, *)) { if (touch_bar_ && [window_ touchBar]) [touch_bar_ setEscapeTouchBarItem:std::move(item) forTouchBar:[window_ touchBar]]; } } void NativeWindowMac::SelectPreviousTab() { if (@available(macOS 10.12, *)) { [window_ selectPreviousTab:nil]; } } void NativeWindowMac::SelectNextTab() { if (@available(macOS 10.12, *)) { [window_ selectNextTab:nil]; } } void NativeWindowMac::MergeAllWindows() { if (@available(macOS 10.12, *)) { [window_ mergeAllWindows:nil]; } } void NativeWindowMac::MoveTabToNewWindow() { if (@available(macOS 10.12, *)) { [window_ moveTabToNewWindow:nil]; } } void NativeWindowMac::ToggleTabBar() { if (@available(macOS 10.12, *)) { [window_ toggleTabBar:nil]; } } bool NativeWindowMac::AddTabbedWindow(NativeWindow* window) { if (window_ == window->GetNativeWindow().GetNativeNSWindow()) { return false; } else { if (@available(macOS 10.12, *)) [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_.reset([[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); if (wheel_event_monitor_) { [NSEvent removeMonitor:wheel_event_monitor_]; wheel_event_monitor_ = nil; } } void NativeWindowMac::OverrideNSWindowContentView() { // When using `views::Widget` to hold WebContents, Chromium would use // `BridgedContentView` as content view, which does not support draggable // regions. In order to make draggable regions work, we have to replace the // content view with a simple NSView. if (has_frame()) { container_view_.reset( [[ElectronAdaptedContentView alloc] initWithShell:this]); } else { container_view_.reset([[FullSizeContentView alloc] init]); [container_view_ setFrame:[[[window_ contentView] superview] bounds]]; } [container_view_ setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable]; [window_ setContentView:container_view_]; AddContentViewLayers(); } 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) { base::PostTask( FROM_HERE, {content::BrowserThread::UI}, 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()) { base::scoped_nsobject<CALayer> background_layer([[CALayer alloc] init]); [background_layer setAutoresizingMask:kCALayerWidthSizable | kCALayerHeightSizable]; [[window_ contentView] setLayer:background_layer]; } [[window_ contentView] setWantsLayer:YES]; } if (!has_frame()) { // In OSX 10.10, adding subviews to the root view for the NSView hierarchy // produces warnings. To eliminate the warnings, we resize the contentView // to fill the window, and add subviews to that. // http://crbug.com/380412 if (!original_set_frame_size) { Class cl = [[window_ contentView] class]; original_set_frame_size = class_replaceMethod( cl, @selector(setFrameSize:), (IMP)SetFrameSize, "v@:{_NSSize=ff}"); original_view_did_move_to_superview = class_replaceMethod(cl, @selector(viewDidMoveToSuperview), (IMP)ViewDidMoveToSuperview, "v@:"); [[window_ contentView] viewDidMoveToWindow]; } } } void NativeWindowMac::InternalSetWindowButtonVisibility(bool visible) { [[window_ standardWindowButton:NSWindowCloseButton] setHidden:!visible]; [[window_ standardWindowButton:NSWindowMiniaturizeButton] setHidden:!visible]; [[window_ standardWindowButton:NSWindowZoomButton] setHidden:!visible]; } void NativeWindowMac::InternalSetParentWindow(NativeWindow* parent, bool attach) { if (is_modal()) return; NativeWindow::SetParentWindow(parent); // Do not remove/add if we are already properly attached. if (attach && parent && [window_ parentWindow] == parent->GetNativeWindow().GetNativeNSWindow()) return; // Remove current parent window. if ([window_ parentWindow]) [[window_ parentWindow] removeChildWindow:window_]; // Set new parent window. // Note that this method will force the window to become visible. if (parent && attach) { // Attaching a window as a child window resets its window level, so // save and restore it afterwards. NSInteger level = window_.level; [parent->GetNativeWindow().GetNativeNSWindow() addChildWindow:window_ ordered:NSWindowAbove]; [window_ setLevel:level]; } } 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
33,732
[Bug]: `BrowserWindow`: `isFocused()` returns `true` even after calling `blur()` 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 18.0.3 ### What operating system are you using? macOS ### Operating System Version macOS Monterey 12.2.1 ### What arch are you using? x64 ### Last Known Working Electron version Unknown, reproduces back to v14. ### Expected Behavior `isFocused()` should return `false` after `blur()` has been called on it. ### Actual Behavior It returns `true` instead, hence the assertion error: ```sh $ npm test > [email protected] test > electron test.js AssertionError [ERR_ASSERTION]: Expected values to be strictly equal: true !== false at /Users/raisinten/Desktop/temp/project/electron/test.js:10:3 { generatedMessage: true, code: 'ERR_ASSERTION', actual: true, expected: false, operator: 'strictEqual' } $ echo $? 1 ``` ### Testcase Gist URL https://gist.github.com/RaisinTen/245976064623786f2276dd89d2df0185 ### Additional Information _No response_
https://github.com/electron/electron/issues/33732
https://github.com/electron/electron/pull/33734
7dee5179cb0f4a79056204a243aa3317fbe711a6
f887000d505cb6dbc4d195c03f38cef943f135fd
2022-04-12T12:42:24Z
c++
2022-05-03T07:39:18Z
spec-main/api-browser-window-spec.ts
import { expect } from 'chai'; import * as childProcess from 'child_process'; import * as path from 'path'; import * as fs from 'fs'; import * as os from 'os'; import * as qs from 'querystring'; import * as http from 'http'; import * as semver from 'semver'; import { AddressInfo } from 'net'; import { app, BrowserWindow, BrowserView, dialog, ipcMain, OnBeforeSendHeadersListenerDetails, protocol, screen, webContents, session, WebContents, BrowserWindowConstructorOptions } from 'electron/main'; import { emittedOnce, emittedUntil, emittedNTimes } from './events-helpers'; import { ifit, ifdescribe, defer, delay } from './spec-helpers'; import { closeWindow, closeAllWindows } from './window-helpers'; import { areColorsSimilar, captureScreen, CHROMA_COLOR_HEX, getPixelColor } from './screen-helpers'; const features = process._linkedBinding('electron_common_features'); const fixtures = path.resolve(__dirname, '..', 'spec', 'fixtures'); const mainFixtures = path.resolve(__dirname, 'fixtures'); // Is the display's scale factor possibly causing rounding of pixel coordinate // values? const isScaleFactorRounding = () => { const { scaleFactor } = screen.getPrimaryDisplay(); // Return true if scale factor is non-integer value if (Math.round(scaleFactor) !== scaleFactor) return true; // Return true if scale factor is odd number above 2 return scaleFactor > 2 && scaleFactor % 2 === 1; }; const expectBoundsEqual = (actual: any, expected: any) => { if (!isScaleFactorRounding()) { expect(expected).to.deep.equal(actual); } else if (Array.isArray(actual)) { expect(actual[0]).to.be.closeTo(expected[0], 1); expect(actual[1]).to.be.closeTo(expected[1], 1); } else { expect(actual.x).to.be.closeTo(expected.x, 1); expect(actual.y).to.be.closeTo(expected.y, 1); expect(actual.width).to.be.closeTo(expected.width, 1); expect(actual.height).to.be.closeTo(expected.height, 1); } }; const isBeforeUnload = (event: Event, level: number, message: string) => { return (message === 'beforeunload'); }; describe('BrowserWindow module', () => { describe('BrowserWindow constructor', () => { it('allows passing void 0 as the webContents', async () => { expect(() => { const w = new BrowserWindow({ show: false, // apparently void 0 had different behaviour from undefined in the // issue that this test is supposed to catch. webContents: void 0 // eslint-disable-line no-void } as any); w.destroy(); }).not.to.throw(); }); ifit(process.platform === 'linux')('does not crash when setting large window icons', async () => { const appPath = path.join(__dirname, 'spec-main', 'fixtures', 'apps', 'xwindow-icon'); const appProcess = childProcess.spawn(process.execPath, [appPath]); await new Promise((resolve) => { appProcess.once('exit', resolve); }); }); it('does not crash or throw when passed an invalid icon', async () => { expect(() => { const w = new BrowserWindow({ icon: undefined } as any); w.destroy(); }).not.to.throw(); }); }); describe('garbage collection', () => { const v8Util = process._linkedBinding('electron_common_v8_util'); afterEach(closeAllWindows); it('window does not get garbage collected when opened', async () => { const w = new BrowserWindow({ show: false }); // Keep a weak reference to the window. // eslint-disable-next-line no-undef const wr = new WeakRef(w); await delay(); // Do garbage collection, since |w| is not referenced in this closure // it would be gone after next call if there is no other reference. v8Util.requestGarbageCollectionForTesting(); await delay(); expect(wr.deref()).to.not.be.undefined(); }); }); describe('BrowserWindow.close()', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('should work if called when a messageBox is showing', async () => { const closed = emittedOnce(w, 'closed'); dialog.showMessageBox(w, { message: 'Hello Error' }); w.close(); await closed; }); it('closes window without rounded corners', async () => { await closeWindow(w); w = new BrowserWindow({ show: false, frame: false, roundedCorners: false }); const closed = emittedOnce(w, 'closed'); w.close(); await closed; }); it('should not crash if called after webContents is destroyed', () => { w.webContents.destroy(); w.webContents.on('destroyed', () => w.close()); }); it('should emit unload handler', async () => { await w.loadFile(path.join(fixtures, 'api', 'unload.html')); const closed = emittedOnce(w, 'closed'); w.close(); await closed; const test = path.join(fixtures, 'api', 'unload'); const content = fs.readFileSync(test); fs.unlinkSync(test); expect(String(content)).to.equal('unload'); }); it('should emit beforeunload handler', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); await emittedOnce(w.webContents, 'before-unload-fired'); }); it('should not crash when keyboard event is sent before closing', async () => { await w.loadURL('data:text/html,pls no crash'); const closed = emittedOnce(w, 'closed'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' }); w.close(); await closed; }); describe('when invoked synchronously inside navigation observer', () => { let server: http.Server = null as unknown as http.Server; let url: string = null as unknown as string; before((done) => { server = http.createServer((request, response) => { switch (request.url) { case '/net-error': response.destroy(); break; case '/301': response.statusCode = 301; response.setHeader('Location', '/200'); response.end(); break; case '/200': response.statusCode = 200; response.end('hello'); break; case '/title': response.statusCode = 200; response.end('<title>Hello</title>'); break; default: throw new Error(`unsupported endpoint: ${request.url}`); } }).listen(0, '127.0.0.1', () => { url = 'http://127.0.0.1:' + (server.address() as AddressInfo).port; done(); }); }); after(() => { server.close(); }); const events = [ { name: 'did-start-loading', path: '/200' }, { name: 'dom-ready', path: '/200' }, { name: 'page-title-updated', path: '/title' }, { name: 'did-stop-loading', path: '/200' }, { name: 'did-finish-load', path: '/200' }, { name: 'did-frame-finish-load', path: '/200' }, { name: 'did-fail-load', path: '/net-error' } ]; for (const { name, path } of events) { it(`should not crash when closed during ${name}`, async () => { const w = new BrowserWindow({ show: false }); w.webContents.once((name as any), () => { w.close(); }); const destroyed = emittedOnce(w.webContents, 'destroyed'); w.webContents.loadURL(url + path); await destroyed; }); } }); }); describe('window.close()', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('should emit unload event', async () => { w.loadFile(path.join(fixtures, 'api', 'close.html')); await emittedOnce(w, 'closed'); const test = path.join(fixtures, 'api', 'close'); const content = fs.readFileSync(test).toString(); fs.unlinkSync(test); expect(content).to.equal('close'); }); it('should emit beforeunload event', async function () { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.webContents.executeJavaScript('window.close()', true); await emittedOnce(w.webContents, 'before-unload-fired'); }); }); describe('BrowserWindow.destroy()', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('prevents users to access methods of webContents', async () => { const contents = w.webContents; w.destroy(); await new Promise(setImmediate); expect(() => { contents.getProcessId(); }).to.throw('Object has been destroyed'); }); it('should not crash when destroying windows with pending events', () => { const focusListener = () => { }; app.on('browser-window-focus', focusListener); const windowCount = 3; const windowOptions = { show: false, width: 400, height: 400, webPreferences: { backgroundThrottling: false } }; const windows = Array.from(Array(windowCount)).map(() => new BrowserWindow(windowOptions)); windows.forEach(win => win.show()); windows.forEach(win => win.focus()); windows.forEach(win => win.destroy()); app.removeListener('browser-window-focus', focusListener); }); }); describe('BrowserWindow.loadURL(url)', () => { let w = null as unknown as BrowserWindow; const scheme = 'other'; const srcPath = path.join(fixtures, 'api', 'loaded-from-dataurl.js'); before(() => { protocol.registerFileProtocol(scheme, (request, callback) => { callback(srcPath); }); }); after(() => { protocol.unregisterProtocol(scheme); }); beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); let server = null as unknown as http.Server; let url = null as unknown as string; let postData = null as any; before((done) => { const filePath = path.join(fixtures, 'pages', 'a.html'); const fileStats = fs.statSync(filePath); postData = [ { type: 'rawData', bytes: Buffer.from('username=test&file=') }, { type: 'file', filePath: filePath, offset: 0, length: fileStats.size, modificationTime: fileStats.mtime.getTime() / 1000 } ]; server = http.createServer((req, res) => { function respond () { if (req.method === 'POST') { let body = ''; req.on('data', (data) => { if (data) body += data; }); req.on('end', () => { const parsedData = qs.parse(body); fs.readFile(filePath, (err, data) => { if (err) return; if (parsedData.username === 'test' && parsedData.file === data.toString()) { res.end(); } }); }); } else if (req.url === '/302') { res.setHeader('Location', '/200'); res.statusCode = 302; res.end(); } else { res.end(); } } setTimeout(respond, req.url && req.url.includes('slow') ? 200 : 0); }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; done(); }); }); after(() => { server.close(); }); it('should emit did-start-loading event', async () => { const didStartLoading = emittedOnce(w.webContents, 'did-start-loading'); w.loadURL('about:blank'); await didStartLoading; }); it('should emit ready-to-show event', async () => { const readyToShow = emittedOnce(w, 'ready-to-show'); w.loadURL('about:blank'); await readyToShow; }); // TODO(deepak1556): The error code now seems to be `ERR_FAILED`, verify what // changed and adjust the test. it.skip('should emit did-fail-load event for files that do not exist', async () => { const didFailLoad = emittedOnce(w.webContents, 'did-fail-load'); w.loadURL('file://a.txt'); const [, code, desc,, isMainFrame] = await didFailLoad; expect(code).to.equal(-6); expect(desc).to.equal('ERR_FILE_NOT_FOUND'); expect(isMainFrame).to.equal(true); }); it('should emit did-fail-load event for invalid URL', async () => { const didFailLoad = emittedOnce(w.webContents, 'did-fail-load'); w.loadURL('http://example:port'); const [, code, desc,, isMainFrame] = await didFailLoad; expect(desc).to.equal('ERR_INVALID_URL'); expect(code).to.equal(-300); expect(isMainFrame).to.equal(true); }); it('should set `mainFrame = false` on did-fail-load events in iframes', async () => { const didFailLoad = emittedOnce(w.webContents, 'did-fail-load'); w.loadFile(path.join(fixtures, 'api', 'did-fail-load-iframe.html')); const [,,,, isMainFrame] = await didFailLoad; expect(isMainFrame).to.equal(false); }); it('does not crash in did-fail-provisional-load handler', (done) => { w.webContents.once('did-fail-provisional-load', () => { w.loadURL('http://127.0.0.1:11111'); done(); }); w.loadURL('http://127.0.0.1:11111'); }); it('should emit did-fail-load event for URL exceeding character limit', async () => { const data = Buffer.alloc(2 * 1024 * 1024).toString('base64'); const didFailLoad = emittedOnce(w.webContents, 'did-fail-load'); w.loadURL(`data:image/png;base64,${data}`); const [, code, desc,, isMainFrame] = await didFailLoad; expect(desc).to.equal('ERR_INVALID_URL'); expect(code).to.equal(-300); expect(isMainFrame).to.equal(true); }); it('should return a promise', () => { const p = w.loadURL('about:blank'); expect(p).to.have.property('then'); }); it('should return a promise that resolves', async () => { await expect(w.loadURL('about:blank')).to.eventually.be.fulfilled(); }); it('should return a promise that rejects on a load failure', async () => { const data = Buffer.alloc(2 * 1024 * 1024).toString('base64'); const p = w.loadURL(`data:image/png;base64,${data}`); await expect(p).to.eventually.be.rejected; }); it('should return a promise that resolves even if pushState occurs during navigation', async () => { const p = w.loadURL('data:text/html,<script>window.history.pushState({}, "/foo")</script>'); await expect(p).to.eventually.be.fulfilled; }); describe('POST navigations', () => { afterEach(() => { w.webContents.session.webRequest.onBeforeSendHeaders(null); }); it('supports specifying POST data', async () => { await w.loadURL(url, { postData }); }); it('sets the content type header on URL encoded forms', async () => { await w.loadURL(url); const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => { w.webContents.session.webRequest.onBeforeSendHeaders((details) => { resolve(details); }); }); w.webContents.executeJavaScript(` form = document.createElement('form') document.body.appendChild(form) form.method = 'POST' form.submit() `); const details = await requestDetails; expect(details.requestHeaders['Content-Type']).to.equal('application/x-www-form-urlencoded'); }); it('sets the content type header on multi part forms', async () => { await w.loadURL(url); const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => { w.webContents.session.webRequest.onBeforeSendHeaders((details) => { resolve(details); }); }); w.webContents.executeJavaScript(` form = document.createElement('form') document.body.appendChild(form) form.method = 'POST' form.enctype = 'multipart/form-data' file = document.createElement('input') file.type = 'file' file.name = 'file' form.appendChild(file) form.submit() `); const details = await requestDetails; expect(details.requestHeaders['Content-Type'].startsWith('multipart/form-data; boundary=----WebKitFormBoundary')).to.equal(true); }); }); it('should support base url for data urls', async () => { await w.loadURL('data:text/html,<script src="loaded-from-dataurl.js"></script>', { baseURLForDataURL: `other://${path.join(fixtures, 'api')}${path.sep}` }); expect(await w.webContents.executeJavaScript('window.ping')).to.equal('pong'); }); }); for (const sandbox of [false, true]) { describe(`navigation events${sandbox ? ' with sandbox' : ''}`, () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: false, sandbox } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('will-navigate event', () => { let server = null as unknown as http.Server; let url = null as unknown as string; before((done) => { server = http.createServer((req, res) => { if (req.url === '/navigate-top') { res.end('<a target=_top href="/">navigate _top</a>'); } else { res.end(''); } }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/`; done(); }); }); after(() => { server.close(); }); it('allows the window to be closed from the event listener', (done) => { w.webContents.once('will-navigate', () => { w.close(); done(); }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('can be prevented', (done) => { let willNavigate = false; w.webContents.once('will-navigate', (e) => { willNavigate = true; e.preventDefault(); }); w.webContents.on('did-stop-loading', () => { if (willNavigate) { // i.e. it shouldn't have had '?navigated' appended to it. try { expect(w.webContents.getURL().endsWith('will-navigate.html')).to.be.true(); done(); } catch (e) { done(e); } } }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('is triggered when navigating from file: to http:', async () => { await w.loadFile(path.join(fixtures, 'api', 'blank.html')); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-navigate', (e, url) => { e.preventDefault(); resolve(url); }); }); expect(navigatedTo).to.equal(url); expect(w.webContents.getURL()).to.match(/^file:/); }); it('is triggered when navigating from about:blank to http:', async () => { await w.loadURL('about:blank'); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-navigate', (e, url) => { e.preventDefault(); resolve(url); }); }); expect(navigatedTo).to.equal(url); expect(w.webContents.getURL()).to.equal('about:blank'); }); it('is triggered when a cross-origin iframe navigates _top', async () => { await w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-top"></iframe>`); await delay(1000); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const iframeTarget = targets.targetInfos.find((t: any) => t.type === 'iframe'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: iframeTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); let willNavigateEmitted = false; w.webContents.on('will-navigate', () => { willNavigateEmitted = true; }); await emittedOnce(w.webContents, 'did-navigate'); expect(willNavigateEmitted).to.be.true(); }); }); describe('will-redirect event', () => { let server = null as unknown as http.Server; let url = null as unknown as string; before((done) => { server = http.createServer((req, res) => { if (req.url === '/302') { res.setHeader('Location', '/200'); res.statusCode = 302; res.end(); } else if (req.url === '/navigate-302') { res.end(`<html><body><script>window.location='${url}/302'</script></body></html>`); } else { res.end(); } }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; done(); }); }); after(() => { server.close(); }); it('is emitted on redirects', async () => { const willRedirect = emittedOnce(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await willRedirect; }); it('is emitted after will-navigate on redirects', async () => { let navigateCalled = false; w.webContents.on('will-navigate', () => { navigateCalled = true; }); const willRedirect = emittedOnce(w.webContents, 'will-redirect'); w.loadURL(`${url}/navigate-302`); await willRedirect; expect(navigateCalled).to.equal(true, 'should have called will-navigate first'); }); it('is emitted before did-stop-loading on redirects', async () => { let stopCalled = false; w.webContents.on('did-stop-loading', () => { stopCalled = true; }); const willRedirect = emittedOnce(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await willRedirect; expect(stopCalled).to.equal(false, 'should not have called did-stop-loading first'); }); it('allows the window to be closed from the event listener', (done) => { w.webContents.once('will-redirect', () => { w.close(); done(); }); w.loadURL(`${url}/302`); }); it('can be prevented', (done) => { w.webContents.once('will-redirect', (event) => { event.preventDefault(); }); w.webContents.on('will-navigate', (e, u) => { expect(u).to.equal(`${url}/302`); }); w.webContents.on('did-stop-loading', () => { try { expect(w.webContents.getURL()).to.equal( `${url}/navigate-302`, 'url should not have changed after navigation event' ); done(); } catch (e) { done(e); } }); w.webContents.on('will-redirect', (e, u) => { try { expect(u).to.equal(`${url}/200`); } catch (e) { done(e); } }); w.loadURL(`${url}/navigate-302`); }); }); }); } describe('focus and visibility', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.show()', () => { it('should focus on window', () => { w.show(); expect(w.isFocused()).to.equal(true); }); it('should make the window visible', () => { w.show(); expect(w.isVisible()).to.equal(true); }); it('emits when window is shown', async () => { const show = emittedOnce(w, 'show'); w.show(); await show; expect(w.isVisible()).to.equal(true); }); }); describe('BrowserWindow.hide()', () => { it('should defocus on window', () => { w.hide(); expect(w.isFocused()).to.equal(false); }); it('should make the window not visible', () => { w.show(); w.hide(); expect(w.isVisible()).to.equal(false); }); it('emits when window is hidden', async () => { const shown = emittedOnce(w, 'show'); w.show(); await shown; const hidden = emittedOnce(w, 'hide'); w.hide(); await hidden; expect(w.isVisible()).to.equal(false); }); }); describe('BrowserWindow.showInactive()', () => { it('should not focus on window', () => { w.showInactive(); expect(w.isFocused()).to.equal(false); }); // TODO(dsanders11): Enable for Linux once CI plays nice with these kinds of tests ifit(process.platform !== 'linux')('should not restore maximized windows', async () => { const maximize = emittedOnce(w, 'maximize'); const shown = emittedOnce(w, 'show'); w.maximize(); // TODO(dsanders11): The maximize event isn't firing on macOS for a window initially hidden if (process.platform !== 'darwin') { await maximize; } else { await delay(1000); } w.showInactive(); await shown; expect(w.isMaximized()).to.equal(true); }); }); describe('BrowserWindow.focus()', () => { it('does not make the window become visible', () => { expect(w.isVisible()).to.equal(false); w.focus(); expect(w.isVisible()).to.equal(false); }); }); describe('BrowserWindow.blur()', () => { it('removes focus from window', () => { w.blur(); expect(w.isFocused()).to.equal(false); }); }); describe('BrowserWindow.getFocusedWindow()', () => { it('returns the opener window when dev tools window is focused', async () => { w.show(); w.webContents.openDevTools({ mode: 'undocked' }); await emittedOnce(w.webContents, 'devtools-focused'); expect(BrowserWindow.getFocusedWindow()).to.equal(w); }); }); describe('BrowserWindow.moveTop()', () => { it('should not steal focus', async () => { const posDelta = 50; const wShownInactive = emittedOnce(w, 'show'); w.showInactive(); await wShownInactive; expect(w.isFocused()).to.equal(false); const otherWindow = new BrowserWindow({ show: false, title: 'otherWindow' }); const otherWindowShown = emittedOnce(otherWindow, 'show'); const otherWindowFocused = emittedOnce(otherWindow, 'focus'); otherWindow.show(); await otherWindowShown; await otherWindowFocused; expect(otherWindow.isFocused()).to.equal(true); w.moveTop(); const wPos = w.getPosition(); const wMoving = emittedOnce(w, 'move'); w.setPosition(wPos[0] + posDelta, wPos[1] + posDelta); await wMoving; expect(w.isFocused()).to.equal(false); expect(otherWindow.isFocused()).to.equal(true); const wFocused = emittedOnce(w, 'focus'); const otherWindowBlurred = emittedOnce(otherWindow, 'blur'); w.focus(); await wFocused; await otherWindowBlurred; expect(w.isFocused()).to.equal(true); otherWindow.moveTop(); const otherWindowPos = otherWindow.getPosition(); const otherWindowMoving = emittedOnce(otherWindow, 'move'); otherWindow.setPosition(otherWindowPos[0] + posDelta, otherWindowPos[1] + posDelta); await otherWindowMoving; expect(otherWindow.isFocused()).to.equal(false); expect(w.isFocused()).to.equal(true); await closeWindow(otherWindow, { assertNotWindows: false }); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1); }); }); ifdescribe(features.isDesktopCapturerEnabled())('BrowserWindow.moveAbove(mediaSourceId)', () => { it('should throw an exception if wrong formatting', async () => { const fakeSourceIds = [ 'none', 'screen:0', 'window:fake', 'window:1234', 'foobar:1:2' ]; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Invalid media source id/); }); }); it('should throw an exception if wrong type', async () => { const fakeSourceIds = [null as any, 123 as any]; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Error processing argument at index 0 */); }); }); it('should throw an exception if invalid window', async () => { // It is very unlikely that these window id exist. const fakeSourceIds = ['window:99999999:0', 'window:123456:1', 'window:123456:9']; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Invalid media source id/); }); }); it('should not throw an exception', async () => { const w2 = new BrowserWindow({ show: false, title: 'window2' }); const w2Shown = emittedOnce(w2, 'show'); w2.show(); await w2Shown; expect(() => { w.moveAbove(w2.getMediaSourceId()); }).to.not.throw(); await closeWindow(w2, { assertNotWindows: false }); }); }); describe('BrowserWindow.setFocusable()', () => { it('can set unfocusable window to focusable', async () => { const w2 = new BrowserWindow({ focusable: false }); const w2Focused = emittedOnce(w2, 'focus'); w2.setFocusable(true); w2.focus(); await w2Focused; await closeWindow(w2, { assertNotWindows: false }); }); }); describe('BrowserWindow.isFocusable()', () => { it('correctly returns whether a window is focusable', async () => { const w2 = new BrowserWindow({ focusable: false }); expect(w2.isFocusable()).to.be.false(); w2.setFocusable(true); expect(w2.isFocusable()).to.be.true(); await closeWindow(w2, { assertNotWindows: false }); }); }); }); describe('sizing', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, width: 400, height: 400 }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.setBounds(bounds[, animate])', () => { it('sets the window bounds with full bounds', () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds); expectBoundsEqual(w.getBounds(), fullBounds); }); it('sets the window bounds with partial bounds', () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds); const boundsUpdate = { width: 200 }; w.setBounds(boundsUpdate as any); const expectedBounds = Object.assign(fullBounds, boundsUpdate); expectBoundsEqual(w.getBounds(), expectedBounds); }); ifit(process.platform === 'darwin')('on macOS', () => { it('emits \'resized\' event after animating', async () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds, true); await expect(emittedOnce(w, 'resized')).to.eventually.be.fulfilled(); }); }); }); describe('BrowserWindow.setSize(width, height)', () => { it('sets the window size', async () => { const size = [300, 400]; const resized = emittedOnce(w, 'resize'); w.setSize(size[0], size[1]); await resized; expectBoundsEqual(w.getSize(), size); }); ifit(process.platform === 'darwin')('on macOS', () => { it('emits \'resized\' event after animating', async () => { const size = [300, 400]; w.setSize(size[0], size[1], true); await expect(emittedOnce(w, 'resized')).to.eventually.be.fulfilled(); }); }); }); describe('BrowserWindow.setMinimum/MaximumSize(width, height)', () => { it('sets the maximum and minimum size of the window', () => { expect(w.getMinimumSize()).to.deep.equal([0, 0]); expect(w.getMaximumSize()).to.deep.equal([0, 0]); w.setMinimumSize(100, 100); expectBoundsEqual(w.getMinimumSize(), [100, 100]); expectBoundsEqual(w.getMaximumSize(), [0, 0]); w.setMaximumSize(900, 600); expectBoundsEqual(w.getMinimumSize(), [100, 100]); expectBoundsEqual(w.getMaximumSize(), [900, 600]); }); }); describe('BrowserWindow.setAspectRatio(ratio)', () => { it('resets the behaviour when passing in 0', async () => { const size = [300, 400]; w.setAspectRatio(1 / 2); w.setAspectRatio(0); const resize = emittedOnce(w, 'resize'); w.setSize(size[0], size[1]); await resize; expectBoundsEqual(w.getSize(), size); }); it('doesn\'t change bounds when maximum size is set', () => { w.setMenu(null); w.setMaximumSize(400, 400); // Without https://github.com/electron/electron/pull/29101 // following call would shrink the window to 384x361. // There would be also DCHECK in resize_utils.cc on // debug build. w.setAspectRatio(1.0); expectBoundsEqual(w.getSize(), [400, 400]); }); }); describe('BrowserWindow.setPosition(x, y)', () => { it('sets the window position', async () => { const pos = [10, 10]; const move = emittedOnce(w, 'move'); w.setPosition(pos[0], pos[1]); await move; expect(w.getPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setContentSize(width, height)', () => { it('sets the content size', async () => { // NB. The CI server has a very small screen. Attempting to size the window // larger than the screen will limit the window's size to the screen and // cause the test to fail. const size = [456, 567]; w.setContentSize(size[0], size[1]); await new Promise(setImmediate); const after = w.getContentSize(); expect(after).to.deep.equal(size); }); it('works for a frameless window', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 400, height: 400 }); const size = [456, 567]; w.setContentSize(size[0], size[1]); await new Promise(setImmediate); const after = w.getContentSize(); expect(after).to.deep.equal(size); }); }); describe('BrowserWindow.setContentBounds(bounds)', () => { it('sets the content size and position', async () => { const bounds = { x: 10, y: 10, width: 250, height: 250 }; const resize = emittedOnce(w, 'resize'); w.setContentBounds(bounds); await resize; await delay(); expectBoundsEqual(w.getContentBounds(), bounds); }); it('works for a frameless window', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300 }); const bounds = { x: 10, y: 10, width: 250, height: 250 }; const resize = emittedOnce(w, 'resize'); w.setContentBounds(bounds); await resize; await delay(); expectBoundsEqual(w.getContentBounds(), bounds); }); }); describe('BrowserWindow.getBackgroundColor()', () => { it('returns default value if no backgroundColor is set', () => { w.destroy(); w = new BrowserWindow({}); expect(w.getBackgroundColor()).to.equal('#FFFFFF'); }); it('returns correct value if backgroundColor is set', () => { const backgroundColor = '#BBAAFF'; w.destroy(); w = new BrowserWindow({ backgroundColor: backgroundColor }); expect(w.getBackgroundColor()).to.equal(backgroundColor); }); it('returns correct value from setBackgroundColor()', () => { const backgroundColor = '#AABBFF'; w.destroy(); w = new BrowserWindow({}); w.setBackgroundColor(backgroundColor); expect(w.getBackgroundColor()).to.equal(backgroundColor); }); 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 = emittedOnce(w, 'resize'); w.setSize(size[0], size[1]); await resize; expectBoundsEqual(w.getNormalBounds(), w.getBounds()); }); it('checks normal bounds after move', async () => { const pos = [10, 10]; const move = emittedOnce(w, 'move'); w.setPosition(pos[0], pos[1]); await move; expectBoundsEqual(w.getNormalBounds(), w.getBounds()); }); }); ifdescribe(process.platform !== 'linux')('Maximized state', () => { it('checks normal bounds when maximized', async () => { const bounds = w.getBounds(); const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('checks normal bounds when unmaximized', async () => { const bounds = w.getBounds(); w.once('maximize', () => { w.unmaximize(); }); const unmaximize = emittedOnce(w, 'unmaximize'); w.show(); w.maximize(); await unmaximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('does not change size for a frameless window with min size', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300, minWidth: 300, minHeight: 300 }); const bounds = w.getBounds(); w.once('maximize', () => { w.unmaximize(); }); const unmaximize = emittedOnce(w, 'unmaximize'); w.show(); w.maximize(); await unmaximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('correctly checks transparent window maximization state', async () => { w.destroy(); w = new BrowserWindow({ show: false, width: 300, height: 300, transparent: true }); const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; expect(w.isMaximized()).to.equal(true); const unmaximize = emittedOnce(w, 'unmaximize'); w.unmaximize(); await unmaximize; expect(w.isMaximized()).to.equal(false); }); it('returns the correct value for windows with an aspect ratio', async () => { w.destroy(); w = new BrowserWindow({ show: false, fullscreenable: false }); w.setAspectRatio(16 / 11); const maximize = emittedOnce(w, 'resize'); w.show(); w.maximize(); await maximize; expect(w.isMaximized()).to.equal(true); w.resizable = false; expect(w.isMaximized()).to.equal(true); }); }); ifdescribe(process.platform !== 'linux')('Minimized state', () => { it('checks normal bounds when minimized', async () => { const bounds = w.getBounds(); const minimize = emittedOnce(w, 'minimize'); w.show(); w.minimize(); await minimize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('checks normal bounds when restored', async () => { const bounds = w.getBounds(); w.once('minimize', () => { w.restore(); }); const restore = emittedOnce(w, 'restore'); w.show(); w.minimize(); await restore; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('does not change size for a frameless window with min size', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300, minWidth: 300, minHeight: 300 }); const bounds = w.getBounds(); w.once('minimize', () => { w.restore(); }); const restore = emittedOnce(w, 'restore'); w.show(); w.minimize(); await restore; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); ifdescribe(process.platform === 'win32')('Fullscreen state', () => { it('with properties', () => { it('can be set with the fullscreen constructor option', () => { w = new BrowserWindow({ fullscreen: true }); expect(w.fullScreen).to.be.true(); }); it('can be changed', () => { w.fullScreen = false; expect(w.fullScreen).to.be.false(); w.fullScreen = true; expect(w.fullScreen).to.be.true(); }); it('checks normal bounds when fullscreen\'ed', async () => { const bounds = w.getBounds(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.show(); w.fullScreen = true; await enterFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('checks normal bounds when unfullscreen\'ed', async () => { const bounds = w.getBounds(); w.once('enter-full-screen', () => { w.fullScreen = false; }); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.show(); w.fullScreen = true; await leaveFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); it('with functions', () => { it('can be set with the fullscreen constructor option', () => { w = new BrowserWindow({ fullscreen: true }); expect(w.isFullScreen()).to.be.true(); }); it('can be changed', () => { w.setFullScreen(false); expect(w.isFullScreen()).to.be.false(); w.setFullScreen(true); expect(w.isFullScreen()).to.be.true(); }); it('checks normal bounds when fullscreen\'ed', async () => { const bounds = w.getBounds(); w.show(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('checks normal bounds when unfullscreen\'ed', async () => { const bounds = w.getBounds(); w.show(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); }); }); }); ifdescribe(process.platform === 'darwin')('tabbed windows', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.selectPreviousTab()', () => { it('does not throw', () => { expect(() => { w.selectPreviousTab(); }).to.not.throw(); }); }); describe('BrowserWindow.selectNextTab()', () => { it('does not throw', () => { expect(() => { w.selectNextTab(); }).to.not.throw(); }); }); describe('BrowserWindow.mergeAllWindows()', () => { it('does not throw', () => { expect(() => { w.mergeAllWindows(); }).to.not.throw(); }); }); describe('BrowserWindow.moveTabToNewWindow()', () => { it('does not throw', () => { expect(() => { w.moveTabToNewWindow(); }).to.not.throw(); }); }); describe('BrowserWindow.toggleTabBar()', () => { it('does not throw', () => { expect(() => { w.toggleTabBar(); }).to.not.throw(); }); }); describe('BrowserWindow.addTabbedWindow()', () => { it('does not throw', async () => { const tabbedWindow = new BrowserWindow({}); expect(() => { w.addTabbedWindow(tabbedWindow); }).to.not.throw(); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(2); // w + tabbedWindow await closeWindow(tabbedWindow, { assertNotWindows: false }); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1); // w }); it('throws when called on itself', () => { expect(() => { w.addTabbedWindow(w); }).to.throw('AddTabbedWindow cannot be called by a window on itself.'); }); }); }); describe('autoHideMenuBar state', () => { afterEach(closeAllWindows); it('for properties', () => { it('can be set with autoHideMenuBar constructor option', () => { const w = new BrowserWindow({ show: false, autoHideMenuBar: true }); expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); w.autoHideMenuBar = true; expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); w.autoHideMenuBar = false; expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); }); }); it('for functions', () => { it('can be set with autoHideMenuBar constructor option', () => { const w = new BrowserWindow({ show: false, autoHideMenuBar: true }); expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar'); w.setAutoHideMenuBar(true); expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar'); w.setAutoHideMenuBar(false); expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar'); }); }); }); describe('BrowserWindow.capturePage(rect)', () => { afterEach(closeAllWindows); it('returns a Promise with a Buffer', async () => { const w = new BrowserWindow({ show: false }); const image = await w.capturePage({ x: 0, y: 0, width: 100, height: 100 }); expect(image.isEmpty()).to.equal(true); }); it('resolves after the window is hidden', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixtures, 'pages', 'a.html')); await emittedOnce(w, 'ready-to-show'); w.show(); const visibleImage = await w.capturePage(); expect(visibleImage.isEmpty()).to.equal(false); w.hide(); const hiddenImage = await w.capturePage(); const isEmpty = process.platform !== 'darwin'; expect(hiddenImage.isEmpty()).to.equal(isEmpty); }); it('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 emittedOnce(w, 'ready-to-show'); w.webContents.incrementCapturerCount(); 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 emittedOnce(w, 'ready-to-show'); w.show(); const image = await w.capturePage(); const imgBuffer = image.toPNG(); // Check the 25th byte in the PNG. // Values can be 0,2,3,4, or 6. We want 6, which is RGB + Alpha expect(imgBuffer[25]).to.equal(6); }); it('should increase the capturer count', () => { const w = new BrowserWindow({ show: false }); w.webContents.incrementCapturerCount(); expect(w.webContents.isBeingCaptured()).to.be.true(); w.webContents.decrementCapturerCount(); expect(w.webContents.isBeingCaptured()).to.be.false(); }); }); describe('BrowserWindow.setProgressBar(progress)', () => { let w = null as unknown as BrowserWindow; before(() => { w = new BrowserWindow({ show: false }); }); after(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('sets the progress', () => { expect(() => { if (process.platform === 'darwin') { app.dock.setIcon(path.join(fixtures, 'assets', 'logo.png')); } w.setProgressBar(0.5); if (process.platform === 'darwin') { app.dock.setIcon(null as any); } w.setProgressBar(-1); }).to.not.throw(); }); it('sets the progress using "paused" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'paused' }); }).to.not.throw(); }); it('sets the progress using "error" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'error' }); }).to.not.throw(); }); it('sets the progress using "normal" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'normal' }); }).to.not.throw(); }); }); describe('BrowserWindow.setAlwaysOnTop(flag, level)', () => { let w = null as unknown as BrowserWindow; afterEach(closeAllWindows); beforeEach(() => { w = new BrowserWindow({ show: true }); }); it('sets the window as always on top', () => { expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); w.setAlwaysOnTop(false); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); }); ifit(process.platform === 'darwin')('resets the windows level on minimize', () => { expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); w.minimize(); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.restore(); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); }); it('causes the right value to be emitted on `always-on-top-changed`', async () => { const alwaysOnTopChanged = emittedOnce(w, 'always-on-top-changed'); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true); const [, alwaysOnTop] = await alwaysOnTopChanged; expect(alwaysOnTop).to.be.true('is not alwaysOnTop'); }); ifit(process.platform === 'darwin')('honors the alwaysOnTop level of a child window', () => { w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ parent: w }); c.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.false(); expect(c.isAlwaysOnTop()).to.be.true('child is not always on top'); expect((c as any)._getAlwaysOnTopLevel()).to.equal('screen-saver'); }); }); describe('preconnect feature', () => { let w = null as unknown as BrowserWindow; let server = null as unknown as http.Server; let url = null as unknown as string; let connections = 0; beforeEach(async () => { connections = 0; server = http.createServer((req, res) => { if (req.url === '/link') { res.setHeader('Content-type', 'text/html'); res.end('<head><link rel="preconnect" href="//example.com" /></head><body>foo</body>'); return; } res.end(); }); server.on('connection', () => { connections++; }); await new Promise<void>(resolve => server.listen(0, '127.0.0.1', () => resolve())); url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; }); afterEach(async () => { server.close(); await closeWindow(w); w = null as unknown as BrowserWindow; server = null as unknown as http.Server; }); it('calling preconnect() connects to the server', async () => { w = new BrowserWindow({ show: false }); w.webContents.on('did-start-navigation', (event, url) => { w.webContents.session.preconnect({ url, numSockets: 4 }); }); await w.loadURL(url); expect(connections).to.equal(4); }); it('does not preconnect unless requested', async () => { w = new BrowserWindow({ show: false }); await w.loadURL(url); expect(connections).to.equal(1); }); it('parses <link rel=preconnect>', async () => { w = new BrowserWindow({ show: true }); const p = emittedOnce(w.webContents.session, 'preconnect'); w.loadURL(url + '/link'); const [, preconnectUrl, allowCredentials] = await p; expect(preconnectUrl).to.equal('http://example.com/'); expect(allowCredentials).to.be.true('allowCredentials'); }); }); describe('BrowserWindow.setAutoHideCursor(autoHide)', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); ifit(process.platform === 'darwin')('on macOS', () => { it('allows changing cursor auto-hiding', () => { expect(() => { w.setAutoHideCursor(false); w.setAutoHideCursor(true); }).to.not.throw(); }); }); ifit(process.platform !== 'darwin')('on non-macOS platforms', () => { it('is not available', () => { expect(w.setAutoHideCursor).to.be.undefined('setAutoHideCursor function'); }); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setWindowButtonVisibility()', () => { afterEach(closeAllWindows); it('does not throw', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setWindowButtonVisibility(true); w.setWindowButtonVisibility(false); }).to.not.throw(); }); it('changes window button visibility for normal window', () => { const w = new BrowserWindow({ show: false }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); it('changes window button visibility for frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); }); it('changes window button visibility for hiddenInset window', () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hiddenInset' }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); // Buttons of customButtonsOnHover are always hidden unless hovered. it('does not change window button visibility for customButtonsOnHover window', () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'customButtonsOnHover' }); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setVibrancy(type)', () => { let appProcess: childProcess.ChildProcessWithoutNullStreams | undefined; afterEach(() => { if (appProcess && !appProcess.killed) { appProcess.kill(); appProcess = undefined; } closeAllWindows(); }); it('allows setting, changing, and removing the vibrancy', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setVibrancy('light'); w.setVibrancy('dark'); w.setVibrancy(null); w.setVibrancy('ultra-dark'); w.setVibrancy('' as any); }).to.not.throw(); }); it('does not crash if vibrancy is set to an invalid value', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setVibrancy('i-am-not-a-valid-vibrancy-type' as any); }).to.not.throw(); }); it('Allows setting a transparent window via CSS', async () => { const appPath = path.join(__dirname, 'fixtures', 'apps', 'background-color-transparent'); appProcess = childProcess.spawn(process.execPath, [appPath]); const [code] = await emittedOnce(appProcess, 'exit'); expect(code).to.equal(0); }); }); ifdescribe(process.platform === 'darwin')('trafficLightPosition', () => { const pos = { x: 10, y: 10 }; afterEach(closeAllWindows); describe('BrowserWindow.getTrafficLightPosition(pos)', () => { it('gets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); expect(w.getTrafficLightPosition()).to.deep.equal(pos); }); it('gets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); expect(w.getTrafficLightPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setTrafficLightPosition(pos)', () => { it('sets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setTrafficLightPosition(newPos); expect(w.getTrafficLightPosition()).to.deep.equal(newPos); }); it('sets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setTrafficLightPosition(newPos); expect(w.getTrafficLightPosition()).to.deep.equal(newPos); }); }); }); ifdescribe(process.platform === 'win32')('BrowserWindow.setAppDetails(options)', () => { afterEach(closeAllWindows); it('supports setting the app details', () => { const w = new BrowserWindow({ show: false }); const iconPath = path.join(fixtures, 'assets', 'icon.ico'); expect(() => { w.setAppDetails({ appId: 'my.app.id' }); w.setAppDetails({ appIconPath: iconPath, appIconIndex: 0 }); w.setAppDetails({ appIconPath: iconPath }); w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name' }); w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2' }); w.setAppDetails({ relaunchDisplayName: 'My app name' }); w.setAppDetails({ appId: 'my.app.id', appIconPath: iconPath, appIconIndex: 0, relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name' }); w.setAppDetails({}); }).to.not.throw(); expect(() => { (w.setAppDetails as any)(); }).to.throw('Insufficient number of arguments.'); }); }); describe('BrowserWindow.fromId(id)', () => { afterEach(closeAllWindows); it('returns the window with id', () => { const w = new BrowserWindow({ show: false }); expect(BrowserWindow.fromId(w.id)!.id).to.equal(w.id); }); }); describe('BrowserWindow.fromWebContents(webContents)', () => { afterEach(closeAllWindows); it('returns the window with the webContents', () => { const w = new BrowserWindow({ show: false }); const found = BrowserWindow.fromWebContents(w.webContents); expect(found!.id).to.equal(w.id); }); it('returns null for webContents without a BrowserWindow', () => { const contents = (webContents as any).create({}); try { expect(BrowserWindow.fromWebContents(contents)).to.be.null('BrowserWindow.fromWebContents(contents)'); } finally { contents.destroy(); } }); it('returns the correct window for a BrowserView webcontents', async () => { const w = new BrowserWindow({ show: false }); const bv = new BrowserView(); w.setBrowserView(bv); defer(() => { w.removeBrowserView(bv); (bv.webContents as any).destroy(); }); await bv.webContents.loadURL('about:blank'); expect(BrowserWindow.fromWebContents(bv.webContents)!.id).to.equal(w.id); }); it('returns the correct window for a WebView webcontents', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } }); w.loadURL('data:text/html,<webview src="data:text/html,hi"></webview>'); // NOTE(nornagon): Waiting for 'did-attach-webview' is a workaround for // https://github.com/electron/electron/issues/25413, and is not integral // to the test. const p = emittedOnce(w.webContents, 'did-attach-webview'); const [, webviewContents] = await emittedOnce(app, 'web-contents-created'); expect(BrowserWindow.fromWebContents(webviewContents)!.id).to.equal(w.id); await p; }); 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((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 as any).destroy(); }); expect(BrowserWindow.fromBrowserView(bv)!.id).to.equal(w.id); }); it('returns the window when there are multiple BrowserViews', () => { const w = new BrowserWindow({ show: false }); const bv1 = new BrowserView(); w.addBrowserView(bv1); const bv2 = new BrowserView(); w.addBrowserView(bv2); defer(() => { w.removeBrowserView(bv1); w.removeBrowserView(bv2); (bv1.webContents as any).destroy(); (bv2.webContents as any).destroy(); }); expect(BrowserWindow.fromBrowserView(bv1)!.id).to.equal(w.id); expect(BrowserWindow.fromBrowserView(bv2)!.id).to.equal(w.id); }); it('returns undefined if not attached', () => { const bv = new BrowserView(); defer(() => { (bv.webContents as any).destroy(); }); expect(BrowserWindow.fromBrowserView(bv)).to.be.null('BrowserWindow associated with bv'); }); }); describe('BrowserWindow.setOpacity(opacity)', () => { afterEach(closeAllWindows); ifdescribe(process.platform !== 'linux')(('Windows and Mac'), () => { it('make window with initial opacity', () => { const w = new BrowserWindow({ show: false, opacity: 0.5 }); expect(w.getOpacity()).to.equal(0.5); }); it('allows setting the opacity', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setOpacity(0.0); expect(w.getOpacity()).to.equal(0.0); w.setOpacity(0.5); expect(w.getOpacity()).to.equal(0.5); w.setOpacity(1.0); expect(w.getOpacity()).to.equal(1.0); }).to.not.throw(); }); it('clamps opacity to [0.0...1.0]', () => { const w = new BrowserWindow({ show: false, opacity: 0.5 }); w.setOpacity(100); expect(w.getOpacity()).to.equal(1.0); w.setOpacity(-100); expect(w.getOpacity()).to.equal(0.0); }); }); ifdescribe(process.platform === 'linux')(('Linux'), () => { it('sets 1 regardless of parameter', () => { const w = new BrowserWindow({ show: false }); w.setOpacity(0); expect(w.getOpacity()).to.equal(1.0); w.setOpacity(0.5); expect(w.getOpacity()).to.equal(1.0); }); }); }); describe('BrowserWindow.setShape(rects)', () => { afterEach(closeAllWindows); it('allows setting shape', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setShape([]); w.setShape([{ x: 0, y: 0, width: 100, height: 100 }]); w.setShape([{ x: 0, y: 0, width: 100, height: 100 }, { x: 0, y: 200, width: 1000, height: 100 }]); w.setShape([]); }).to.not.throw(); }); }); describe('"useContentSize" option', () => { afterEach(closeAllWindows); it('make window created with content size when used', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, useContentSize: true }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); it('make window created with window size when not used', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400 }); const size = w.getSize(); expect(size).to.deep.equal([400, 400]); }); it('works for a frameless window', () => { const w = new BrowserWindow({ show: false, frame: false, width: 400, height: 400, useContentSize: true }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); const size = w.getSize(); expect(size).to.deep.equal([400, 400]); }); }); ifdescribe(process.platform === 'win32' || (process.platform === 'darwin' && semver.gte(os.release(), '14.0.0')))('"titleBarStyle" option', () => { const testWindowsOverlay = async (style: any) => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: style, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: true }); const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); if (process.platform === 'darwin') { await w.loadFile(overlayHTML); } else { const overlayReady = emittedOnce(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const overlayRect = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(overlayRect.y).to.equal(0); if (process.platform === 'darwin') { expect(overlayRect.x).to.be.greaterThan(0); } else { expect(overlayRect.x).to.equal(0); } expect(overlayRect.width).to.be.greaterThan(0); expect(overlayRect.height).to.be.greaterThan(0); const cssOverlayRect = await w.webContents.executeJavaScript('getCssOverlayProperties();'); expect(cssOverlayRect).to.deep.equal(overlayRect); const geometryChange = emittedOnce(ipcMain, 'geometrychange'); w.setBounds({ width: 800 }); const [, newOverlayRect] = await geometryChange; expect(newOverlayRect.width).to.equal(overlayRect.width + 400); }; afterEach(closeAllWindows); afterEach(() => { ipcMain.removeAllListeners('geometrychange'); }); it('creates browser window with hidden title bar', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden' }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); ifit(process.platform === 'darwin')('creates browser window with hidden inset title bar', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hiddenInset' }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); it('sets Window Control Overlay with hidden title bar', async () => { await testWindowsOverlay('hidden'); }); ifit(process.platform === 'darwin')('sets Window Control Overlay with hidden inset title bar', async () => { await testWindowsOverlay('hiddenInset'); }); }); ifdescribe(process.platform === 'win32' || (process.platform === 'darwin' && semver.gte(os.release(), '14.0.0')))('"titleBarOverlay" option', () => { const testWindowsOverlayHeight = async (size: any) => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden', webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { height: size } }); const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); if (process.platform === 'darwin') { await w.loadFile(overlayHTML); } else { const overlayReady = emittedOnce(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const overlayRectPreMax = await w.webContents.executeJavaScript('getJSOverlayProperties()'); await w.maximize(); const max = await w.isMaximized(); expect(max).to.equal(true); const overlayRectPostMax = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(overlayRectPreMax.y).to.equal(0); if (process.platform === 'darwin') { expect(overlayRectPreMax.x).to.be.greaterThan(0); } else { expect(overlayRectPreMax.x).to.equal(0); } expect(overlayRectPreMax.width).to.be.greaterThan(0); expect(overlayRectPreMax.height).to.equal(size); // Confirm that maximization only affected the height of the buttons and not the title bar expect(overlayRectPostMax.height).to.equal(size); }; afterEach(closeAllWindows); afterEach(() => { ipcMain.removeAllListeners('geometrychange'); }); it('sets Window Control Overlay with title bar height of 40', async () => { await testWindowsOverlayHeight(40); }); }); ifdescribe(process.platform === 'darwin')('"enableLargerThanScreen" option', () => { afterEach(closeAllWindows); it('can move the window out of screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); w.setPosition(-10, 50); const after = w.getPosition(); expect(after).to.deep.equal([-10, 50]); }); it('cannot move the window behind menu bar', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[1]).to.be.at.least(0); }); it('can move the window behind menu bar if it has no frame', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true, frame: false }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[0]).to.be.equal(-10); expect(after[1]).to.be.equal(-10); }); it('without it, cannot move the window out of screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: false }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[1]).to.be.at.least(0); }); it('can set the window larger than screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); const size = screen.getPrimaryDisplay().size; size.width += 100; size.height += 100; w.setSize(size.width, size.height); expectBoundsEqual(w.getSize(), [size.width, size.height]); }); it('without it, cannot set the window larger than screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: false }); const size = screen.getPrimaryDisplay().size; size.width += 100; size.height += 100; w.setSize(size.width, size.height); expect(w.getSize()[1]).to.at.most(screen.getPrimaryDisplay().size.height); }); }); ifdescribe(process.platform === 'darwin')('"zoomToPageWidth" option', () => { afterEach(closeAllWindows); it('sets the window width to the page width when used', () => { const w = new BrowserWindow({ show: false, width: 500, height: 400, zoomToPageWidth: true }); w.maximize(); expect(w.getSize()[0]).to.equal(500); }); }); describe('"tabbingIdentifier" option', () => { afterEach(closeAllWindows); it('can be set on a window', () => { expect(() => { /* eslint-disable no-new */ new BrowserWindow({ tabbingIdentifier: 'group1' }); new BrowserWindow({ tabbingIdentifier: 'group2', frame: false }); /* eslint-enable no-new */ }).not.to.throw(); }); }); describe('"webPreferences" option', () => { afterEach(() => { ipcMain.removeAllListeners('answer'); }); afterEach(closeAllWindows); describe('"preload" option', () => { const doesNotLeakSpec = (name: string, webPrefs: { nodeIntegration: boolean, sandbox: boolean, contextIsolation: boolean }) => { it(name, async () => { const w = new BrowserWindow({ webPreferences: { ...webPrefs, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'no-leak.html')); const [, result] = await emittedOnce(ipcMain, 'leak-result'); expect(result).to.have.property('require', 'undefined'); expect(result).to.have.property('exports', 'undefined'); expect(result).to.have.property('windowExports', 'undefined'); expect(result).to.have.property('windowPreload', 'undefined'); expect(result).to.have.property('windowRequire', 'undefined'); }); }; doesNotLeakSpec('does not leak require', { nodeIntegration: false, sandbox: false, contextIsolation: false }); doesNotLeakSpec('does not leak require when sandbox is enabled', { nodeIntegration: false, sandbox: true, contextIsolation: false }); doesNotLeakSpec('does not leak require when context isolation is enabled', { nodeIntegration: false, sandbox: false, contextIsolation: true }); doesNotLeakSpec('does not leak require when context isolation and sandbox are enabled', { nodeIntegration: false, sandbox: true, contextIsolation: true }); it('does not leak any node globals on the window object with nodeIntegration is disabled', async () => { let w = new BrowserWindow({ webPreferences: { contextIsolation: false, nodeIntegration: false, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'globals.html')); const [, notIsolated] = await emittedOnce(ipcMain, 'leak-result'); expect(notIsolated).to.have.property('globals'); w.destroy(); w = new BrowserWindow({ webPreferences: { contextIsolation: true, nodeIntegration: false, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'globals.html')); const [, isolated] = await emittedOnce(ipcMain, 'leak-result'); expect(isolated).to.have.property('globals'); const notIsolatedGlobals = new Set(notIsolated.globals); for (const isolatedGlobal of isolated.globals) { notIsolatedGlobals.delete(isolatedGlobal); } expect([...notIsolatedGlobals]).to.deep.equal([], 'non-isoalted renderer should have no additional globals'); }); it('loads the script before other scripts in window', async () => { const preload = path.join(fixtures, 'module', 'set-global.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false, preload } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test).to.eql('preload'); }); it('has synchronous access to all eventual window APIs', async () => { const preload = path.join(fixtures, 'module', 'access-blink-apis.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false, preload } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test).to.be.an('object'); expect(test.atPreload).to.be.an('array'); expect(test.atLoad).to.be.an('array'); expect(test.atPreload).to.deep.equal(test.atLoad, 'should have access to the same window APIs'); }); }); describe('session preload scripts', function () { const preloads = [ path.join(fixtures, 'module', 'set-global-preload-1.js'), path.join(fixtures, 'module', 'set-global-preload-2.js'), path.relative(process.cwd(), path.join(fixtures, 'module', 'set-global-preload-3.js')) ]; const defaultSession = session.defaultSession; beforeEach(() => { expect(defaultSession.getPreloads()).to.deep.equal([]); defaultSession.setPreloads(preloads); }); afterEach(() => { defaultSession.setPreloads([]); }); it('can set multiple session preload script', () => { expect(defaultSession.getPreloads()).to.deep.equal(preloads); }); const generateSpecs = (description: string, sandbox: boolean) => { describe(description, () => { it('loads the script before other scripts in window including normal preloads', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox, preload: path.join(fixtures, 'module', 'get-global-preload.js'), contextIsolation: false } }); w.loadURL('about:blank'); const [, preload1, preload2, preload3] = await emittedOnce(ipcMain, 'vars'); expect(preload1).to.equal('preload-1'); expect(preload2).to.equal('preload-1-2'); expect(preload3).to.be.undefined('preload 3'); }); }); }; generateSpecs('without sandbox', false); generateSpecs('with sandbox', true); }); describe('"additionalArguments" option', () => { it('adds extra args to process.argv in the renderer process', async () => { const preload = path.join(fixtures, 'module', 'check-arguments.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, preload, additionalArguments: ['--my-magic-arg'] } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, argv] = await emittedOnce(ipcMain, 'answer'); expect(argv).to.include('--my-magic-arg'); }); it('adds extra value args to process.argv in the renderer process', async () => { const preload = path.join(fixtures, 'module', 'check-arguments.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, preload, additionalArguments: ['--my-magic-arg=foo'] } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, argv] = await emittedOnce(ipcMain, 'answer'); expect(argv).to.include('--my-magic-arg=foo'); }); }); describe('"node-integration" option', () => { it('disables node integration by default', async () => { const preload = path.join(fixtures, 'module', 'send-later.js'); const w = new BrowserWindow({ show: false, webPreferences: { preload, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, typeofProcess, typeofBuffer] = await emittedOnce(ipcMain, 'answer'); expect(typeofProcess).to.equal('undefined'); expect(typeofBuffer).to.equal('undefined'); }); }); describe('"sandbox" option', () => { const preload = path.join(path.resolve(__dirname, 'fixtures'), 'module', 'preload-sandbox.js'); let server: http.Server = null as unknown as http.Server; let serverUrl: string = null as unknown as string; before((done) => { server = http.createServer((request, response) => { switch (request.url) { case '/cross-site': response.end(`<html><body><h1>${request.url}</h1></body></html>`); break; default: throw new Error(`unsupported endpoint: ${request.url}`); } }).listen(0, '127.0.0.1', () => { serverUrl = 'http://127.0.0.1:' + (server.address() as AddressInfo).port; done(); }); }); after(() => { server.close(); }); it('exposes ipcRenderer to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test).to.equal('preload'); }); it('exposes ipcRenderer to preload script (path has special chars)', async () => { const preloadSpecialChars = path.join(fixtures, 'module', 'preload-sandboxæø åü.js'); const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload: preloadSpecialChars, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test).to.equal('preload'); }); it('exposes "loaded" event to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload } }); w.loadURL('about:blank'); await emittedOnce(ipcMain, 'process-loaded'); }); it('exposes "exit" event to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?exit-event'); const pageUrl = 'file://' + htmlPath; w.loadURL(pageUrl); const [, url] = await emittedOnce(ipcMain, 'answer'); const expectedUrl = process.platform === 'win32' ? 'file:///' + htmlPath.replace(/\\/g, '/') : pageUrl; expect(url).to.equal(expectedUrl); }); it('should open windows in same domain with cross-scripting enabled', async () => { const w = new BrowserWindow({ show: true, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload } } })); const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?window-open'); const pageUrl = 'file://' + htmlPath; const answer = emittedOnce(ipcMain, 'answer'); w.loadURL(pageUrl); const [, { url, frameName, options }] = await emittedOnce(w.webContents, 'did-create-window'); const expectedUrl = process.platform === 'win32' ? 'file:///' + htmlPath.replace(/\\/g, '/') : pageUrl; expect(url).to.equal(expectedUrl); expect(frameName).to.equal('popup!'); expect(options.width).to.equal(500); expect(options.height).to.equal(600); const [, html] = await answer; expect(html).to.equal('<h1>scripting from opener</h1>'); }); it('should open windows in another domain with cross-scripting disabled', async () => { const w = new BrowserWindow({ show: true, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload } } })); w.loadFile( path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'window-open-external' } ); // Wait for a message from the main window saying that it's ready. await emittedOnce(ipcMain, 'opener-loaded'); // Ask the opener to open a popup with window.opener. const expectedPopupUrl = `${serverUrl}/cross-site`; // Set in "sandbox.html". w.webContents.send('open-the-popup', expectedPopupUrl); // The page is going to open a popup that it won't be able to close. // We have to close it from here later. const [, popupWindow] = await emittedOnce(app, 'browser-window-created'); // Ask the popup window for details. const detailsAnswer = emittedOnce(ipcMain, 'child-loaded'); popupWindow.webContents.send('provide-details'); const [, openerIsNull, , locationHref] = await detailsAnswer; expect(openerIsNull).to.be.false('window.opener is null'); expect(locationHref).to.equal(expectedPopupUrl); // Ask the page to access the popup. const touchPopupResult = emittedOnce(ipcMain, 'answer'); w.webContents.send('touch-the-popup'); const [, popupAccessMessage] = await touchPopupResult; // Ask the popup to access the opener. const touchOpenerResult = emittedOnce(ipcMain, 'answer'); popupWindow.webContents.send('touch-the-opener'); const [, openerAccessMessage] = await touchOpenerResult; // We don't need the popup anymore, and its parent page can't close it, // so let's close it from here before we run any checks. await closeWindow(popupWindow, { assertNotWindows: false }); expect(popupAccessMessage).to.be.a('string', 'child\'s .document is accessible from its parent window'); expect(popupAccessMessage).to.match(/^Blocked a frame with origin/); expect(openerAccessMessage).to.be.a('string', 'opener .document is accessible from a popup window'); expect(openerAccessMessage).to.match(/^Blocked a frame with origin/); }); it('should inherit the sandbox setting in opened windows', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [, { argv }] = await emittedOnce(ipcMain, 'answer'); expect(argv).to.include('--enable-sandbox'); }); it('should open windows with the options configured via new-window event listeners', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath, contextIsolation: false } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [[, childWebContents]] = await Promise.all([ emittedOnce(app, 'web-contents-created'), emittedOnce(ipcMain, 'answer') ]); const webPreferences = childWebContents.getLastWebPreferences(); expect(webPreferences.contextIsolation).to.equal(false); }); it('should set ipc event sender correctly', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); let childWc: WebContents | null = null; w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload, contextIsolation: false } } })); w.webContents.on('did-create-window', (win) => { childWc = win.webContents; expect(w.webContents).to.not.equal(childWc); }); ipcMain.once('parent-ready', function (event) { expect(event.sender).to.equal(w.webContents, 'sender should be the parent'); event.sender.send('verified'); }); ipcMain.once('child-ready', function (event) { expect(childWc).to.not.be.null('child webcontents should be available'); expect(event.sender).to.equal(childWc, 'sender should be the child'); event.sender.send('verified'); }); const done = Promise.all([ 'parent-answer', 'child-answer' ].map(name => emittedOnce(ipcMain, name))); w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'verify-ipc-sender' }); await done; }); describe('event handling', () => { let w: BrowserWindow = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); }); it('works for window events', async () => { const pageTitleUpdated = emittedOnce(w, 'page-title-updated'); w.loadURL('data:text/html,<script>document.title = \'changed\'</script>'); await pageTitleUpdated; }); it('works for stop events', async () => { const done = Promise.all([ 'did-navigate', 'did-fail-load', 'did-stop-loading' ].map(name => emittedOnce(w.webContents, name))); w.loadURL('data:text/html,<script>stop()</script>'); await done; }); it('works for web contents events', async () => { const done = Promise.all([ 'did-finish-load', 'did-frame-finish-load', 'did-navigate-in-page', 'will-navigate', 'did-start-loading', 'did-stop-loading', 'did-frame-finish-load', 'dom-ready' ].map(name => emittedOnce(w.webContents, name))); w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'webcontents-events' }); await done; }); }); it('supports calling preventDefault on new-window events', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const initialWebContents = webContents.getAllWebContents().map((i) => i.id); w.webContents.once('new-window', (e) => { e.preventDefault(); // We need to give it some time so the windows get properly disposed (at least on OSX). setTimeout(() => { const currentWebContents = webContents.getAllWebContents().map((i) => i.id); try { expect(currentWebContents).to.deep.equal(initialWebContents); done(); } catch (error) { done(e); } }, 100); }); w.loadFile(path.join(fixtures, 'pages', 'window-open.html')); }); it('validates process APIs access in sandboxed renderer', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.once('preload-error', (event, preloadPath, error) => { throw error; }); process.env.sandboxmain = 'foo'; w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test.hasCrash).to.be.true('has crash'); expect(test.hasHang).to.be.true('has hang'); expect(test.heapStatistics).to.be.an('object'); expect(test.blinkMemoryInfo).to.be.an('object'); expect(test.processMemoryInfo).to.be.an('object'); expect(test.systemVersion).to.be.a('string'); expect(test.cpuUsage).to.be.an('object'); expect(test.ioCounters).to.be.an('object'); expect(test.uptime).to.be.a('number'); expect(test.arch).to.equal(process.arch); expect(test.platform).to.equal(process.platform); expect(test.env).to.deep.equal(process.env); expect(test.execPath).to.equal(process.helperExecPath); expect(test.sandboxed).to.be.true('sandboxed'); expect(test.contextIsolated).to.be.false('contextIsolated'); expect(test.type).to.equal('renderer'); expect(test.version).to.equal(process.version); expect(test.versions).to.deep.equal(process.versions); expect(test.contextId).to.be.a('string'); if (process.platform === 'linux' && test.osSandbox) { expect(test.creationTime).to.be.null('creation time'); expect(test.systemMemoryInfo).to.be.null('system memory info'); } else { expect(test.creationTime).to.be.a('number'); expect(test.systemMemoryInfo).to.be.an('object'); } }); it('webview in sandbox renderer', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, webviewTag: true, contextIsolation: false } }); const didAttachWebview = emittedOnce(w.webContents, 'did-attach-webview'); const webviewDomReady = emittedOnce(ipcMain, 'webview-dom-ready'); w.loadFile(path.join(fixtures, 'pages', 'webview-did-attach-event.html')); const [, webContents] = await didAttachWebview; const [, id] = await webviewDomReady; expect(webContents.id).to.equal(id); }); }); describe('child windows', () => { let w: BrowserWindow = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, // tests relies on preloads in opened windows nodeIntegrationInSubFrames: true, contextIsolation: false } }); }); it('opens window of about:blank with cross-scripting enabled', async () => { const answer = emittedOnce(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-blank.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('opens window of same domain with cross-scripting enabled', async () => { const answer = emittedOnce(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-file.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('blocks accessing cross-origin frames', async () => { const answer = emittedOnce(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-cross-origin.html')); const [, content] = await answer; expect(content).to.equal('Blocked a frame with origin "file://" from accessing a cross-origin frame.'); }); it('opens window from <iframe> tags', async () => { const answer = emittedOnce(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-iframe.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('opens window with cross-scripting enabled from isolated context', async () => { const w = new BrowserWindow({ show: false, webPreferences: { preload: path.join(fixtures, 'api', 'native-window-open-isolated-preload.js') } }); w.loadFile(path.join(fixtures, 'api', 'native-window-open-isolated.html')); const [, content] = await emittedOnce(ipcMain, 'answer'); expect(content).to.equal('Hello'); }); ifit(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('loads native addons correctly after reload', async () => { w.loadFile(path.join(__dirname, 'fixtures', 'api', 'native-window-open-native-addon.html')); { const [, content] = await emittedOnce(ipcMain, 'answer'); expect(content).to.equal('function'); } w.reload(); { const [, content] = await emittedOnce(ipcMain, 'answer'); expect(content).to.equal('function'); } }); it('<webview> works in a scriptable popup', async () => { const preload = path.join(fixtures, 'api', 'new-window-webview-preload.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegrationInSubFrames: true, webviewTag: true, contextIsolation: false, preload } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { show: false, webPreferences: { contextIsolation: false, webviewTag: true, nodeIntegrationInSubFrames: true } } })); w.webContents.once('new-window', (event, url, frameName, disposition, options) => { options.show = false; }); const webviewLoaded = emittedOnce(ipcMain, 'webview-loaded'); w.loadFile(path.join(fixtures, 'api', 'new-window-webview.html')); await webviewLoaded; }); it('should open windows with the options configured via new-window event listeners', async () => { const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath, contextIsolation: false } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [[, childWebContents]] = await Promise.all([ emittedOnce(app, 'web-contents-created'), emittedOnce(ipcMain, 'answer') ]); const webPreferences = childWebContents.getLastWebPreferences(); expect(webPreferences.contextIsolation).to.equal(false); }); describe('window.location', () => { const protocols = [ ['foo', path.join(fixtures, 'api', 'window-open-location-change.html')], ['bar', path.join(fixtures, 'api', 'window-open-location-final.html')] ]; beforeEach(() => { for (const [scheme, path] of protocols) { protocol.registerBufferProtocol(scheme, (request, callback) => { callback({ mimeType: 'text/html', data: fs.readFileSync(path) }); }); } }); afterEach(() => { for (const [scheme] of protocols) { protocol.unregisterProtocol(scheme); } }); it('retains the original web preferences when window.location is changed to a new origin', async () => { const w = new BrowserWindow({ show: false, webPreferences: { // test relies on preloads in opened window nodeIntegrationInSubFrames: true, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: path.join(mainFixtures, 'api', 'window-open-preload.js'), contextIsolation: false, nodeIntegrationInSubFrames: true } } })); w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html')); const [, { nodeIntegration, typeofProcess }] = await emittedOnce(ipcMain, 'answer'); expect(nodeIntegration).to.be.false(); expect(typeofProcess).to.eql('undefined'); }); it('window.opener is not null when window.location is changed to a new origin', async () => { const w = new BrowserWindow({ show: false, webPreferences: { // test relies on preloads in opened window nodeIntegrationInSubFrames: true } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: path.join(mainFixtures, 'api', 'window-open-preload.js') } } })); w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html')); const [, { windowOpenerIsNull }] = await emittedOnce(ipcMain, 'answer'); expect(windowOpenerIsNull).to.be.false('window.opener is null'); }); }); }); describe('"disableHtmlFullscreenWindowResize" option', () => { it('prevents window from resizing when set', async () => { const w = new BrowserWindow({ show: false, webPreferences: { disableHtmlFullscreenWindowResize: true } }); await w.loadURL('about:blank'); const size = w.getSize(); const enterHtmlFullScreen = emittedOnce(w.webContents, 'enter-html-full-screen'); w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true); await enterHtmlFullScreen; expect(w.getSize()).to.deep.equal(size); }); }); }); describe('beforeunload handler', function () { let w: BrowserWindow = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(closeAllWindows); it('returning undefined would not prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html')); const wait = emittedOnce(w, 'closed'); w.close(); await wait; }); it('returning false would prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); const [, proceed] = await emittedOnce(w.webContents, 'before-unload-fired'); expect(proceed).to.equal(false); }); it('returning empty string would prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-empty-string.html')); w.close(); const [, proceed] = await emittedOnce(w.webContents, 'before-unload-fired'); expect(proceed).to.equal(false); }); it('emits for each close attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const destroyListener = () => { expect.fail('Close was not prevented'); }; w.webContents.once('destroyed', destroyListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await emittedOnce(w.webContents, 'console-message'); w.close(); await emittedOnce(w.webContents, 'before-unload-fired'); w.close(); await emittedOnce(w.webContents, 'before-unload-fired'); w.webContents.removeListener('destroyed', destroyListener); const wait = emittedOnce(w, 'closed'); w.close(); await wait; }); it('emits for each reload attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const navigationListener = () => { expect.fail('Reload was not prevented'); }; w.webContents.once('did-start-navigation', navigationListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await emittedOnce(w.webContents, 'console-message'); w.reload(); // Chromium does not emit 'before-unload-fired' on WebContents for // navigations, so we have to use other ways to know if beforeunload // is fired. await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.reload(); await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.webContents.removeListener('did-start-navigation', navigationListener); w.reload(); await emittedOnce(w.webContents, 'did-finish-load'); }); it('emits for each navigation attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const navigationListener = () => { expect.fail('Reload was not prevented'); }; w.webContents.once('did-start-navigation', navigationListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await emittedOnce(w.webContents, 'console-message'); w.loadURL('about:blank'); // Chromium does not emit 'before-unload-fired' on WebContents for // navigations, so we have to use other ways to know if beforeunload // is fired. await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.loadURL('about:blank'); await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.webContents.removeListener('did-start-navigation', navigationListener); await w.loadURL('about:blank'); }); }); describe('document.visibilityState/hidden', () => { afterEach(closeAllWindows); it('visibilityState is initially visible despite window being hidden', async () => { const w = new BrowserWindow({ show: false, width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); let readyToShow = false; w.once('ready-to-show', () => { readyToShow = true; }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(readyToShow).to.be.false('ready to show'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform !== 'win32')('visibilityState changes when window is hidden', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.hide(); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform !== 'win32')('visibilityState changes when window is shown', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); if (process.platform === 'darwin') { // See https://github.com/electron/electron/issues/8664 await emittedOnce(w, 'show'); } w.hide(); w.show(); const [, visibilityState] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); }); ifit(process.platform !== 'win32')('visibilityState changes when window is shown inactive', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); if (process.platform === 'darwin') { // See https://github.com/electron/electron/issues/8664 await emittedOnce(w, 'show'); } w.hide(); w.showInactive(); const [, visibilityState] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform === 'darwin')('visibilityState changes when window is minimized', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.minimize(); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } }); // FIXME(MarshallOfSound): This test fails locally 100% of the time, on CI it started failing // when we introduced the compositor recycling patch. Should figure out how to fix this it.skip('visibilityState remains visible if backgroundThrottling is disabled', async () => { const w = new BrowserWindow({ show: false, width: 100, height: 100, webPreferences: { backgroundThrottling: false, nodeIntegration: true } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } ipcMain.once('pong', (event, visibilityState, hidden) => { throw new Error(`Unexpected visibility change event. visibilityState: ${visibilityState} hidden: ${hidden}`); }); try { const shown1 = emittedOnce(w, 'show'); w.show(); await shown1; const hidden = emittedOnce(w, 'hide'); w.hide(); await hidden; const shown2 = emittedOnce(w, 'show'); w.show(); await shown2; } finally { ipcMain.removeAllListeners('pong'); } }); }); describe('new-window event', () => { afterEach(closeAllWindows); it('emits when window.open is called', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); w.webContents.once('new-window', (e, url, frameName, disposition, options) => { e.preventDefault(); try { expect(url).to.equal('http://host/'); expect(frameName).to.equal('host'); expect((options as any)['this-is-not-a-standard-feature']).to.equal(true); done(); } catch (e) { done(e); } }); w.loadFile(path.join(fixtures, 'pages', 'window-open.html')); }); it('emits when window.open is called with no webPreferences', (done) => { const w = new BrowserWindow({ show: false }); w.webContents.once('new-window', function (e, url, frameName, disposition, options) { e.preventDefault(); try { expect(url).to.equal('http://host/'); expect(frameName).to.equal('host'); expect((options as any)['this-is-not-a-standard-feature']).to.equal(true); done(); } catch (e) { done(e); } }); w.loadFile(path.join(fixtures, 'pages', 'window-open.html')); }); it('emits when link with target is called', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); w.webContents.once('new-window', (e, url, frameName) => { e.preventDefault(); try { expect(url).to.equal('http://host/'); expect(frameName).to.equal('target'); done(); } catch (e) { done(e); } }); w.loadFile(path.join(fixtures, 'pages', 'target-name.html')); }); it('includes all properties', async () => { const w = new BrowserWindow({ show: false }); const p = new Promise<{ url: string, frameName: string, disposition: string, options: BrowserWindowConstructorOptions, additionalFeatures: string[], referrer: Electron.Referrer, postBody: Electron.PostBody }>((resolve) => { w.webContents.once('new-window', (e, url, frameName, disposition, options, additionalFeatures, referrer, postBody) => { e.preventDefault(); resolve({ url, frameName, disposition, options, additionalFeatures, referrer, postBody }); }); }); w.loadURL(`data:text/html,${encodeURIComponent(` <form target="_blank" method="POST" id="form" action="http://example.com/test"> <input type="text" name="post-test-key" value="post-test-value"></input> </form> <script>form.submit()</script> `)}`); const { url, frameName, disposition, options, additionalFeatures, referrer, postBody } = await p; expect(url).to.equal('http://example.com/test'); expect(frameName).to.equal(''); expect(disposition).to.equal('foreground-tab'); expect(options).to.be.an('object').not.null(); expect(referrer.policy).to.equal('strict-origin-when-cross-origin'); expect(referrer.url).to.equal(''); expect(additionalFeatures).to.deep.equal([]); expect(postBody.data).to.have.length(1); expect(postBody.data[0].type).to.equal('rawData'); expect((postBody.data[0] as any).bytes).to.deep.equal(Buffer.from('post-test-key=post-test-value')); expect(postBody.contentType).to.equal('application/x-www-form-urlencoded'); }); }); ifdescribe(process.platform !== 'linux')('max/minimize events', () => { afterEach(closeAllWindows); it('emits an event when window is maximized', async () => { const w = new BrowserWindow({ show: false }); const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; }); it('emits an event when a transparent window is maximized', async () => { const w = new BrowserWindow({ show: false, frame: false, transparent: true }); const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; }); it('emits only one event when frameless window is maximized', () => { const w = new BrowserWindow({ show: false, frame: false }); let emitted = 0; w.on('maximize', () => emitted++); w.show(); w.maximize(); expect(emitted).to.equal(1); }); it('emits an event when window is unmaximized', async () => { const w = new BrowserWindow({ show: false }); const unmaximize = emittedOnce(w, 'unmaximize'); w.show(); w.maximize(); w.unmaximize(); await unmaximize; }); it('emits an event when a transparent window is unmaximized', async () => { const w = new BrowserWindow({ show: false, frame: false, transparent: true }); const maximize = emittedOnce(w, 'maximize'); const unmaximize = emittedOnce(w, 'unmaximize'); w.show(); w.maximize(); await maximize; w.unmaximize(); await unmaximize; }); it('emits an event when window is minimized', async () => { const w = new BrowserWindow({ show: false }); const minimize = emittedOnce(w, 'minimize'); w.show(); w.minimize(); await minimize; }); }); describe('beginFrameSubscription method', () => { it('does not crash when callback returns nothing', (done) => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); w.webContents.on('dom-ready', () => { w.webContents.beginFrameSubscription(function () { // Pending endFrameSubscription to next tick can reliably reproduce // a crash which happens when nothing is returned in the callback. setTimeout(() => { w.webContents.endFrameSubscription(); done(); }); }); }); }); it('subscribes to frame updates', (done) => { const w = new BrowserWindow({ show: false }); let called = false; w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); w.webContents.on('dom-ready', () => { w.webContents.beginFrameSubscription(function (data) { // This callback might be called twice. if (called) return; called = true; try { expect(data.constructor.name).to.equal('NativeImage'); expect(data.isEmpty()).to.be.false('data is empty'); done(); } catch (e) { done(e); } finally { w.webContents.endFrameSubscription(); } }); }); }); it('subscribes to frame updates (only dirty rectangle)', (done) => { const w = new BrowserWindow({ show: false }); let called = false; let gotInitialFullSizeFrame = false; const [contentWidth, contentHeight] = w.getContentSize(); w.webContents.on('did-finish-load', () => { w.webContents.beginFrameSubscription(true, (image, rect) => { if (image.isEmpty()) { // Chromium sometimes sends a 0x0 frame at the beginning of the // page load. return; } if (rect.height === contentHeight && rect.width === contentWidth && !gotInitialFullSizeFrame) { // The initial frame is full-size, but we're looking for a call // with just the dirty-rect. The next frame should be a smaller // rect. gotInitialFullSizeFrame = true; return; } // This callback might be called twice. if (called) return; // We asked for just the dirty rectangle, so we expect to receive a // rect smaller than the full size. // TODO(jeremy): this is failing on windows currently; investigate. // assert(rect.width < contentWidth || rect.height < contentHeight) called = true; try { const expectedSize = rect.width * rect.height * 4; expect(image.getBitmap()).to.be.an.instanceOf(Buffer).with.lengthOf(expectedSize); done(); } catch (e) { done(e); } finally { w.webContents.endFrameSubscription(); } }); }); w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); }); it('throws error when subscriber is not well defined', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.webContents.beginFrameSubscription(true, true as any); // TODO(zcbenz): gin is weak at guessing parameter types, we should // upstream native_mate's implementation to gin. }).to.throw('Error processing argument at index 1, conversion failure from '); }); }); describe('savePage method', () => { const savePageDir = path.join(fixtures, 'save_page'); const savePageHtmlPath = path.join(savePageDir, 'save_page.html'); const savePageJsPath = path.join(savePageDir, 'save_page_files', 'test.js'); const savePageCssPath = path.join(savePageDir, 'save_page_files', 'test.css'); afterEach(() => { closeAllWindows(); try { fs.unlinkSync(savePageCssPath); fs.unlinkSync(savePageJsPath); fs.unlinkSync(savePageHtmlPath); fs.rmdirSync(path.join(savePageDir, 'save_page_files')); fs.rmdirSync(savePageDir); } catch {} }); it('should throw when passing relative paths', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await expect( w.webContents.savePage('save_page.html', 'HTMLComplete') ).to.eventually.be.rejectedWith('Path must be absolute'); await expect( w.webContents.savePage('save_page.html', 'HTMLOnly') ).to.eventually.be.rejectedWith('Path must be absolute'); await expect( w.webContents.savePage('save_page.html', 'MHTML') ).to.eventually.be.rejectedWith('Path must be absolute'); }); it('should save page to disk with HTMLOnly', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'HTMLOnly'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.false('js path'); expect(fs.existsSync(savePageCssPath)).to.be.false('css path'); }); it('should save page to disk with MHTML', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'MHTML'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.false('js path'); expect(fs.existsSync(savePageCssPath)).to.be.false('css path'); }); it('should save page to disk with HTMLComplete', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'HTMLComplete'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.true('js path'); expect(fs.existsSync(savePageCssPath)).to.be.true('css path'); }); }); describe('BrowserWindow options argument is optional', () => { afterEach(closeAllWindows); it('should create a window with default size (800x600)', () => { const w = new BrowserWindow(); expect(w.getSize()).to.deep.equal([800, 600]); }); }); describe('BrowserWindow.restore()', () => { afterEach(closeAllWindows); it('should restore the previous window size', () => { const w = new BrowserWindow({ minWidth: 800, width: 800 }); const initialSize = w.getSize(); w.minimize(); w.restore(); expectBoundsEqual(w.getSize(), initialSize); }); it('does not crash when restoring hidden minimized window', () => { const w = new BrowserWindow({}); w.minimize(); w.hide(); w.show(); }); }); // 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 = emittedOnce(w, 'hide'); let shown = emittedOnce(w, 'show'); const maximize = emittedOnce(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 = emittedOnce(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 = emittedOnce(w, 'minimize'); w.minimize(); await minimize; w.unmaximize(); await delay(1000); expect(w.isMinimized()).to.be.true(); }); it('should not change the size or position of a normal window', async () => { const w = new BrowserWindow(); const initialSize = w.getSize(); const initialPosition = w.getPosition(); w.unmaximize(); await delay(1000); expectBoundsEqual(w.getSize(), initialSize); expectBoundsEqual(w.getPosition(), initialPosition); }); 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 delay(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 = emittedOnce(w, 'show'); // start fullscreen and hidden w.setFullScreen(true); w.show(); await shown; const leftFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leftFullScreen; expect(w.isVisible()).to.be.true('visible'); expect(w.isFullScreen()).to.be.false('fullscreen'); }); it('should keep window hidden if already in hidden state', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const leftFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leftFullScreen; expect(w.isVisible()).to.be.false('visible'); expect(w.isFullScreen()).to.be.false('fullscreen'); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setFullScreen(false) when HTML fullscreen', () => { it('exits HTML fullscreen when window leaves fullscreen', async () => { const w = new BrowserWindow(); await w.loadURL('about:blank'); await w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true); await emittedOnce(w, 'enter-full-screen'); // Wait a tick for the full-screen state to 'stick' await delay(); w.setFullScreen(false); await emittedOnce(w, 'leave-html-full-screen'); }); }); }); describe('parent window', () => { afterEach(closeAllWindows); ifit(process.platform === 'darwin')('sheet-begin event emits when window opens a sheet', async () => { const w = new BrowserWindow(); const sheetBegin = emittedOnce(w, 'sheet-begin'); // eslint-disable-next-line no-new new BrowserWindow({ modal: true, parent: w }); await sheetBegin; }); ifit(process.platform === 'darwin')('sheet-end event emits when window has closed a sheet', async () => { const w = new BrowserWindow(); const sheet = new BrowserWindow({ modal: true, parent: w }); const sheetEnd = emittedOnce(w, 'sheet-end'); sheet.close(); await sheetEnd; }); describe('parent option', () => { it('sets parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(c.getParentWindow()).to.equal(w); }); it('adds window to child windows of parent', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(w.getChildWindows()).to.deep.equal([c]); }); it('removes from child windows of parent when window is closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); const closed = emittedOnce(c, 'closed'); c.close(); await closed; // The child window list is not immediately cleared, so wait a tick until it's ready. await delay(); expect(w.getChildWindows().length).to.equal(0); }); it('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 delay(); 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 = emittedOnce(c, 'closed'); c.setParentWindow(w); c.close(); await closed; // The child window list is not immediately cleared, so wait a tick until it's ready. await delay(); expect(w.getChildWindows().length).to.equal(0); }); }); describe('modal option', () => { it('does not freeze or crash', async () => { const parentWindow = new BrowserWindow(); const createTwo = async () => { const two = new BrowserWindow({ width: 300, height: 200, parent: parentWindow, modal: true, show: false }); const twoShown = emittedOnce(two, 'show'); two.show(); await twoShown; setTimeout(() => two.close(), 500); await emittedOnce(two, 'closed'); }; const one = new BrowserWindow({ width: 600, height: 400, parent: parentWindow, modal: true, show: false }); const oneShown = emittedOnce(one, 'show'); one.show(); await oneShown; setTimeout(() => one.destroy(), 500); await emittedOnce(one, 'closed'); await createTwo(); }); ifit(process.platform !== 'darwin')('disables parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); expect(w.isEnabled()).to.be.true('w.isEnabled'); c.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); }); ifit(process.platform !== 'darwin')('re-enables an enabled parent window when closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const closed = emittedOnce(c, 'closed'); c.show(); c.close(); await closed; expect(w.isEnabled()).to.be.true('w.isEnabled'); }); ifit(process.platform !== 'darwin')('does not re-enable a disabled parent window when closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const closed = emittedOnce(c, 'closed'); w.setEnabled(false); c.show(); c.close(); await closed; expect(w.isEnabled()).to.be.false('w.isEnabled'); }); ifit(process.platform !== 'darwin')('disables parent window recursively', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const c2 = new BrowserWindow({ show: false, parent: w, modal: true }); c.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c2.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c.destroy(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c2.destroy(); expect(w.isEnabled()).to.be.true('w.isEnabled'); }); }); }); describe('window states', () => { afterEach(closeAllWindows); it('does not resize frameless windows when states change', () => { const w = new BrowserWindow({ frame: false, width: 300, height: 200, show: false }); w.minimizable = false; w.minimizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.resizable = false; w.resizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.maximizable = false; w.maximizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.fullScreenable = false; w.fullScreenable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.closable = false; w.closable = true; expect(w.getSize()).to.deep.equal([300, 200]); }); describe('resizable state', () => { it('with properties', () => { it('can be set with resizable constructor option', () => { const w = new BrowserWindow({ show: false, resizable: false }); expect(w.resizable).to.be.false('resizable'); if (process.platform === 'darwin') { expect(w.maximizable).to.to.true('maximizable'); } }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.resizable).to.be.true('resizable'); w.resizable = false; expect(w.resizable).to.be.false('resizable'); w.resizable = true; expect(w.resizable).to.be.true('resizable'); }); }); it('with functions', () => { it('can be set with resizable constructor option', () => { const w = new BrowserWindow({ show: false, resizable: false }); expect(w.isResizable()).to.be.false('resizable'); if (process.platform === 'darwin') { expect(w.isMaximizable()).to.to.true('maximizable'); } }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isResizable()).to.be.true('resizable'); w.setResizable(false); expect(w.isResizable()).to.be.false('resizable'); w.setResizable(true); expect(w.isResizable()).to.be.true('resizable'); }); }); it('works for a frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); expect(w.resizable).to.be.true('resizable'); if (process.platform === 'win32') { const w = new BrowserWindow({ show: false, thickFrame: false }); expect(w.resizable).to.be.false('resizable'); } }); // On Linux there is no "resizable" property of a window. ifit(process.platform !== 'linux')('does affect maximizability when disabled and enabled', () => { const w = new BrowserWindow({ show: false }); expect(w.resizable).to.be.true('resizable'); expect(w.maximizable).to.be.true('maximizable'); w.resizable = false; expect(w.maximizable).to.be.false('not maximizable'); w.resizable = true; expect(w.maximizable).to.be.true('maximizable'); }); ifit(process.platform === 'win32')('works for a window smaller than 64x64', () => { const w = new BrowserWindow({ show: false, frame: false, resizable: false, transparent: true }); w.setContentSize(60, 60); expectBoundsEqual(w.getContentSize(), [60, 60]); w.setContentSize(30, 30); expectBoundsEqual(w.getContentSize(), [30, 30]); w.setContentSize(10, 10); expectBoundsEqual(w.getContentSize(), [10, 10]); }); }); describe('loading main frame state', () => { let server: http.Server = null as unknown as http.Server; let serverUrl: string = null as unknown as string; before((done) => { server = http.createServer((request, response) => { response.end(); }).listen(0, '127.0.0.1', () => { serverUrl = 'http://127.0.0.1:' + (server.address() as AddressInfo).port; done(); }); }); after(() => { server.close(); }); it('is true when the main frame is loading', async () => { const w = new BrowserWindow({ show: false }); const didStartLoading = emittedOnce(w.webContents, 'did-start-loading'); w.webContents.loadURL(serverUrl); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame'); }); it('is false when only a subframe is loading', async () => { const w = new BrowserWindow({ show: false }); const didStopLoading = emittedOnce(w.webContents, 'did-stop-loading'); w.webContents.loadURL(serverUrl); await didStopLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); const didStartLoading = emittedOnce(w.webContents, 'did-start-loading'); w.webContents.executeJavaScript(` var iframe = document.createElement('iframe') iframe.src = '${serverUrl}/page2' document.body.appendChild(iframe) `); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); }); it('is true when navigating to pages from the same origin', async () => { const w = new BrowserWindow({ show: false }); const didStopLoading = emittedOnce(w.webContents, 'did-stop-loading'); w.webContents.loadURL(serverUrl); await didStopLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); const didStartLoading = emittedOnce(w.webContents, 'did-start-loading'); w.webContents.loadURL(`${serverUrl}/page2`); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame'); }); }); }); ifdescribe(process.platform !== 'linux')('window states (excluding Linux)', () => { // Not implemented on Linux. afterEach(closeAllWindows); describe('movable state', () => { it('with properties', () => { it('can be set with movable constructor option', () => { const w = new BrowserWindow({ show: false, movable: false }); expect(w.movable).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.movable).to.be.true('movable'); w.movable = false; expect(w.movable).to.be.false('movable'); w.movable = true; expect(w.movable).to.be.true('movable'); }); }); it('with functions', () => { it('can be set with movable constructor option', () => { const w = new BrowserWindow({ show: false, movable: false }); expect(w.isMovable()).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMovable()).to.be.true('movable'); w.setMovable(false); expect(w.isMovable()).to.be.false('movable'); w.setMovable(true); expect(w.isMovable()).to.be.true('movable'); }); }); }); describe('visibleOnAllWorkspaces state', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.visibleOnAllWorkspaces).to.be.false(); w.visibleOnAllWorkspaces = true; expect(w.visibleOnAllWorkspaces).to.be.true(); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isVisibleOnAllWorkspaces()).to.be.false(); w.setVisibleOnAllWorkspaces(true); expect(w.isVisibleOnAllWorkspaces()).to.be.true(); }); }); }); ifdescribe(process.platform === 'darwin')('documentEdited state', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.documentEdited).to.be.false(); w.documentEdited = true; expect(w.documentEdited).to.be.true(); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isDocumentEdited()).to.be.false(); w.setDocumentEdited(true); expect(w.isDocumentEdited()).to.be.true(); }); }); }); ifdescribe(process.platform === 'darwin')('representedFilename', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.representedFilename).to.eql(''); w.representedFilename = 'a name'; expect(w.representedFilename).to.eql('a name'); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.getRepresentedFilename()).to.eql(''); w.setRepresentedFilename('a name'); expect(w.getRepresentedFilename()).to.eql('a name'); }); }); }); describe('native window title', () => { it('with properties', () => { it('can be set with title constructor option', () => { const w = new BrowserWindow({ show: false, title: 'mYtItLe' }); expect(w.title).to.eql('mYtItLe'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.title).to.eql('Electron Test Main'); w.title = 'NEW TITLE'; expect(w.title).to.eql('NEW TITLE'); }); }); it('with functions', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, title: 'mYtItLe' }); expect(w.getTitle()).to.eql('mYtItLe'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.getTitle()).to.eql('Electron Test Main'); w.setTitle('NEW TITLE'); expect(w.getTitle()).to.eql('NEW TITLE'); }); }); }); describe('minimizable state', () => { it('with properties', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, minimizable: false }); expect(w.minimizable).to.be.false('minimizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.minimizable).to.be.true('minimizable'); w.minimizable = false; expect(w.minimizable).to.be.false('minimizable'); w.minimizable = true; expect(w.minimizable).to.be.true('minimizable'); }); }); it('with functions', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, minimizable: false }); expect(w.isMinimizable()).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMinimizable()).to.be.true('isMinimizable'); w.setMinimizable(false); expect(w.isMinimizable()).to.be.false('isMinimizable'); w.setMinimizable(true); expect(w.isMinimizable()).to.be.true('isMinimizable'); }); }); }); describe('maximizable state (property)', () => { it('with properties', () => { it('can be set with maximizable constructor option', () => { const w = new BrowserWindow({ show: false, maximizable: false }); expect(w.maximizable).to.be.false('maximizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.maximizable).to.be.true('maximizable'); w.maximizable = false; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; expect(w.maximizable).to.be.true('maximizable'); }); it('is not affected when changing other states', () => { const w = new BrowserWindow({ show: false }); w.maximizable = false; expect(w.maximizable).to.be.false('maximizable'); w.minimizable = false; expect(w.maximizable).to.be.false('maximizable'); w.closable = false; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; expect(w.maximizable).to.be.true('maximizable'); w.closable = true; expect(w.maximizable).to.be.true('maximizable'); w.fullScreenable = false; expect(w.maximizable).to.be.true('maximizable'); }); }); it('with functions', () => { it('can be set with maximizable constructor option', () => { const w = new BrowserWindow({ show: false, maximizable: false }); expect(w.isMaximizable()).to.be.false('isMaximizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setMaximizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); it('is not affected when changing other states', () => { const w = new BrowserWindow({ show: false }); w.setMaximizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMinimizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setClosable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setClosable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setFullScreenable(false); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); }); }); ifdescribe(process.platform === 'win32')('maximizable state', () => { it('with properties', () => { it('is reset to its former state', () => { const w = new BrowserWindow({ show: false }); w.maximizable = false; w.resizable = false; w.resizable = true; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; w.resizable = false; w.resizable = true; expect(w.maximizable).to.be.true('maximizable'); }); }); it('with functions', () => { it('is reset to its former state', () => { const w = new BrowserWindow({ show: false }); w.setMaximizable(false); w.setResizable(false); w.setResizable(true); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); w.setResizable(false); w.setResizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); }); }); ifdescribe(process.platform !== 'darwin')('menuBarVisible state', () => { describe('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.menuBarVisible).to.be.true(); w.menuBarVisible = false; expect(w.menuBarVisible).to.be.false(); w.menuBarVisible = true; expect(w.menuBarVisible).to.be.true(); }); }); describe('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); w.setMenuBarVisibility(false); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); w.setMenuBarVisibility(true); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); }); }); }); ifdescribe(process.platform === 'darwin')('fullscreenable state', () => { it('with functions', () => { it('can be set with fullscreenable constructor option', () => { const w = new BrowserWindow({ show: false, fullscreenable: false }); expect(w.isFullScreenable()).to.be.false('isFullScreenable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isFullScreenable()).to.be.true('isFullScreenable'); w.setFullScreenable(false); expect(w.isFullScreenable()).to.be.false('isFullScreenable'); w.setFullScreenable(true); expect(w.isFullScreenable()).to.be.true('isFullScreenable'); }); }); }); // fullscreen events are dispatched eagerly and twiddling things too fast can confuse poor Electron ifdescribe(process.platform === 'darwin')('kiosk state', () => { it('with properties', () => { it('can be set with a constructor property', () => { const w = new BrowserWindow({ kiosk: true }); expect(w.kiosk).to.be.true(); }); it('can be changed ', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.kiosk = true; expect(w.isKiosk()).to.be.true('isKiosk'); await enterFullScreen; await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.kiosk = false; expect(w.isKiosk()).to.be.false('isKiosk'); await leaveFullScreen; }); }); it('with functions', () => { it('can be set with a constructor property', () => { const w = new BrowserWindow({ kiosk: true }); expect(w.isKiosk()).to.be.true(); }); it('can be changed ', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setKiosk(true); expect(w.isKiosk()).to.be.true('isKiosk'); await enterFullScreen; await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setKiosk(false); expect(w.isKiosk()).to.be.false('isKiosk'); await leaveFullScreen; }); }); }); ifdescribe(process.platform === 'darwin')('fullscreen state with resizable set', () => { it('resizable flag should be set to true and restored', async () => { const w = new BrowserWindow({ resizable: false }); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.resizable).to.be.true('resizable'); await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.resizable).to.be.false('resizable'); }); }); ifdescribe(process.platform === 'darwin')('fullscreen state', () => { it('should not cause a crash if called when exiting fullscreen', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; }); it('can be changed with setFullScreen method', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('isFullScreen'); }); it('handles several transitions starting with fullscreen', async () => { const w = new BrowserWindow({ fullscreen: true, show: true }); expect(w.isFullScreen()).to.be.true('not fullscreen'); w.setFullScreen(false); w.setFullScreen(true); const enterFullScreen = emittedNTimes(w, 'enter-full-screen', 2); await enterFullScreen; expect(w.isFullScreen()).to.be.true('not fullscreen'); await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); }); it('handles several transitions in close proximity', async () => { const w = new BrowserWindow(); expect(w.isFullScreen()).to.be.false('is fullscreen'); w.setFullScreen(true); w.setFullScreen(false); w.setFullScreen(true); const enterFullScreen = emittedNTimes(w, 'enter-full-screen', 2); await enterFullScreen; expect(w.isFullScreen()).to.be.true('not fullscreen'); }); it('does not crash when exiting simpleFullScreen (properties)', async () => { const w = new BrowserWindow(); w.setSimpleFullScreen(true); await delay(1000); w.setFullScreen(!w.isFullScreen()); }); it('does not crash when exiting simpleFullScreen (functions)', async () => { const w = new BrowserWindow(); w.simpleFullScreen = true; await delay(1000); w.setFullScreen(!w.isFullScreen()); }); it('should not be changed by setKiosk method', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await delay(); w.setKiosk(true); await delay(); w.setKiosk(false); expect(w.isFullScreen()).to.be.true('isFullScreen'); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('isFullScreen'); }); // FIXME: https://github.com/electron/electron/issues/30140 xit('multiple windows inherit correct fullscreen state', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await delay(); const w2 = new BrowserWindow({ show: false }); const enterFullScreen2 = emittedOnce(w2, 'enter-full-screen'); w2.show(); await enterFullScreen2; expect(w2.isFullScreen()).to.be.true('isFullScreen'); }); }); describe('closable state', () => { it('with properties', () => { it('can be set with closable constructor option', () => { const w = new BrowserWindow({ show: false, closable: false }); expect(w.closable).to.be.false('closable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.closable).to.be.true('closable'); w.closable = false; expect(w.closable).to.be.false('closable'); w.closable = true; expect(w.closable).to.be.true('closable'); }); }); it('with functions', () => { it('can be set with closable constructor option', () => { const w = new BrowserWindow({ show: false, closable: false }); expect(w.isClosable()).to.be.false('isClosable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isClosable()).to.be.true('isClosable'); w.setClosable(false); expect(w.isClosable()).to.be.false('isClosable'); w.setClosable(true); expect(w.isClosable()).to.be.true('isClosable'); }); }); }); describe('hasShadow state', () => { it('with properties', () => { it('returns a boolean on all platforms', () => { const w = new BrowserWindow({ show: false }); expect(w.shadow).to.be.a('boolean'); }); // On Windows there's no shadow by default & it can't be changed dynamically. it('can be changed with hasShadow option', () => { const hasShadow = process.platform !== 'darwin'; const w = new BrowserWindow({ show: false, hasShadow }); expect(w.shadow).to.equal(hasShadow); }); it('can be changed with setHasShadow method', () => { const w = new BrowserWindow({ show: false }); w.shadow = false; expect(w.shadow).to.be.false('hasShadow'); w.shadow = true; expect(w.shadow).to.be.true('hasShadow'); w.shadow = false; expect(w.shadow).to.be.false('hasShadow'); }); }); describe('with functions', () => { it('returns a boolean on all platforms', () => { const w = new BrowserWindow({ show: false }); const hasShadow = w.hasShadow(); expect(hasShadow).to.be.a('boolean'); }); // On Windows there's no shadow by default & it can't be changed dynamically. it('can be changed with hasShadow option', () => { const hasShadow = process.platform !== 'darwin'; const w = new BrowserWindow({ show: false, hasShadow }); expect(w.hasShadow()).to.equal(hasShadow); }); it('can be changed with setHasShadow method', () => { const w = new BrowserWindow({ show: false }); w.setHasShadow(false); expect(w.hasShadow()).to.be.false('hasShadow'); w.setHasShadow(true); expect(w.hasShadow()).to.be.true('hasShadow'); w.setHasShadow(false); expect(w.hasShadow()).to.be.false('hasShadow'); }); }); }); }); describe('window.getMediaSourceId()', () => { afterEach(closeAllWindows); it('returns valid source id', async () => { const w = new BrowserWindow({ show: false }); const shown = emittedOnce(w, 'show'); w.show(); await shown; // Check format 'window:1234:0'. const sourceId = w.getMediaSourceId(); expect(sourceId).to.match(/^window:\d+:\d+$/); }); }); ifdescribe(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('window.getNativeWindowHandle()', () => { afterEach(closeAllWindows); it('returns valid handle', () => { const w = new BrowserWindow({ show: false }); // The module's source code is hosted at // https://github.com/electron/node-is-valid-window const isValidWindow = require('is-valid-window'); expect(isValidWindow(w.getNativeWindowHandle())).to.be.true('is valid window'); }); }); ifdescribe(process.platform === 'darwin')('previewFile', () => { afterEach(closeAllWindows); it('opens the path in Quick Look on macOS', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.previewFile(__filename); w.closeFilePreview(); }).to.not.throw(); }); }); describe('contextIsolation option with and without sandbox option', () => { const expectedContextData = { preloadContext: { preloadProperty: 'number', pageProperty: 'undefined', typeofRequire: 'function', typeofProcess: 'object', typeofArrayPush: 'function', typeofFunctionApply: 'function', typeofPreloadExecuteJavaScriptProperty: 'undefined' }, pageContext: { preloadProperty: 'undefined', pageProperty: 'string', typeofRequire: 'undefined', typeofProcess: 'undefined', typeofArrayPush: 'number', typeofFunctionApply: 'boolean', typeofPreloadExecuteJavaScriptProperty: 'number', typeofOpenedWindow: 'object' } }; afterEach(closeAllWindows); it('separates the page context from the Electron/preload context', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = emittedOnce(ipcMain, 'isolated-world'); iw.loadFile(path.join(fixtures, 'api', 'isolated.html')); const [, data] = await p; expect(data).to.deep.equal(expectedContextData); }); it('recreates the contexts on reload', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); await iw.loadFile(path.join(fixtures, 'api', 'isolated.html')); const isolatedWorld = emittedOnce(ipcMain, 'isolated-world'); iw.webContents.reload(); const [, data] = await isolatedWorld; expect(data).to.deep.equal(expectedContextData); }); it('enables context isolation on child windows', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const browserWindowCreated = emittedOnce(app, 'browser-window-created'); iw.loadFile(path.join(fixtures, 'pages', 'window-open.html')); const [, window] = await browserWindowCreated; expect(window.webContents.getLastWebPreferences().contextIsolation).to.be.true('contextIsolation'); }); it('separates the page context from the Electron/preload context with sandbox on', async () => { const ws = new BrowserWindow({ show: false, webPreferences: { sandbox: true, contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = emittedOnce(ipcMain, 'isolated-world'); ws.loadFile(path.join(fixtures, 'api', 'isolated.html')); const [, data] = await p; expect(data).to.deep.equal(expectedContextData); }); it('recreates the contexts on reload with sandbox on', async () => { const ws = new BrowserWindow({ show: false, webPreferences: { sandbox: true, contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); await ws.loadFile(path.join(fixtures, 'api', 'isolated.html')); const isolatedWorld = emittedOnce(ipcMain, 'isolated-world'); ws.webContents.reload(); const [, data] = await isolatedWorld; expect(data).to.deep.equal(expectedContextData); }); it('supports fetch api', async () => { const fetchWindow = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-fetch-preload.js') } }); const p = emittedOnce(ipcMain, 'isolated-fetch-error'); fetchWindow.loadURL('about:blank'); const [, error] = await p; expect(error).to.equal('Failed to fetch'); }); it('doesn\'t break ipc serialization', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = emittedOnce(ipcMain, 'isolated-world'); iw.loadURL('about:blank'); iw.webContents.executeJavaScript(` const opened = window.open() openedLocation = opened.location.href opened.close() window.postMessage({openedLocation}, '*') `); const [, data] = await p; expect(data.pageContext.openedLocation).to.equal('about:blank'); }); it('reports process.contextIsolated', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-process.js') } }); const p = emittedOnce(ipcMain, 'context-isolation'); iw.loadURL('about:blank'); const [, contextIsolation] = await p; expect(contextIsolation).to.be.true('contextIsolation'); }); }); it('reloading does not cause Node.js module API hangs after reload', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); let count = 0; ipcMain.on('async-node-api-done', () => { if (count === 3) { ipcMain.removeAllListeners('async-node-api-done'); done(); } else { count++; w.reload(); } }); w.loadFile(path.join(fixtures, 'pages', 'send-after-node.html')); }); describe('window.webContents.focus()', () => { afterEach(closeAllWindows); it('focuses window', async () => { const w1 = new BrowserWindow({ x: 100, y: 300, width: 300, height: 200 }); w1.loadURL('about:blank'); const w2 = new BrowserWindow({ x: 300, y: 300, width: 300, height: 200 }); w2.loadURL('about:blank'); const w1Focused = emittedOnce(w1, 'focus'); w1.webContents.focus(); await w1Focused; expect(w1.webContents.isFocused()).to.be.true('focuses window'); }); }); ifdescribe(features.isOffscreenRenderingEnabled())('offscreen rendering', () => { let w: BrowserWindow; beforeEach(function () { w = new BrowserWindow({ width: 100, height: 100, show: false, webPreferences: { backgroundThrottling: false, offscreen: true } }); }); afterEach(closeAllWindows); it('creates offscreen window with correct size', async () => { const paint = emittedOnce(w.webContents, 'paint'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); const [,, data] = await paint; expect(data.constructor.name).to.equal('NativeImage'); expect(data.isEmpty()).to.be.false('data is empty'); const size = data.getSize(); const { scaleFactor } = screen.getPrimaryDisplay(); expect(size.width).to.be.closeTo(100 * scaleFactor, 2); expect(size.height).to.be.closeTo(100 * scaleFactor, 2); }); it('does not crash after navigation', () => { w.webContents.loadURL('about:blank'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); }); describe('window.webContents.isOffscreen()', () => { it('is true for offscreen type', () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); expect(w.webContents.isOffscreen()).to.be.true('isOffscreen'); }); it('is false for regular window', () => { const c = new BrowserWindow({ show: false }); expect(c.webContents.isOffscreen()).to.be.false('isOffscreen'); c.destroy(); }); }); describe('window.webContents.isPainting()', () => { it('returns whether is currently painting', async () => { const paint = emittedOnce(w.webContents, 'paint'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await paint; expect(w.webContents.isPainting()).to.be.true('isPainting'); }); }); describe('window.webContents.stopPainting()', () => { it('stops painting', async () => { const domReady = emittedOnce(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.stopPainting(); expect(w.webContents.isPainting()).to.be.false('isPainting'); }); }); describe('window.webContents.startPainting()', () => { it('starts painting', async () => { const domReady = emittedOnce(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.stopPainting(); w.webContents.startPainting(); await emittedOnce(w.webContents, 'paint'); expect(w.webContents.isPainting()).to.be.true('isPainting'); }); }); describe('frameRate APIs', () => { it('has default frame rate (function)', async () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await emittedOnce(w.webContents, 'paint'); expect(w.webContents.getFrameRate()).to.equal(60); }); it('has default frame rate (property)', async () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await emittedOnce(w.webContents, 'paint'); expect(w.webContents.frameRate).to.equal(60); }); it('sets custom frame rate (function)', async () => { const domReady = emittedOnce(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.setFrameRate(30); await emittedOnce(w.webContents, 'paint'); expect(w.webContents.getFrameRate()).to.equal(30); }); it('sets custom frame rate (property)', async () => { const domReady = emittedOnce(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.frameRate = 30; await emittedOnce(w.webContents, 'paint'); expect(w.webContents.frameRate).to.equal(30); }); }); }); describe('"transparent" option', () => { afterEach(closeAllWindows); // Only applicable on Windows where transparent windows can't be maximized. ifit(process.platform === 'win32')('can show maximized frameless window', async () => { const display = screen.getPrimaryDisplay(); const w = new BrowserWindow({ ...display.bounds, frame: false, transparent: true, show: true }); w.loadURL('about:blank'); await emittedOnce(w, 'ready-to-show'); expect(w.isMaximized()).to.be.true(); // Fails when the transparent HWND is in an invalid maximized state. expect(w.getBounds()).to.deep.equal(display.workArea); const newBounds = { width: 256, height: 256, x: 0, y: 0 }; w.setBounds(newBounds); expect(w.getBounds()).to.deep.equal(newBounds); }); // Linux and arm64 platforms (WOA and macOS) do not return any capture sources ifit(process.platform !== 'linux' && process.arch !== 'arm64')('should not display a visible background', async () => { const display = screen.getPrimaryDisplay(); const backgroundWindow = new BrowserWindow({ ...display.bounds, frame: false, backgroundColor: CHROMA_COLOR_HEX, hasShadow: false }); await backgroundWindow.loadURL('about:blank'); const foregroundWindow = new BrowserWindow({ ...display.bounds, show: true, transparent: true, frame: false, hasShadow: false }); foregroundWindow.loadFile(path.join(__dirname, 'fixtures', 'pages', 'half-background-color.html')); await emittedOnce(foregroundWindow, 'ready-to-show'); const screenCapture = await captureScreen(); const leftHalfColor = getPixelColor(screenCapture, { x: display.size.width / 4, y: display.size.height / 2 }); const rightHalfColor = getPixelColor(screenCapture, { x: display.size.width - (display.size.width / 4), y: display.size.height / 2 }); expect(areColorsSimilar(leftHalfColor, CHROMA_COLOR_HEX)).to.be.true(); expect(areColorsSimilar(rightHalfColor, '#ff0000')).to.be.true(); }); }); describe('"backgroundColor" option', () => { afterEach(closeAllWindows); // Linux/WOA doesn't return any capture sources. ifit(process.platform !== 'linux' && (process.platform !== 'win32' || process.arch !== 'arm64'))('should display the set color', async () => { const display = screen.getPrimaryDisplay(); const w = new BrowserWindow({ ...display.bounds, show: true, backgroundColor: CHROMA_COLOR_HEX }); w.loadURL('about:blank'); await emittedOnce(w, 'ready-to-show'); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); expect(areColorsSimilar(centerColor, CHROMA_COLOR_HEX)).to.be.true(); }); }); });
closed
electron/electron
https://github.com/electron/electron
33,732
[Bug]: `BrowserWindow`: `isFocused()` returns `true` even after calling `blur()` 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 18.0.3 ### What operating system are you using? macOS ### Operating System Version macOS Monterey 12.2.1 ### What arch are you using? x64 ### Last Known Working Electron version Unknown, reproduces back to v14. ### Expected Behavior `isFocused()` should return `false` after `blur()` has been called on it. ### Actual Behavior It returns `true` instead, hence the assertion error: ```sh $ npm test > [email protected] test > electron test.js AssertionError [ERR_ASSERTION]: Expected values to be strictly equal: true !== false at /Users/raisinten/Desktop/temp/project/electron/test.js:10:3 { generatedMessage: true, code: 'ERR_ASSERTION', actual: true, expected: false, operator: 'strictEqual' } $ echo $? 1 ``` ### Testcase Gist URL https://gist.github.com/RaisinTen/245976064623786f2276dd89d2df0185 ### Additional Information _No response_
https://github.com/electron/electron/issues/33732
https://github.com/electron/electron/pull/33734
7dee5179cb0f4a79056204a243aa3317fbe711a6
f887000d505cb6dbc4d195c03f38cef943f135fd
2022-04-12T12:42:24Z
c++
2022-05-03T07:39:18Z
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 <string> #include <utility> #include <vector> #include "base/cxx17_backports.h" #include "base/mac/mac_util.h" #include "base/mac/scoped_cftyperef.h" #include "base/strings/sys_string_conversions.h" #include "base/task/post_task.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/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/inspectable_web_contents.h" #include "shell/browser/ui/inspectable_web_contents_view.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/webrtc/modules/desktop_capture/mac/window_list_utils.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" // This view would inform Chromium to resize the hosted views::View. // // The overridden methods should behave the same with BridgedContentView. @interface ElectronAdaptedContentView : NSView { @private views::NativeWidgetMacNSWindowHost* bridge_host_; } @end @implementation ElectronAdaptedContentView - (id)initWithShell:(electron::NativeWindowMac*)shell { if ((self = [self init])) { bridge_host_ = views::NativeWidgetMacNSWindowHost::GetFromNativeWindow( shell->GetNativeWindow()); } return self; } - (void)viewDidMoveToWindow { // When this view is added to a window, AppKit calls setFrameSize before it is // added to the window, so the behavior in setFrameSize is not triggered. NSWindow* window = [self window]; if (window) [self setFrameSize:NSZeroSize]; } - (void)setFrameSize:(NSSize)newSize { // The size passed in here does not always use // -[NSWindow contentRectForFrameRect]. The following ensures that the // contentView for a frameless window can extend over the titlebar of the new // window containing it, since AppKit requires a titlebar to give frameless // windows correct shadows and rounded corners. NSWindow* window = [self window]; if (window && [window contentView] == self) { newSize = [window contentRectForFrameRect:[window frame]].size; // Ensure that the window geometry be updated on the host side before the // view size is updated. bridge_host_->GetInProcessNSWindowBridge()->UpdateWindowGeometry(); } [super setFrameSize:newSize]; // The OnViewSizeChanged is marked private in derived class. static_cast<remote_cocoa::mojom::NativeWidgetNSWindowHost*>(bridge_host_) ->OnViewSizeChanged(gfx::Size(newSize.width, newSize.height)); } @end // This view always takes the size of its superview. It is intended to be used // as a NSWindow's contentView. It is needed because NSWindow's implementation // explicitly resizes the contentView at inopportune times. @interface FullSizeContentView : NSView @end @implementation FullSizeContentView // 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:(NSSize)size { if ([self superview]) size = [[self superview] bounds].size; [super setFrameSize:size]; } // The contentView gets moved around during certain full-screen operations. // This is less than ideal, and should eventually be removed. - (void)viewDidMoveToSuperview { [self setFrame:[[self superview] bounds]]; } @end @interface ElectronProgressBar : NSProgressIndicator @end @implementation ElectronProgressBar - (void)drawRect:(NSRect)dirtyRect { if (self.style != NSProgressIndicatorBarStyle) 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]]; } } // 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 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; // Removing NSWindowStyleMaskTitled removes window title, which removes // rounded corners of window. bool rounded_corner = true; options.Get(options::kRoundedCorners, &rounded_corner); if (!rounded_corner && !has_frame()) styleMask = 0; if (minimizable) styleMask |= NSMiniaturizableWindowMask; if (closable) styleMask |= NSWindowStyleMaskClosable; if (resizable) styleMask |= NSResizableWindowMask; if (!useStandardWindow || transparent() || !has_frame()) styleMask |= NSTexturedBackgroundWindowMask; // 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, 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_.reset(); }, this)); [window_ setEnableLargerThanScreen:enable_larger_than_screen()]; window_delegate_.reset([[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)]; } 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_.reset([[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()) { if (@available(macOS 10.12, *)) { [window_ setTabbingMode:NSWindowTabbingModeDisallowed]; } } else { if (@available(macOS 10.12, *)) { [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]; // Use an NSEvent monitor to listen for the wheel event. BOOL __block began = NO; wheel_event_monitor_ = [NSEvent addLocalMonitorForEventsMatchingMask:NSEventMaskScrollWheel handler:^(NSEvent* event) { if ([[event window] windowNumber] != [window_ windowNumber]) return event; if (!began && (([event phase] == NSEventPhaseMayBegin) || ([event phase] == NSEventPhaseBegan))) { this->NotifyWindowScrollTouchBegin(); began = YES; } else if (began && (([event phase] == NSEventPhaseEnded) || ([event phase] == NSEventPhaseCancelled))) { this->NotifyWindowScrollTouchEnd(); began = NO; } return event; }]; // 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(); original_frame_ = [window_ frame]; 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 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]. SetEnabled(true); [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() { // Retain the child window before closing it. If the last reference to the // NSWindow goes away inside -[NSWindow close], then bad stuff can happen. // See e.g. http://crbug.com/616701. base::scoped_nsobject<NSWindow> child_window(window_, base::scoped_policy::RETAIN); [window_ close]; } void NativeWindowMac::Focus(bool focus) { if (!IsVisible()) return; if (focus) { [[NSApplication sharedApplication] activateIgnoringOtherApps:NO]; [window_ makeKeyAndOrderFront:nil]; } else { [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]. SetEnabled(true); if (is_modal() && parent()) { [window_ orderOut:nil]; [parent()->GetNativeWindow().GetNativeNSWindow() endSheet:window_]; return; } // Hide all children of the current window before hiding the window. // components/remote_cocoa/app_shim/native_widget_ns_window_bridge.mm // expects this when window visibility changes. if ([window_ childWindows]) { for (NSWindow* child in [window_ childWindows]) { [child orderOut:nil]; } } // Detach the window from the parent before. if (parent()) InternalSetParentWindow(parent(), false); [window_ orderOut:nil]; } bool NativeWindowMac::IsVisible() { bool occluded = [window_ occlusionState] == NSWindowOcclusionStateVisible; // For a window to be visible, it must be visible to the user in the // foreground of the app, which means that it should not be minimized or // occluded return [window_ isVisible] && !occluded && !IsMinimized(); } void NativeWindowMac::SetFullScreenTransitionState( FullScreenTransitionState state) { fullscreen_transition_state_ = state; } bool NativeWindowMac::IsEnabled() { return [window_ attachedSheet] == nil; } void NativeWindowMac::SetEnabled(bool enable) { if (!enable) { [window_ beginSheet:window_ completionHandler:^(NSModalResponse returnCode) { NSLog(@"modal enabled"); 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()) original_frame_ = [window_ frame]; [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() { if (([window_ styleMask] & 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()) original_frame_ = [window_ frame]; [window_ miniaturize:nil]; } void NativeWindowMac::Restore() { [window_ deminiaturize:nil]; } bool NativeWindowMac::IsMinimized() { return [window_ isMiniaturized]; } void NativeWindowMac::HandlePendingFullscreenTransitions() { if (pending_transitions_.empty()) return; bool next_transition = pending_transitions_.front(); pending_transitions_.pop(); SetFullScreen(next_transition); } 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::NONE) { 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()) return; // Take note of the current window size if (IsNormal()) original_frame_ = [window_ frame]; // 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::ENTERING : FullScreenTransitionState::EXITING; [window_ toggleFullScreenMode:nil]; } bool NativeWindowMac::IsFullscreen() const { return [window_ styleMask] & 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; } 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; [window_ orderWindow:NSWindowAbove relativeTo:id.id]; return true; } void NativeWindowMac::MoveTop() { [window_ orderWindow:NSWindowAbove relativeTo:0]; } void NativeWindowMac::SetResizable(bool resizable) { SetStyleMask(resizable, NSWindowStyleMaskResizable); SetCanResize(resizable); } bool NativeWindowMac::IsResizable() { return [window_ styleMask] & NSWindowStyleMaskResizable; } void NativeWindowMac::SetMovable(bool movable) { [window_ setMovable:movable]; } bool NativeWindowMac::IsMovable() { return [window_ isMovable]; } void NativeWindowMac::SetMinimizable(bool minimizable) { SetStyleMask(minimizable, NSMiniaturizableWindowMask); } bool NativeWindowMac::IsMinimizable() { return [window_ styleMask] & NSMiniaturizableWindowMask; } 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 [window_ styleMask] & 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; } else if (level_name == "dock") { // Deprecated by macOS, but kept for backwards compatibility level = NSDockWindowLevel; } 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"; } else if (level == NSDockWindowLevel) { level_name = "dock"; } 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_ flushWindow]; [[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; base::PostTask(FROM_HERE, {content::BrowserThread::UI}, 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()) { original_frame_ = [window_ frame]; 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; SetFullScreen(true); } else if (!kiosk && is_kiosk_) { [NSApp setPresentationOptions:kiosk_options_]; is_kiosk_ = false; SetFullScreen(false); } } 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::SetOpacity(const double opacity) { const double boundedOpacity = base::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)]; } 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]; } 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/+/master:chrome/browser/media/webrtc/native_desktop_media_list.cc;l=372?q=kWindowCaptureMacV2&ss=chromium // 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] autorelease]; [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] autorelease]; [progress_indicator setStyle:NSProgressIndicatorBarStyle]; [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 functionally // mimic 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) { ProcessSerialNumber psn = {0, kCurrentProcess}; if (visibleOnFullScreen) { [window_ setCanHide:NO]; TransformProcessType(&psn, kProcessTransformToUIElementApplication); } else { [window_ setCanHide:YES]; TransformProcessType(&psn, kProcessTransformToForegroundApplication); } } 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 = !([window_ styleMask] & 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::SetVibrancy(const std::string& type) { NSVisualEffectView* vibrantView = [window_ vibrantView]; if (type.empty()) { if (vibrantView == nil) return; [vibrantView removeFromSuperview]; [window_ setVibrantView:nil]; return; } std::string dep_warn = " has been deprecated and removed as of macOS 10.15."; node::Environment* env = node::Environment::GetCurrent(JavascriptEnvironment::GetIsolate()); NSVisualEffectMaterial vibrancyType{}; if (type == "appearance-based") { EmitWarning(env, "NSVisualEffectMaterialAppearanceBased" + dep_warn, "electron"); vibrancyType = NSVisualEffectMaterialAppearanceBased; } else if (type == "light") { EmitWarning(env, "NSVisualEffectMaterialLight" + dep_warn, "electron"); vibrancyType = NSVisualEffectMaterialLight; } else if (type == "dark") { EmitWarning(env, "NSVisualEffectMaterialDark" + dep_warn, "electron"); vibrancyType = NSVisualEffectMaterialDark; } else if (type == "titlebar") { vibrancyType = NSVisualEffectMaterialTitlebar; } 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 == "medium-light") { EmitWarning(env, "NSVisualEffectMaterialMediumLight" + dep_warn, "electron"); vibrancyType = NSVisualEffectMaterialMediumLight; } else if (type == "ultra-dark") { EmitWarning(env, "NSVisualEffectMaterialUltraDark" + dep_warn, "electron"); vibrancyType = NSVisualEffectMaterialUltraDark; } if (@available(macOS 10.14, *)) { 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]] autorelease]; [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; // The visibility of window buttons are managed by |buttons_proxy_| if the // style is customButtonsOnHover. if (title_bar_style_ == TitleBarStyle::kCustomButtonsOnHover) [buttons_proxy_ setVisible:visible]; else InternalSetWindowButtonVisibility(visible); NotifyLayoutWindowControlsOverlay(); } bool NativeWindowMac::GetWindowButtonVisibility() const { return ![window_ standardWindowButton:NSWindowZoomButton].hidden || ![window_ standardWindowButton:NSWindowMiniaturizeButton].hidden || ![window_ standardWindowButton:NSWindowCloseButton].hidden; } void NativeWindowMac::SetTrafficLightPosition( 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::GetTrafficLightPosition() 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) { if (@available(macOS 10.12.2, *)) { touch_bar_.reset([[ElectronTouchBar alloc] initWithDelegate:window_delegate_.get() window:this settings:std::move(items)]); [window_ setTouchBar:nil]; } } void NativeWindowMac::RefreshTouchBarItem(const std::string& item_id) { if (@available(macOS 10.12.2, *)) { if (touch_bar_ && [window_ touchBar]) [touch_bar_ refreshTouchBarItem:[window_ touchBar] id:item_id]; } } void NativeWindowMac::SetEscapeTouchBarItem( gin_helper::PersistentDictionary item) { if (@available(macOS 10.12.2, *)) { if (touch_bar_ && [window_ touchBar]) [touch_bar_ setEscapeTouchBarItem:std::move(item) forTouchBar:[window_ touchBar]]; } } void NativeWindowMac::SelectPreviousTab() { if (@available(macOS 10.12, *)) { [window_ selectPreviousTab:nil]; } } void NativeWindowMac::SelectNextTab() { if (@available(macOS 10.12, *)) { [window_ selectNextTab:nil]; } } void NativeWindowMac::MergeAllWindows() { if (@available(macOS 10.12, *)) { [window_ mergeAllWindows:nil]; } } void NativeWindowMac::MoveTabToNewWindow() { if (@available(macOS 10.12, *)) { [window_ moveTabToNewWindow:nil]; } } void NativeWindowMac::ToggleTabBar() { if (@available(macOS 10.12, *)) { [window_ toggleTabBar:nil]; } } bool NativeWindowMac::AddTabbedWindow(NativeWindow* window) { if (window_ == window->GetNativeWindow().GetNativeNSWindow()) { return false; } else { if (@available(macOS 10.12, *)) [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_.reset([[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); if (wheel_event_monitor_) { [NSEvent removeMonitor:wheel_event_monitor_]; wheel_event_monitor_ = nil; } } void NativeWindowMac::OverrideNSWindowContentView() { // When using `views::Widget` to hold WebContents, Chromium would use // `BridgedContentView` as content view, which does not support draggable // regions. In order to make draggable regions work, we have to replace the // content view with a simple NSView. if (has_frame()) { container_view_.reset( [[ElectronAdaptedContentView alloc] initWithShell:this]); } else { container_view_.reset([[FullSizeContentView alloc] init]); [container_view_ setFrame:[[[window_ contentView] superview] bounds]]; } [container_view_ setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable]; [window_ setContentView:container_view_]; AddContentViewLayers(); } 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) { base::PostTask( FROM_HERE, {content::BrowserThread::UI}, 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()) { base::scoped_nsobject<CALayer> background_layer([[CALayer alloc] init]); [background_layer setAutoresizingMask:kCALayerWidthSizable | kCALayerHeightSizable]; [[window_ contentView] setLayer:background_layer]; } [[window_ contentView] setWantsLayer:YES]; } if (!has_frame()) { // In OSX 10.10, adding subviews to the root view for the NSView hierarchy // produces warnings. To eliminate the warnings, we resize the contentView // to fill the window, and add subviews to that. // http://crbug.com/380412 if (!original_set_frame_size) { Class cl = [[window_ contentView] class]; original_set_frame_size = class_replaceMethod( cl, @selector(setFrameSize:), (IMP)SetFrameSize, "v@:{_NSSize=ff}"); original_view_did_move_to_superview = class_replaceMethod(cl, @selector(viewDidMoveToSuperview), (IMP)ViewDidMoveToSuperview, "v@:"); [[window_ contentView] viewDidMoveToWindow]; } } } void NativeWindowMac::InternalSetWindowButtonVisibility(bool visible) { [[window_ standardWindowButton:NSWindowCloseButton] setHidden:!visible]; [[window_ standardWindowButton:NSWindowMiniaturizeButton] setHidden:!visible]; [[window_ standardWindowButton:NSWindowZoomButton] setHidden:!visible]; } void NativeWindowMac::InternalSetParentWindow(NativeWindow* parent, bool attach) { if (is_modal()) return; NativeWindow::SetParentWindow(parent); // Do not remove/add if we are already properly attached. if (attach && parent && [window_ parentWindow] == parent->GetNativeWindow().GetNativeNSWindow()) return; // Remove current parent window. if ([window_ parentWindow]) [[window_ parentWindow] removeChildWindow:window_]; // Set new parent window. // Note that this method will force the window to become visible. if (parent && attach) { // Attaching a window as a child window resets its window level, so // save and restore it afterwards. NSInteger level = window_.level; [parent->GetNativeWindow().GetNativeNSWindow() addChildWindow:window_ ordered:NSWindowAbove]; [window_ setLevel:level]; } } 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
33,732
[Bug]: `BrowserWindow`: `isFocused()` returns `true` even after calling `blur()` 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 18.0.3 ### What operating system are you using? macOS ### Operating System Version macOS Monterey 12.2.1 ### What arch are you using? x64 ### Last Known Working Electron version Unknown, reproduces back to v14. ### Expected Behavior `isFocused()` should return `false` after `blur()` has been called on it. ### Actual Behavior It returns `true` instead, hence the assertion error: ```sh $ npm test > [email protected] test > electron test.js AssertionError [ERR_ASSERTION]: Expected values to be strictly equal: true !== false at /Users/raisinten/Desktop/temp/project/electron/test.js:10:3 { generatedMessage: true, code: 'ERR_ASSERTION', actual: true, expected: false, operator: 'strictEqual' } $ echo $? 1 ``` ### Testcase Gist URL https://gist.github.com/RaisinTen/245976064623786f2276dd89d2df0185 ### Additional Information _No response_
https://github.com/electron/electron/issues/33732
https://github.com/electron/electron/pull/33734
7dee5179cb0f4a79056204a243aa3317fbe711a6
f887000d505cb6dbc4d195c03f38cef943f135fd
2022-04-12T12:42:24Z
c++
2022-05-03T07:39:18Z
spec-main/api-browser-window-spec.ts
import { expect } from 'chai'; import * as childProcess from 'child_process'; import * as path from 'path'; import * as fs from 'fs'; import * as os from 'os'; import * as qs from 'querystring'; import * as http from 'http'; import * as semver from 'semver'; import { AddressInfo } from 'net'; import { app, BrowserWindow, BrowserView, dialog, ipcMain, OnBeforeSendHeadersListenerDetails, protocol, screen, webContents, session, WebContents, BrowserWindowConstructorOptions } from 'electron/main'; import { emittedOnce, emittedUntil, emittedNTimes } from './events-helpers'; import { ifit, ifdescribe, defer, delay } from './spec-helpers'; import { closeWindow, closeAllWindows } from './window-helpers'; import { areColorsSimilar, captureScreen, CHROMA_COLOR_HEX, getPixelColor } from './screen-helpers'; const features = process._linkedBinding('electron_common_features'); const fixtures = path.resolve(__dirname, '..', 'spec', 'fixtures'); const mainFixtures = path.resolve(__dirname, 'fixtures'); // Is the display's scale factor possibly causing rounding of pixel coordinate // values? const isScaleFactorRounding = () => { const { scaleFactor } = screen.getPrimaryDisplay(); // Return true if scale factor is non-integer value if (Math.round(scaleFactor) !== scaleFactor) return true; // Return true if scale factor is odd number above 2 return scaleFactor > 2 && scaleFactor % 2 === 1; }; const expectBoundsEqual = (actual: any, expected: any) => { if (!isScaleFactorRounding()) { expect(expected).to.deep.equal(actual); } else if (Array.isArray(actual)) { expect(actual[0]).to.be.closeTo(expected[0], 1); expect(actual[1]).to.be.closeTo(expected[1], 1); } else { expect(actual.x).to.be.closeTo(expected.x, 1); expect(actual.y).to.be.closeTo(expected.y, 1); expect(actual.width).to.be.closeTo(expected.width, 1); expect(actual.height).to.be.closeTo(expected.height, 1); } }; const isBeforeUnload = (event: Event, level: number, message: string) => { return (message === 'beforeunload'); }; describe('BrowserWindow module', () => { describe('BrowserWindow constructor', () => { it('allows passing void 0 as the webContents', async () => { expect(() => { const w = new BrowserWindow({ show: false, // apparently void 0 had different behaviour from undefined in the // issue that this test is supposed to catch. webContents: void 0 // eslint-disable-line no-void } as any); w.destroy(); }).not.to.throw(); }); ifit(process.platform === 'linux')('does not crash when setting large window icons', async () => { const appPath = path.join(__dirname, 'spec-main', 'fixtures', 'apps', 'xwindow-icon'); const appProcess = childProcess.spawn(process.execPath, [appPath]); await new Promise((resolve) => { appProcess.once('exit', resolve); }); }); it('does not crash or throw when passed an invalid icon', async () => { expect(() => { const w = new BrowserWindow({ icon: undefined } as any); w.destroy(); }).not.to.throw(); }); }); describe('garbage collection', () => { const v8Util = process._linkedBinding('electron_common_v8_util'); afterEach(closeAllWindows); it('window does not get garbage collected when opened', async () => { const w = new BrowserWindow({ show: false }); // Keep a weak reference to the window. // eslint-disable-next-line no-undef const wr = new WeakRef(w); await delay(); // Do garbage collection, since |w| is not referenced in this closure // it would be gone after next call if there is no other reference. v8Util.requestGarbageCollectionForTesting(); await delay(); expect(wr.deref()).to.not.be.undefined(); }); }); describe('BrowserWindow.close()', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('should work if called when a messageBox is showing', async () => { const closed = emittedOnce(w, 'closed'); dialog.showMessageBox(w, { message: 'Hello Error' }); w.close(); await closed; }); it('closes window without rounded corners', async () => { await closeWindow(w); w = new BrowserWindow({ show: false, frame: false, roundedCorners: false }); const closed = emittedOnce(w, 'closed'); w.close(); await closed; }); it('should not crash if called after webContents is destroyed', () => { w.webContents.destroy(); w.webContents.on('destroyed', () => w.close()); }); it('should emit unload handler', async () => { await w.loadFile(path.join(fixtures, 'api', 'unload.html')); const closed = emittedOnce(w, 'closed'); w.close(); await closed; const test = path.join(fixtures, 'api', 'unload'); const content = fs.readFileSync(test); fs.unlinkSync(test); expect(String(content)).to.equal('unload'); }); it('should emit beforeunload handler', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); await emittedOnce(w.webContents, 'before-unload-fired'); }); it('should not crash when keyboard event is sent before closing', async () => { await w.loadURL('data:text/html,pls no crash'); const closed = emittedOnce(w, 'closed'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' }); w.close(); await closed; }); describe('when invoked synchronously inside navigation observer', () => { let server: http.Server = null as unknown as http.Server; let url: string = null as unknown as string; before((done) => { server = http.createServer((request, response) => { switch (request.url) { case '/net-error': response.destroy(); break; case '/301': response.statusCode = 301; response.setHeader('Location', '/200'); response.end(); break; case '/200': response.statusCode = 200; response.end('hello'); break; case '/title': response.statusCode = 200; response.end('<title>Hello</title>'); break; default: throw new Error(`unsupported endpoint: ${request.url}`); } }).listen(0, '127.0.0.1', () => { url = 'http://127.0.0.1:' + (server.address() as AddressInfo).port; done(); }); }); after(() => { server.close(); }); const events = [ { name: 'did-start-loading', path: '/200' }, { name: 'dom-ready', path: '/200' }, { name: 'page-title-updated', path: '/title' }, { name: 'did-stop-loading', path: '/200' }, { name: 'did-finish-load', path: '/200' }, { name: 'did-frame-finish-load', path: '/200' }, { name: 'did-fail-load', path: '/net-error' } ]; for (const { name, path } of events) { it(`should not crash when closed during ${name}`, async () => { const w = new BrowserWindow({ show: false }); w.webContents.once((name as any), () => { w.close(); }); const destroyed = emittedOnce(w.webContents, 'destroyed'); w.webContents.loadURL(url + path); await destroyed; }); } }); }); describe('window.close()', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('should emit unload event', async () => { w.loadFile(path.join(fixtures, 'api', 'close.html')); await emittedOnce(w, 'closed'); const test = path.join(fixtures, 'api', 'close'); const content = fs.readFileSync(test).toString(); fs.unlinkSync(test); expect(content).to.equal('close'); }); it('should emit beforeunload event', async function () { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.webContents.executeJavaScript('window.close()', true); await emittedOnce(w.webContents, 'before-unload-fired'); }); }); describe('BrowserWindow.destroy()', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('prevents users to access methods of webContents', async () => { const contents = w.webContents; w.destroy(); await new Promise(setImmediate); expect(() => { contents.getProcessId(); }).to.throw('Object has been destroyed'); }); it('should not crash when destroying windows with pending events', () => { const focusListener = () => { }; app.on('browser-window-focus', focusListener); const windowCount = 3; const windowOptions = { show: false, width: 400, height: 400, webPreferences: { backgroundThrottling: false } }; const windows = Array.from(Array(windowCount)).map(() => new BrowserWindow(windowOptions)); windows.forEach(win => win.show()); windows.forEach(win => win.focus()); windows.forEach(win => win.destroy()); app.removeListener('browser-window-focus', focusListener); }); }); describe('BrowserWindow.loadURL(url)', () => { let w = null as unknown as BrowserWindow; const scheme = 'other'; const srcPath = path.join(fixtures, 'api', 'loaded-from-dataurl.js'); before(() => { protocol.registerFileProtocol(scheme, (request, callback) => { callback(srcPath); }); }); after(() => { protocol.unregisterProtocol(scheme); }); beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); let server = null as unknown as http.Server; let url = null as unknown as string; let postData = null as any; before((done) => { const filePath = path.join(fixtures, 'pages', 'a.html'); const fileStats = fs.statSync(filePath); postData = [ { type: 'rawData', bytes: Buffer.from('username=test&file=') }, { type: 'file', filePath: filePath, offset: 0, length: fileStats.size, modificationTime: fileStats.mtime.getTime() / 1000 } ]; server = http.createServer((req, res) => { function respond () { if (req.method === 'POST') { let body = ''; req.on('data', (data) => { if (data) body += data; }); req.on('end', () => { const parsedData = qs.parse(body); fs.readFile(filePath, (err, data) => { if (err) return; if (parsedData.username === 'test' && parsedData.file === data.toString()) { res.end(); } }); }); } else if (req.url === '/302') { res.setHeader('Location', '/200'); res.statusCode = 302; res.end(); } else { res.end(); } } setTimeout(respond, req.url && req.url.includes('slow') ? 200 : 0); }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; done(); }); }); after(() => { server.close(); }); it('should emit did-start-loading event', async () => { const didStartLoading = emittedOnce(w.webContents, 'did-start-loading'); w.loadURL('about:blank'); await didStartLoading; }); it('should emit ready-to-show event', async () => { const readyToShow = emittedOnce(w, 'ready-to-show'); w.loadURL('about:blank'); await readyToShow; }); // TODO(deepak1556): The error code now seems to be `ERR_FAILED`, verify what // changed and adjust the test. it.skip('should emit did-fail-load event for files that do not exist', async () => { const didFailLoad = emittedOnce(w.webContents, 'did-fail-load'); w.loadURL('file://a.txt'); const [, code, desc,, isMainFrame] = await didFailLoad; expect(code).to.equal(-6); expect(desc).to.equal('ERR_FILE_NOT_FOUND'); expect(isMainFrame).to.equal(true); }); it('should emit did-fail-load event for invalid URL', async () => { const didFailLoad = emittedOnce(w.webContents, 'did-fail-load'); w.loadURL('http://example:port'); const [, code, desc,, isMainFrame] = await didFailLoad; expect(desc).to.equal('ERR_INVALID_URL'); expect(code).to.equal(-300); expect(isMainFrame).to.equal(true); }); it('should set `mainFrame = false` on did-fail-load events in iframes', async () => { const didFailLoad = emittedOnce(w.webContents, 'did-fail-load'); w.loadFile(path.join(fixtures, 'api', 'did-fail-load-iframe.html')); const [,,,, isMainFrame] = await didFailLoad; expect(isMainFrame).to.equal(false); }); it('does not crash in did-fail-provisional-load handler', (done) => { w.webContents.once('did-fail-provisional-load', () => { w.loadURL('http://127.0.0.1:11111'); done(); }); w.loadURL('http://127.0.0.1:11111'); }); it('should emit did-fail-load event for URL exceeding character limit', async () => { const data = Buffer.alloc(2 * 1024 * 1024).toString('base64'); const didFailLoad = emittedOnce(w.webContents, 'did-fail-load'); w.loadURL(`data:image/png;base64,${data}`); const [, code, desc,, isMainFrame] = await didFailLoad; expect(desc).to.equal('ERR_INVALID_URL'); expect(code).to.equal(-300); expect(isMainFrame).to.equal(true); }); it('should return a promise', () => { const p = w.loadURL('about:blank'); expect(p).to.have.property('then'); }); it('should return a promise that resolves', async () => { await expect(w.loadURL('about:blank')).to.eventually.be.fulfilled(); }); it('should return a promise that rejects on a load failure', async () => { const data = Buffer.alloc(2 * 1024 * 1024).toString('base64'); const p = w.loadURL(`data:image/png;base64,${data}`); await expect(p).to.eventually.be.rejected; }); it('should return a promise that resolves even if pushState occurs during navigation', async () => { const p = w.loadURL('data:text/html,<script>window.history.pushState({}, "/foo")</script>'); await expect(p).to.eventually.be.fulfilled; }); describe('POST navigations', () => { afterEach(() => { w.webContents.session.webRequest.onBeforeSendHeaders(null); }); it('supports specifying POST data', async () => { await w.loadURL(url, { postData }); }); it('sets the content type header on URL encoded forms', async () => { await w.loadURL(url); const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => { w.webContents.session.webRequest.onBeforeSendHeaders((details) => { resolve(details); }); }); w.webContents.executeJavaScript(` form = document.createElement('form') document.body.appendChild(form) form.method = 'POST' form.submit() `); const details = await requestDetails; expect(details.requestHeaders['Content-Type']).to.equal('application/x-www-form-urlencoded'); }); it('sets the content type header on multi part forms', async () => { await w.loadURL(url); const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => { w.webContents.session.webRequest.onBeforeSendHeaders((details) => { resolve(details); }); }); w.webContents.executeJavaScript(` form = document.createElement('form') document.body.appendChild(form) form.method = 'POST' form.enctype = 'multipart/form-data' file = document.createElement('input') file.type = 'file' file.name = 'file' form.appendChild(file) form.submit() `); const details = await requestDetails; expect(details.requestHeaders['Content-Type'].startsWith('multipart/form-data; boundary=----WebKitFormBoundary')).to.equal(true); }); }); it('should support base url for data urls', async () => { await w.loadURL('data:text/html,<script src="loaded-from-dataurl.js"></script>', { baseURLForDataURL: `other://${path.join(fixtures, 'api')}${path.sep}` }); expect(await w.webContents.executeJavaScript('window.ping')).to.equal('pong'); }); }); for (const sandbox of [false, true]) { describe(`navigation events${sandbox ? ' with sandbox' : ''}`, () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: false, sandbox } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('will-navigate event', () => { let server = null as unknown as http.Server; let url = null as unknown as string; before((done) => { server = http.createServer((req, res) => { if (req.url === '/navigate-top') { res.end('<a target=_top href="/">navigate _top</a>'); } else { res.end(''); } }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/`; done(); }); }); after(() => { server.close(); }); it('allows the window to be closed from the event listener', (done) => { w.webContents.once('will-navigate', () => { w.close(); done(); }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('can be prevented', (done) => { let willNavigate = false; w.webContents.once('will-navigate', (e) => { willNavigate = true; e.preventDefault(); }); w.webContents.on('did-stop-loading', () => { if (willNavigate) { // i.e. it shouldn't have had '?navigated' appended to it. try { expect(w.webContents.getURL().endsWith('will-navigate.html')).to.be.true(); done(); } catch (e) { done(e); } } }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('is triggered when navigating from file: to http:', async () => { await w.loadFile(path.join(fixtures, 'api', 'blank.html')); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-navigate', (e, url) => { e.preventDefault(); resolve(url); }); }); expect(navigatedTo).to.equal(url); expect(w.webContents.getURL()).to.match(/^file:/); }); it('is triggered when navigating from about:blank to http:', async () => { await w.loadURL('about:blank'); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-navigate', (e, url) => { e.preventDefault(); resolve(url); }); }); expect(navigatedTo).to.equal(url); expect(w.webContents.getURL()).to.equal('about:blank'); }); it('is triggered when a cross-origin iframe navigates _top', async () => { await w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-top"></iframe>`); await delay(1000); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const iframeTarget = targets.targetInfos.find((t: any) => t.type === 'iframe'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: iframeTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); let willNavigateEmitted = false; w.webContents.on('will-navigate', () => { willNavigateEmitted = true; }); await emittedOnce(w.webContents, 'did-navigate'); expect(willNavigateEmitted).to.be.true(); }); }); describe('will-redirect event', () => { let server = null as unknown as http.Server; let url = null as unknown as string; before((done) => { server = http.createServer((req, res) => { if (req.url === '/302') { res.setHeader('Location', '/200'); res.statusCode = 302; res.end(); } else if (req.url === '/navigate-302') { res.end(`<html><body><script>window.location='${url}/302'</script></body></html>`); } else { res.end(); } }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; done(); }); }); after(() => { server.close(); }); it('is emitted on redirects', async () => { const willRedirect = emittedOnce(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await willRedirect; }); it('is emitted after will-navigate on redirects', async () => { let navigateCalled = false; w.webContents.on('will-navigate', () => { navigateCalled = true; }); const willRedirect = emittedOnce(w.webContents, 'will-redirect'); w.loadURL(`${url}/navigate-302`); await willRedirect; expect(navigateCalled).to.equal(true, 'should have called will-navigate first'); }); it('is emitted before did-stop-loading on redirects', async () => { let stopCalled = false; w.webContents.on('did-stop-loading', () => { stopCalled = true; }); const willRedirect = emittedOnce(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await willRedirect; expect(stopCalled).to.equal(false, 'should not have called did-stop-loading first'); }); it('allows the window to be closed from the event listener', (done) => { w.webContents.once('will-redirect', () => { w.close(); done(); }); w.loadURL(`${url}/302`); }); it('can be prevented', (done) => { w.webContents.once('will-redirect', (event) => { event.preventDefault(); }); w.webContents.on('will-navigate', (e, u) => { expect(u).to.equal(`${url}/302`); }); w.webContents.on('did-stop-loading', () => { try { expect(w.webContents.getURL()).to.equal( `${url}/navigate-302`, 'url should not have changed after navigation event' ); done(); } catch (e) { done(e); } }); w.webContents.on('will-redirect', (e, u) => { try { expect(u).to.equal(`${url}/200`); } catch (e) { done(e); } }); w.loadURL(`${url}/navigate-302`); }); }); }); } describe('focus and visibility', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.show()', () => { it('should focus on window', () => { w.show(); expect(w.isFocused()).to.equal(true); }); it('should make the window visible', () => { w.show(); expect(w.isVisible()).to.equal(true); }); it('emits when window is shown', async () => { const show = emittedOnce(w, 'show'); w.show(); await show; expect(w.isVisible()).to.equal(true); }); }); describe('BrowserWindow.hide()', () => { it('should defocus on window', () => { w.hide(); expect(w.isFocused()).to.equal(false); }); it('should make the window not visible', () => { w.show(); w.hide(); expect(w.isVisible()).to.equal(false); }); it('emits when window is hidden', async () => { const shown = emittedOnce(w, 'show'); w.show(); await shown; const hidden = emittedOnce(w, 'hide'); w.hide(); await hidden; expect(w.isVisible()).to.equal(false); }); }); describe('BrowserWindow.showInactive()', () => { it('should not focus on window', () => { w.showInactive(); expect(w.isFocused()).to.equal(false); }); // TODO(dsanders11): Enable for Linux once CI plays nice with these kinds of tests ifit(process.platform !== 'linux')('should not restore maximized windows', async () => { const maximize = emittedOnce(w, 'maximize'); const shown = emittedOnce(w, 'show'); w.maximize(); // TODO(dsanders11): The maximize event isn't firing on macOS for a window initially hidden if (process.platform !== 'darwin') { await maximize; } else { await delay(1000); } w.showInactive(); await shown; expect(w.isMaximized()).to.equal(true); }); }); describe('BrowserWindow.focus()', () => { it('does not make the window become visible', () => { expect(w.isVisible()).to.equal(false); w.focus(); expect(w.isVisible()).to.equal(false); }); }); describe('BrowserWindow.blur()', () => { it('removes focus from window', () => { w.blur(); expect(w.isFocused()).to.equal(false); }); }); describe('BrowserWindow.getFocusedWindow()', () => { it('returns the opener window when dev tools window is focused', async () => { w.show(); w.webContents.openDevTools({ mode: 'undocked' }); await emittedOnce(w.webContents, 'devtools-focused'); expect(BrowserWindow.getFocusedWindow()).to.equal(w); }); }); describe('BrowserWindow.moveTop()', () => { it('should not steal focus', async () => { const posDelta = 50; const wShownInactive = emittedOnce(w, 'show'); w.showInactive(); await wShownInactive; expect(w.isFocused()).to.equal(false); const otherWindow = new BrowserWindow({ show: false, title: 'otherWindow' }); const otherWindowShown = emittedOnce(otherWindow, 'show'); const otherWindowFocused = emittedOnce(otherWindow, 'focus'); otherWindow.show(); await otherWindowShown; await otherWindowFocused; expect(otherWindow.isFocused()).to.equal(true); w.moveTop(); const wPos = w.getPosition(); const wMoving = emittedOnce(w, 'move'); w.setPosition(wPos[0] + posDelta, wPos[1] + posDelta); await wMoving; expect(w.isFocused()).to.equal(false); expect(otherWindow.isFocused()).to.equal(true); const wFocused = emittedOnce(w, 'focus'); const otherWindowBlurred = emittedOnce(otherWindow, 'blur'); w.focus(); await wFocused; await otherWindowBlurred; expect(w.isFocused()).to.equal(true); otherWindow.moveTop(); const otherWindowPos = otherWindow.getPosition(); const otherWindowMoving = emittedOnce(otherWindow, 'move'); otherWindow.setPosition(otherWindowPos[0] + posDelta, otherWindowPos[1] + posDelta); await otherWindowMoving; expect(otherWindow.isFocused()).to.equal(false); expect(w.isFocused()).to.equal(true); await closeWindow(otherWindow, { assertNotWindows: false }); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1); }); }); ifdescribe(features.isDesktopCapturerEnabled())('BrowserWindow.moveAbove(mediaSourceId)', () => { it('should throw an exception if wrong formatting', async () => { const fakeSourceIds = [ 'none', 'screen:0', 'window:fake', 'window:1234', 'foobar:1:2' ]; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Invalid media source id/); }); }); it('should throw an exception if wrong type', async () => { const fakeSourceIds = [null as any, 123 as any]; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Error processing argument at index 0 */); }); }); it('should throw an exception if invalid window', async () => { // It is very unlikely that these window id exist. const fakeSourceIds = ['window:99999999:0', 'window:123456:1', 'window:123456:9']; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Invalid media source id/); }); }); it('should not throw an exception', async () => { const w2 = new BrowserWindow({ show: false, title: 'window2' }); const w2Shown = emittedOnce(w2, 'show'); w2.show(); await w2Shown; expect(() => { w.moveAbove(w2.getMediaSourceId()); }).to.not.throw(); await closeWindow(w2, { assertNotWindows: false }); }); }); describe('BrowserWindow.setFocusable()', () => { it('can set unfocusable window to focusable', async () => { const w2 = new BrowserWindow({ focusable: false }); const w2Focused = emittedOnce(w2, 'focus'); w2.setFocusable(true); w2.focus(); await w2Focused; await closeWindow(w2, { assertNotWindows: false }); }); }); describe('BrowserWindow.isFocusable()', () => { it('correctly returns whether a window is focusable', async () => { const w2 = new BrowserWindow({ focusable: false }); expect(w2.isFocusable()).to.be.false(); w2.setFocusable(true); expect(w2.isFocusable()).to.be.true(); await closeWindow(w2, { assertNotWindows: false }); }); }); }); describe('sizing', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, width: 400, height: 400 }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.setBounds(bounds[, animate])', () => { it('sets the window bounds with full bounds', () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds); expectBoundsEqual(w.getBounds(), fullBounds); }); it('sets the window bounds with partial bounds', () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds); const boundsUpdate = { width: 200 }; w.setBounds(boundsUpdate as any); const expectedBounds = Object.assign(fullBounds, boundsUpdate); expectBoundsEqual(w.getBounds(), expectedBounds); }); ifit(process.platform === 'darwin')('on macOS', () => { it('emits \'resized\' event after animating', async () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds, true); await expect(emittedOnce(w, 'resized')).to.eventually.be.fulfilled(); }); }); }); describe('BrowserWindow.setSize(width, height)', () => { it('sets the window size', async () => { const size = [300, 400]; const resized = emittedOnce(w, 'resize'); w.setSize(size[0], size[1]); await resized; expectBoundsEqual(w.getSize(), size); }); ifit(process.platform === 'darwin')('on macOS', () => { it('emits \'resized\' event after animating', async () => { const size = [300, 400]; w.setSize(size[0], size[1], true); await expect(emittedOnce(w, 'resized')).to.eventually.be.fulfilled(); }); }); }); describe('BrowserWindow.setMinimum/MaximumSize(width, height)', () => { it('sets the maximum and minimum size of the window', () => { expect(w.getMinimumSize()).to.deep.equal([0, 0]); expect(w.getMaximumSize()).to.deep.equal([0, 0]); w.setMinimumSize(100, 100); expectBoundsEqual(w.getMinimumSize(), [100, 100]); expectBoundsEqual(w.getMaximumSize(), [0, 0]); w.setMaximumSize(900, 600); expectBoundsEqual(w.getMinimumSize(), [100, 100]); expectBoundsEqual(w.getMaximumSize(), [900, 600]); }); }); describe('BrowserWindow.setAspectRatio(ratio)', () => { it('resets the behaviour when passing in 0', async () => { const size = [300, 400]; w.setAspectRatio(1 / 2); w.setAspectRatio(0); const resize = emittedOnce(w, 'resize'); w.setSize(size[0], size[1]); await resize; expectBoundsEqual(w.getSize(), size); }); it('doesn\'t change bounds when maximum size is set', () => { w.setMenu(null); w.setMaximumSize(400, 400); // Without https://github.com/electron/electron/pull/29101 // following call would shrink the window to 384x361. // There would be also DCHECK in resize_utils.cc on // debug build. w.setAspectRatio(1.0); expectBoundsEqual(w.getSize(), [400, 400]); }); }); describe('BrowserWindow.setPosition(x, y)', () => { it('sets the window position', async () => { const pos = [10, 10]; const move = emittedOnce(w, 'move'); w.setPosition(pos[0], pos[1]); await move; expect(w.getPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setContentSize(width, height)', () => { it('sets the content size', async () => { // NB. The CI server has a very small screen. Attempting to size the window // larger than the screen will limit the window's size to the screen and // cause the test to fail. const size = [456, 567]; w.setContentSize(size[0], size[1]); await new Promise(setImmediate); const after = w.getContentSize(); expect(after).to.deep.equal(size); }); it('works for a frameless window', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 400, height: 400 }); const size = [456, 567]; w.setContentSize(size[0], size[1]); await new Promise(setImmediate); const after = w.getContentSize(); expect(after).to.deep.equal(size); }); }); describe('BrowserWindow.setContentBounds(bounds)', () => { it('sets the content size and position', async () => { const bounds = { x: 10, y: 10, width: 250, height: 250 }; const resize = emittedOnce(w, 'resize'); w.setContentBounds(bounds); await resize; await delay(); expectBoundsEqual(w.getContentBounds(), bounds); }); it('works for a frameless window', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300 }); const bounds = { x: 10, y: 10, width: 250, height: 250 }; const resize = emittedOnce(w, 'resize'); w.setContentBounds(bounds); await resize; await delay(); expectBoundsEqual(w.getContentBounds(), bounds); }); }); describe('BrowserWindow.getBackgroundColor()', () => { it('returns default value if no backgroundColor is set', () => { w.destroy(); w = new BrowserWindow({}); expect(w.getBackgroundColor()).to.equal('#FFFFFF'); }); it('returns correct value if backgroundColor is set', () => { const backgroundColor = '#BBAAFF'; w.destroy(); w = new BrowserWindow({ backgroundColor: backgroundColor }); expect(w.getBackgroundColor()).to.equal(backgroundColor); }); it('returns correct value from setBackgroundColor()', () => { const backgroundColor = '#AABBFF'; w.destroy(); w = new BrowserWindow({}); w.setBackgroundColor(backgroundColor); expect(w.getBackgroundColor()).to.equal(backgroundColor); }); 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 = emittedOnce(w, 'resize'); w.setSize(size[0], size[1]); await resize; expectBoundsEqual(w.getNormalBounds(), w.getBounds()); }); it('checks normal bounds after move', async () => { const pos = [10, 10]; const move = emittedOnce(w, 'move'); w.setPosition(pos[0], pos[1]); await move; expectBoundsEqual(w.getNormalBounds(), w.getBounds()); }); }); ifdescribe(process.platform !== 'linux')('Maximized state', () => { it('checks normal bounds when maximized', async () => { const bounds = w.getBounds(); const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('checks normal bounds when unmaximized', async () => { const bounds = w.getBounds(); w.once('maximize', () => { w.unmaximize(); }); const unmaximize = emittedOnce(w, 'unmaximize'); w.show(); w.maximize(); await unmaximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('does not change size for a frameless window with min size', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300, minWidth: 300, minHeight: 300 }); const bounds = w.getBounds(); w.once('maximize', () => { w.unmaximize(); }); const unmaximize = emittedOnce(w, 'unmaximize'); w.show(); w.maximize(); await unmaximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('correctly checks transparent window maximization state', async () => { w.destroy(); w = new BrowserWindow({ show: false, width: 300, height: 300, transparent: true }); const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; expect(w.isMaximized()).to.equal(true); const unmaximize = emittedOnce(w, 'unmaximize'); w.unmaximize(); await unmaximize; expect(w.isMaximized()).to.equal(false); }); it('returns the correct value for windows with an aspect ratio', async () => { w.destroy(); w = new BrowserWindow({ show: false, fullscreenable: false }); w.setAspectRatio(16 / 11); const maximize = emittedOnce(w, 'resize'); w.show(); w.maximize(); await maximize; expect(w.isMaximized()).to.equal(true); w.resizable = false; expect(w.isMaximized()).to.equal(true); }); }); ifdescribe(process.platform !== 'linux')('Minimized state', () => { it('checks normal bounds when minimized', async () => { const bounds = w.getBounds(); const minimize = emittedOnce(w, 'minimize'); w.show(); w.minimize(); await minimize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('checks normal bounds when restored', async () => { const bounds = w.getBounds(); w.once('minimize', () => { w.restore(); }); const restore = emittedOnce(w, 'restore'); w.show(); w.minimize(); await restore; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('does not change size for a frameless window with min size', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300, minWidth: 300, minHeight: 300 }); const bounds = w.getBounds(); w.once('minimize', () => { w.restore(); }); const restore = emittedOnce(w, 'restore'); w.show(); w.minimize(); await restore; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); ifdescribe(process.platform === 'win32')('Fullscreen state', () => { it('with properties', () => { it('can be set with the fullscreen constructor option', () => { w = new BrowserWindow({ fullscreen: true }); expect(w.fullScreen).to.be.true(); }); it('can be changed', () => { w.fullScreen = false; expect(w.fullScreen).to.be.false(); w.fullScreen = true; expect(w.fullScreen).to.be.true(); }); it('checks normal bounds when fullscreen\'ed', async () => { const bounds = w.getBounds(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.show(); w.fullScreen = true; await enterFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('checks normal bounds when unfullscreen\'ed', async () => { const bounds = w.getBounds(); w.once('enter-full-screen', () => { w.fullScreen = false; }); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.show(); w.fullScreen = true; await leaveFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); it('with functions', () => { it('can be set with the fullscreen constructor option', () => { w = new BrowserWindow({ fullscreen: true }); expect(w.isFullScreen()).to.be.true(); }); it('can be changed', () => { w.setFullScreen(false); expect(w.isFullScreen()).to.be.false(); w.setFullScreen(true); expect(w.isFullScreen()).to.be.true(); }); it('checks normal bounds when fullscreen\'ed', async () => { const bounds = w.getBounds(); w.show(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('checks normal bounds when unfullscreen\'ed', async () => { const bounds = w.getBounds(); w.show(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); }); }); }); ifdescribe(process.platform === 'darwin')('tabbed windows', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.selectPreviousTab()', () => { it('does not throw', () => { expect(() => { w.selectPreviousTab(); }).to.not.throw(); }); }); describe('BrowserWindow.selectNextTab()', () => { it('does not throw', () => { expect(() => { w.selectNextTab(); }).to.not.throw(); }); }); describe('BrowserWindow.mergeAllWindows()', () => { it('does not throw', () => { expect(() => { w.mergeAllWindows(); }).to.not.throw(); }); }); describe('BrowserWindow.moveTabToNewWindow()', () => { it('does not throw', () => { expect(() => { w.moveTabToNewWindow(); }).to.not.throw(); }); }); describe('BrowserWindow.toggleTabBar()', () => { it('does not throw', () => { expect(() => { w.toggleTabBar(); }).to.not.throw(); }); }); describe('BrowserWindow.addTabbedWindow()', () => { it('does not throw', async () => { const tabbedWindow = new BrowserWindow({}); expect(() => { w.addTabbedWindow(tabbedWindow); }).to.not.throw(); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(2); // w + tabbedWindow await closeWindow(tabbedWindow, { assertNotWindows: false }); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1); // w }); it('throws when called on itself', () => { expect(() => { w.addTabbedWindow(w); }).to.throw('AddTabbedWindow cannot be called by a window on itself.'); }); }); }); describe('autoHideMenuBar state', () => { afterEach(closeAllWindows); it('for properties', () => { it('can be set with autoHideMenuBar constructor option', () => { const w = new BrowserWindow({ show: false, autoHideMenuBar: true }); expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); w.autoHideMenuBar = true; expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); w.autoHideMenuBar = false; expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); }); }); it('for functions', () => { it('can be set with autoHideMenuBar constructor option', () => { const w = new BrowserWindow({ show: false, autoHideMenuBar: true }); expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar'); w.setAutoHideMenuBar(true); expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar'); w.setAutoHideMenuBar(false); expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar'); }); }); }); describe('BrowserWindow.capturePage(rect)', () => { afterEach(closeAllWindows); it('returns a Promise with a Buffer', async () => { const w = new BrowserWindow({ show: false }); const image = await w.capturePage({ x: 0, y: 0, width: 100, height: 100 }); expect(image.isEmpty()).to.equal(true); }); it('resolves after the window is hidden', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixtures, 'pages', 'a.html')); await emittedOnce(w, 'ready-to-show'); w.show(); const visibleImage = await w.capturePage(); expect(visibleImage.isEmpty()).to.equal(false); w.hide(); const hiddenImage = await w.capturePage(); const isEmpty = process.platform !== 'darwin'; expect(hiddenImage.isEmpty()).to.equal(isEmpty); }); it('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 emittedOnce(w, 'ready-to-show'); w.webContents.incrementCapturerCount(); 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 emittedOnce(w, 'ready-to-show'); w.show(); const image = await w.capturePage(); const imgBuffer = image.toPNG(); // Check the 25th byte in the PNG. // Values can be 0,2,3,4, or 6. We want 6, which is RGB + Alpha expect(imgBuffer[25]).to.equal(6); }); it('should increase the capturer count', () => { const w = new BrowserWindow({ show: false }); w.webContents.incrementCapturerCount(); expect(w.webContents.isBeingCaptured()).to.be.true(); w.webContents.decrementCapturerCount(); expect(w.webContents.isBeingCaptured()).to.be.false(); }); }); describe('BrowserWindow.setProgressBar(progress)', () => { let w = null as unknown as BrowserWindow; before(() => { w = new BrowserWindow({ show: false }); }); after(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('sets the progress', () => { expect(() => { if (process.platform === 'darwin') { app.dock.setIcon(path.join(fixtures, 'assets', 'logo.png')); } w.setProgressBar(0.5); if (process.platform === 'darwin') { app.dock.setIcon(null as any); } w.setProgressBar(-1); }).to.not.throw(); }); it('sets the progress using "paused" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'paused' }); }).to.not.throw(); }); it('sets the progress using "error" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'error' }); }).to.not.throw(); }); it('sets the progress using "normal" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'normal' }); }).to.not.throw(); }); }); describe('BrowserWindow.setAlwaysOnTop(flag, level)', () => { let w = null as unknown as BrowserWindow; afterEach(closeAllWindows); beforeEach(() => { w = new BrowserWindow({ show: true }); }); it('sets the window as always on top', () => { expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); w.setAlwaysOnTop(false); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); }); ifit(process.platform === 'darwin')('resets the windows level on minimize', () => { expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); w.minimize(); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.restore(); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); }); it('causes the right value to be emitted on `always-on-top-changed`', async () => { const alwaysOnTopChanged = emittedOnce(w, 'always-on-top-changed'); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true); const [, alwaysOnTop] = await alwaysOnTopChanged; expect(alwaysOnTop).to.be.true('is not alwaysOnTop'); }); ifit(process.platform === 'darwin')('honors the alwaysOnTop level of a child window', () => { w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ parent: w }); c.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.false(); expect(c.isAlwaysOnTop()).to.be.true('child is not always on top'); expect((c as any)._getAlwaysOnTopLevel()).to.equal('screen-saver'); }); }); describe('preconnect feature', () => { let w = null as unknown as BrowserWindow; let server = null as unknown as http.Server; let url = null as unknown as string; let connections = 0; beforeEach(async () => { connections = 0; server = http.createServer((req, res) => { if (req.url === '/link') { res.setHeader('Content-type', 'text/html'); res.end('<head><link rel="preconnect" href="//example.com" /></head><body>foo</body>'); return; } res.end(); }); server.on('connection', () => { connections++; }); await new Promise<void>(resolve => server.listen(0, '127.0.0.1', () => resolve())); url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; }); afterEach(async () => { server.close(); await closeWindow(w); w = null as unknown as BrowserWindow; server = null as unknown as http.Server; }); it('calling preconnect() connects to the server', async () => { w = new BrowserWindow({ show: false }); w.webContents.on('did-start-navigation', (event, url) => { w.webContents.session.preconnect({ url, numSockets: 4 }); }); await w.loadURL(url); expect(connections).to.equal(4); }); it('does not preconnect unless requested', async () => { w = new BrowserWindow({ show: false }); await w.loadURL(url); expect(connections).to.equal(1); }); it('parses <link rel=preconnect>', async () => { w = new BrowserWindow({ show: true }); const p = emittedOnce(w.webContents.session, 'preconnect'); w.loadURL(url + '/link'); const [, preconnectUrl, allowCredentials] = await p; expect(preconnectUrl).to.equal('http://example.com/'); expect(allowCredentials).to.be.true('allowCredentials'); }); }); describe('BrowserWindow.setAutoHideCursor(autoHide)', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); ifit(process.platform === 'darwin')('on macOS', () => { it('allows changing cursor auto-hiding', () => { expect(() => { w.setAutoHideCursor(false); w.setAutoHideCursor(true); }).to.not.throw(); }); }); ifit(process.platform !== 'darwin')('on non-macOS platforms', () => { it('is not available', () => { expect(w.setAutoHideCursor).to.be.undefined('setAutoHideCursor function'); }); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setWindowButtonVisibility()', () => { afterEach(closeAllWindows); it('does not throw', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setWindowButtonVisibility(true); w.setWindowButtonVisibility(false); }).to.not.throw(); }); it('changes window button visibility for normal window', () => { const w = new BrowserWindow({ show: false }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); it('changes window button visibility for frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); }); it('changes window button visibility for hiddenInset window', () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hiddenInset' }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); // Buttons of customButtonsOnHover are always hidden unless hovered. it('does not change window button visibility for customButtonsOnHover window', () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'customButtonsOnHover' }); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setVibrancy(type)', () => { let appProcess: childProcess.ChildProcessWithoutNullStreams | undefined; afterEach(() => { if (appProcess && !appProcess.killed) { appProcess.kill(); appProcess = undefined; } closeAllWindows(); }); it('allows setting, changing, and removing the vibrancy', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setVibrancy('light'); w.setVibrancy('dark'); w.setVibrancy(null); w.setVibrancy('ultra-dark'); w.setVibrancy('' as any); }).to.not.throw(); }); it('does not crash if vibrancy is set to an invalid value', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setVibrancy('i-am-not-a-valid-vibrancy-type' as any); }).to.not.throw(); }); it('Allows setting a transparent window via CSS', async () => { const appPath = path.join(__dirname, 'fixtures', 'apps', 'background-color-transparent'); appProcess = childProcess.spawn(process.execPath, [appPath]); const [code] = await emittedOnce(appProcess, 'exit'); expect(code).to.equal(0); }); }); ifdescribe(process.platform === 'darwin')('trafficLightPosition', () => { const pos = { x: 10, y: 10 }; afterEach(closeAllWindows); describe('BrowserWindow.getTrafficLightPosition(pos)', () => { it('gets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); expect(w.getTrafficLightPosition()).to.deep.equal(pos); }); it('gets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); expect(w.getTrafficLightPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setTrafficLightPosition(pos)', () => { it('sets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setTrafficLightPosition(newPos); expect(w.getTrafficLightPosition()).to.deep.equal(newPos); }); it('sets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setTrafficLightPosition(newPos); expect(w.getTrafficLightPosition()).to.deep.equal(newPos); }); }); }); ifdescribe(process.platform === 'win32')('BrowserWindow.setAppDetails(options)', () => { afterEach(closeAllWindows); it('supports setting the app details', () => { const w = new BrowserWindow({ show: false }); const iconPath = path.join(fixtures, 'assets', 'icon.ico'); expect(() => { w.setAppDetails({ appId: 'my.app.id' }); w.setAppDetails({ appIconPath: iconPath, appIconIndex: 0 }); w.setAppDetails({ appIconPath: iconPath }); w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name' }); w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2' }); w.setAppDetails({ relaunchDisplayName: 'My app name' }); w.setAppDetails({ appId: 'my.app.id', appIconPath: iconPath, appIconIndex: 0, relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name' }); w.setAppDetails({}); }).to.not.throw(); expect(() => { (w.setAppDetails as any)(); }).to.throw('Insufficient number of arguments.'); }); }); describe('BrowserWindow.fromId(id)', () => { afterEach(closeAllWindows); it('returns the window with id', () => { const w = new BrowserWindow({ show: false }); expect(BrowserWindow.fromId(w.id)!.id).to.equal(w.id); }); }); describe('BrowserWindow.fromWebContents(webContents)', () => { afterEach(closeAllWindows); it('returns the window with the webContents', () => { const w = new BrowserWindow({ show: false }); const found = BrowserWindow.fromWebContents(w.webContents); expect(found!.id).to.equal(w.id); }); it('returns null for webContents without a BrowserWindow', () => { const contents = (webContents as any).create({}); try { expect(BrowserWindow.fromWebContents(contents)).to.be.null('BrowserWindow.fromWebContents(contents)'); } finally { contents.destroy(); } }); it('returns the correct window for a BrowserView webcontents', async () => { const w = new BrowserWindow({ show: false }); const bv = new BrowserView(); w.setBrowserView(bv); defer(() => { w.removeBrowserView(bv); (bv.webContents as any).destroy(); }); await bv.webContents.loadURL('about:blank'); expect(BrowserWindow.fromWebContents(bv.webContents)!.id).to.equal(w.id); }); it('returns the correct window for a WebView webcontents', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } }); w.loadURL('data:text/html,<webview src="data:text/html,hi"></webview>'); // NOTE(nornagon): Waiting for 'did-attach-webview' is a workaround for // https://github.com/electron/electron/issues/25413, and is not integral // to the test. const p = emittedOnce(w.webContents, 'did-attach-webview'); const [, webviewContents] = await emittedOnce(app, 'web-contents-created'); expect(BrowserWindow.fromWebContents(webviewContents)!.id).to.equal(w.id); await p; }); 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((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 as any).destroy(); }); expect(BrowserWindow.fromBrowserView(bv)!.id).to.equal(w.id); }); it('returns the window when there are multiple BrowserViews', () => { const w = new BrowserWindow({ show: false }); const bv1 = new BrowserView(); w.addBrowserView(bv1); const bv2 = new BrowserView(); w.addBrowserView(bv2); defer(() => { w.removeBrowserView(bv1); w.removeBrowserView(bv2); (bv1.webContents as any).destroy(); (bv2.webContents as any).destroy(); }); expect(BrowserWindow.fromBrowserView(bv1)!.id).to.equal(w.id); expect(BrowserWindow.fromBrowserView(bv2)!.id).to.equal(w.id); }); it('returns undefined if not attached', () => { const bv = new BrowserView(); defer(() => { (bv.webContents as any).destroy(); }); expect(BrowserWindow.fromBrowserView(bv)).to.be.null('BrowserWindow associated with bv'); }); }); describe('BrowserWindow.setOpacity(opacity)', () => { afterEach(closeAllWindows); ifdescribe(process.platform !== 'linux')(('Windows and Mac'), () => { it('make window with initial opacity', () => { const w = new BrowserWindow({ show: false, opacity: 0.5 }); expect(w.getOpacity()).to.equal(0.5); }); it('allows setting the opacity', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setOpacity(0.0); expect(w.getOpacity()).to.equal(0.0); w.setOpacity(0.5); expect(w.getOpacity()).to.equal(0.5); w.setOpacity(1.0); expect(w.getOpacity()).to.equal(1.0); }).to.not.throw(); }); it('clamps opacity to [0.0...1.0]', () => { const w = new BrowserWindow({ show: false, opacity: 0.5 }); w.setOpacity(100); expect(w.getOpacity()).to.equal(1.0); w.setOpacity(-100); expect(w.getOpacity()).to.equal(0.0); }); }); ifdescribe(process.platform === 'linux')(('Linux'), () => { it('sets 1 regardless of parameter', () => { const w = new BrowserWindow({ show: false }); w.setOpacity(0); expect(w.getOpacity()).to.equal(1.0); w.setOpacity(0.5); expect(w.getOpacity()).to.equal(1.0); }); }); }); describe('BrowserWindow.setShape(rects)', () => { afterEach(closeAllWindows); it('allows setting shape', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setShape([]); w.setShape([{ x: 0, y: 0, width: 100, height: 100 }]); w.setShape([{ x: 0, y: 0, width: 100, height: 100 }, { x: 0, y: 200, width: 1000, height: 100 }]); w.setShape([]); }).to.not.throw(); }); }); describe('"useContentSize" option', () => { afterEach(closeAllWindows); it('make window created with content size when used', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, useContentSize: true }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); it('make window created with window size when not used', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400 }); const size = w.getSize(); expect(size).to.deep.equal([400, 400]); }); it('works for a frameless window', () => { const w = new BrowserWindow({ show: false, frame: false, width: 400, height: 400, useContentSize: true }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); const size = w.getSize(); expect(size).to.deep.equal([400, 400]); }); }); ifdescribe(process.platform === 'win32' || (process.platform === 'darwin' && semver.gte(os.release(), '14.0.0')))('"titleBarStyle" option', () => { const testWindowsOverlay = async (style: any) => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: style, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: true }); const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); if (process.platform === 'darwin') { await w.loadFile(overlayHTML); } else { const overlayReady = emittedOnce(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const overlayRect = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(overlayRect.y).to.equal(0); if (process.platform === 'darwin') { expect(overlayRect.x).to.be.greaterThan(0); } else { expect(overlayRect.x).to.equal(0); } expect(overlayRect.width).to.be.greaterThan(0); expect(overlayRect.height).to.be.greaterThan(0); const cssOverlayRect = await w.webContents.executeJavaScript('getCssOverlayProperties();'); expect(cssOverlayRect).to.deep.equal(overlayRect); const geometryChange = emittedOnce(ipcMain, 'geometrychange'); w.setBounds({ width: 800 }); const [, newOverlayRect] = await geometryChange; expect(newOverlayRect.width).to.equal(overlayRect.width + 400); }; afterEach(closeAllWindows); afterEach(() => { ipcMain.removeAllListeners('geometrychange'); }); it('creates browser window with hidden title bar', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden' }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); ifit(process.platform === 'darwin')('creates browser window with hidden inset title bar', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hiddenInset' }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); it('sets Window Control Overlay with hidden title bar', async () => { await testWindowsOverlay('hidden'); }); ifit(process.platform === 'darwin')('sets Window Control Overlay with hidden inset title bar', async () => { await testWindowsOverlay('hiddenInset'); }); }); ifdescribe(process.platform === 'win32' || (process.platform === 'darwin' && semver.gte(os.release(), '14.0.0')))('"titleBarOverlay" option', () => { const testWindowsOverlayHeight = async (size: any) => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden', webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { height: size } }); const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); if (process.platform === 'darwin') { await w.loadFile(overlayHTML); } else { const overlayReady = emittedOnce(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const overlayRectPreMax = await w.webContents.executeJavaScript('getJSOverlayProperties()'); await w.maximize(); const max = await w.isMaximized(); expect(max).to.equal(true); const overlayRectPostMax = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(overlayRectPreMax.y).to.equal(0); if (process.platform === 'darwin') { expect(overlayRectPreMax.x).to.be.greaterThan(0); } else { expect(overlayRectPreMax.x).to.equal(0); } expect(overlayRectPreMax.width).to.be.greaterThan(0); expect(overlayRectPreMax.height).to.equal(size); // Confirm that maximization only affected the height of the buttons and not the title bar expect(overlayRectPostMax.height).to.equal(size); }; afterEach(closeAllWindows); afterEach(() => { ipcMain.removeAllListeners('geometrychange'); }); it('sets Window Control Overlay with title bar height of 40', async () => { await testWindowsOverlayHeight(40); }); }); ifdescribe(process.platform === 'darwin')('"enableLargerThanScreen" option', () => { afterEach(closeAllWindows); it('can move the window out of screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); w.setPosition(-10, 50); const after = w.getPosition(); expect(after).to.deep.equal([-10, 50]); }); it('cannot move the window behind menu bar', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[1]).to.be.at.least(0); }); it('can move the window behind menu bar if it has no frame', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true, frame: false }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[0]).to.be.equal(-10); expect(after[1]).to.be.equal(-10); }); it('without it, cannot move the window out of screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: false }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[1]).to.be.at.least(0); }); it('can set the window larger than screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); const size = screen.getPrimaryDisplay().size; size.width += 100; size.height += 100; w.setSize(size.width, size.height); expectBoundsEqual(w.getSize(), [size.width, size.height]); }); it('without it, cannot set the window larger than screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: false }); const size = screen.getPrimaryDisplay().size; size.width += 100; size.height += 100; w.setSize(size.width, size.height); expect(w.getSize()[1]).to.at.most(screen.getPrimaryDisplay().size.height); }); }); ifdescribe(process.platform === 'darwin')('"zoomToPageWidth" option', () => { afterEach(closeAllWindows); it('sets the window width to the page width when used', () => { const w = new BrowserWindow({ show: false, width: 500, height: 400, zoomToPageWidth: true }); w.maximize(); expect(w.getSize()[0]).to.equal(500); }); }); describe('"tabbingIdentifier" option', () => { afterEach(closeAllWindows); it('can be set on a window', () => { expect(() => { /* eslint-disable no-new */ new BrowserWindow({ tabbingIdentifier: 'group1' }); new BrowserWindow({ tabbingIdentifier: 'group2', frame: false }); /* eslint-enable no-new */ }).not.to.throw(); }); }); describe('"webPreferences" option', () => { afterEach(() => { ipcMain.removeAllListeners('answer'); }); afterEach(closeAllWindows); describe('"preload" option', () => { const doesNotLeakSpec = (name: string, webPrefs: { nodeIntegration: boolean, sandbox: boolean, contextIsolation: boolean }) => { it(name, async () => { const w = new BrowserWindow({ webPreferences: { ...webPrefs, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'no-leak.html')); const [, result] = await emittedOnce(ipcMain, 'leak-result'); expect(result).to.have.property('require', 'undefined'); expect(result).to.have.property('exports', 'undefined'); expect(result).to.have.property('windowExports', 'undefined'); expect(result).to.have.property('windowPreload', 'undefined'); expect(result).to.have.property('windowRequire', 'undefined'); }); }; doesNotLeakSpec('does not leak require', { nodeIntegration: false, sandbox: false, contextIsolation: false }); doesNotLeakSpec('does not leak require when sandbox is enabled', { nodeIntegration: false, sandbox: true, contextIsolation: false }); doesNotLeakSpec('does not leak require when context isolation is enabled', { nodeIntegration: false, sandbox: false, contextIsolation: true }); doesNotLeakSpec('does not leak require when context isolation and sandbox are enabled', { nodeIntegration: false, sandbox: true, contextIsolation: true }); it('does not leak any node globals on the window object with nodeIntegration is disabled', async () => { let w = new BrowserWindow({ webPreferences: { contextIsolation: false, nodeIntegration: false, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'globals.html')); const [, notIsolated] = await emittedOnce(ipcMain, 'leak-result'); expect(notIsolated).to.have.property('globals'); w.destroy(); w = new BrowserWindow({ webPreferences: { contextIsolation: true, nodeIntegration: false, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'globals.html')); const [, isolated] = await emittedOnce(ipcMain, 'leak-result'); expect(isolated).to.have.property('globals'); const notIsolatedGlobals = new Set(notIsolated.globals); for (const isolatedGlobal of isolated.globals) { notIsolatedGlobals.delete(isolatedGlobal); } expect([...notIsolatedGlobals]).to.deep.equal([], 'non-isoalted renderer should have no additional globals'); }); it('loads the script before other scripts in window', async () => { const preload = path.join(fixtures, 'module', 'set-global.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false, preload } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test).to.eql('preload'); }); it('has synchronous access to all eventual window APIs', async () => { const preload = path.join(fixtures, 'module', 'access-blink-apis.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false, preload } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test).to.be.an('object'); expect(test.atPreload).to.be.an('array'); expect(test.atLoad).to.be.an('array'); expect(test.atPreload).to.deep.equal(test.atLoad, 'should have access to the same window APIs'); }); }); describe('session preload scripts', function () { const preloads = [ path.join(fixtures, 'module', 'set-global-preload-1.js'), path.join(fixtures, 'module', 'set-global-preload-2.js'), path.relative(process.cwd(), path.join(fixtures, 'module', 'set-global-preload-3.js')) ]; const defaultSession = session.defaultSession; beforeEach(() => { expect(defaultSession.getPreloads()).to.deep.equal([]); defaultSession.setPreloads(preloads); }); afterEach(() => { defaultSession.setPreloads([]); }); it('can set multiple session preload script', () => { expect(defaultSession.getPreloads()).to.deep.equal(preloads); }); const generateSpecs = (description: string, sandbox: boolean) => { describe(description, () => { it('loads the script before other scripts in window including normal preloads', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox, preload: path.join(fixtures, 'module', 'get-global-preload.js'), contextIsolation: false } }); w.loadURL('about:blank'); const [, preload1, preload2, preload3] = await emittedOnce(ipcMain, 'vars'); expect(preload1).to.equal('preload-1'); expect(preload2).to.equal('preload-1-2'); expect(preload3).to.be.undefined('preload 3'); }); }); }; generateSpecs('without sandbox', false); generateSpecs('with sandbox', true); }); describe('"additionalArguments" option', () => { it('adds extra args to process.argv in the renderer process', async () => { const preload = path.join(fixtures, 'module', 'check-arguments.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, preload, additionalArguments: ['--my-magic-arg'] } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, argv] = await emittedOnce(ipcMain, 'answer'); expect(argv).to.include('--my-magic-arg'); }); it('adds extra value args to process.argv in the renderer process', async () => { const preload = path.join(fixtures, 'module', 'check-arguments.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, preload, additionalArguments: ['--my-magic-arg=foo'] } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, argv] = await emittedOnce(ipcMain, 'answer'); expect(argv).to.include('--my-magic-arg=foo'); }); }); describe('"node-integration" option', () => { it('disables node integration by default', async () => { const preload = path.join(fixtures, 'module', 'send-later.js'); const w = new BrowserWindow({ show: false, webPreferences: { preload, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, typeofProcess, typeofBuffer] = await emittedOnce(ipcMain, 'answer'); expect(typeofProcess).to.equal('undefined'); expect(typeofBuffer).to.equal('undefined'); }); }); describe('"sandbox" option', () => { const preload = path.join(path.resolve(__dirname, 'fixtures'), 'module', 'preload-sandbox.js'); let server: http.Server = null as unknown as http.Server; let serverUrl: string = null as unknown as string; before((done) => { server = http.createServer((request, response) => { switch (request.url) { case '/cross-site': response.end(`<html><body><h1>${request.url}</h1></body></html>`); break; default: throw new Error(`unsupported endpoint: ${request.url}`); } }).listen(0, '127.0.0.1', () => { serverUrl = 'http://127.0.0.1:' + (server.address() as AddressInfo).port; done(); }); }); after(() => { server.close(); }); it('exposes ipcRenderer to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test).to.equal('preload'); }); it('exposes ipcRenderer to preload script (path has special chars)', async () => { const preloadSpecialChars = path.join(fixtures, 'module', 'preload-sandboxæø åü.js'); const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload: preloadSpecialChars, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test).to.equal('preload'); }); it('exposes "loaded" event to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload } }); w.loadURL('about:blank'); await emittedOnce(ipcMain, 'process-loaded'); }); it('exposes "exit" event to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?exit-event'); const pageUrl = 'file://' + htmlPath; w.loadURL(pageUrl); const [, url] = await emittedOnce(ipcMain, 'answer'); const expectedUrl = process.platform === 'win32' ? 'file:///' + htmlPath.replace(/\\/g, '/') : pageUrl; expect(url).to.equal(expectedUrl); }); it('should open windows in same domain with cross-scripting enabled', async () => { const w = new BrowserWindow({ show: true, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload } } })); const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?window-open'); const pageUrl = 'file://' + htmlPath; const answer = emittedOnce(ipcMain, 'answer'); w.loadURL(pageUrl); const [, { url, frameName, options }] = await emittedOnce(w.webContents, 'did-create-window'); const expectedUrl = process.platform === 'win32' ? 'file:///' + htmlPath.replace(/\\/g, '/') : pageUrl; expect(url).to.equal(expectedUrl); expect(frameName).to.equal('popup!'); expect(options.width).to.equal(500); expect(options.height).to.equal(600); const [, html] = await answer; expect(html).to.equal('<h1>scripting from opener</h1>'); }); it('should open windows in another domain with cross-scripting disabled', async () => { const w = new BrowserWindow({ show: true, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload } } })); w.loadFile( path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'window-open-external' } ); // Wait for a message from the main window saying that it's ready. await emittedOnce(ipcMain, 'opener-loaded'); // Ask the opener to open a popup with window.opener. const expectedPopupUrl = `${serverUrl}/cross-site`; // Set in "sandbox.html". w.webContents.send('open-the-popup', expectedPopupUrl); // The page is going to open a popup that it won't be able to close. // We have to close it from here later. const [, popupWindow] = await emittedOnce(app, 'browser-window-created'); // Ask the popup window for details. const detailsAnswer = emittedOnce(ipcMain, 'child-loaded'); popupWindow.webContents.send('provide-details'); const [, openerIsNull, , locationHref] = await detailsAnswer; expect(openerIsNull).to.be.false('window.opener is null'); expect(locationHref).to.equal(expectedPopupUrl); // Ask the page to access the popup. const touchPopupResult = emittedOnce(ipcMain, 'answer'); w.webContents.send('touch-the-popup'); const [, popupAccessMessage] = await touchPopupResult; // Ask the popup to access the opener. const touchOpenerResult = emittedOnce(ipcMain, 'answer'); popupWindow.webContents.send('touch-the-opener'); const [, openerAccessMessage] = await touchOpenerResult; // We don't need the popup anymore, and its parent page can't close it, // so let's close it from here before we run any checks. await closeWindow(popupWindow, { assertNotWindows: false }); expect(popupAccessMessage).to.be.a('string', 'child\'s .document is accessible from its parent window'); expect(popupAccessMessage).to.match(/^Blocked a frame with origin/); expect(openerAccessMessage).to.be.a('string', 'opener .document is accessible from a popup window'); expect(openerAccessMessage).to.match(/^Blocked a frame with origin/); }); it('should inherit the sandbox setting in opened windows', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [, { argv }] = await emittedOnce(ipcMain, 'answer'); expect(argv).to.include('--enable-sandbox'); }); it('should open windows with the options configured via new-window event listeners', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath, contextIsolation: false } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [[, childWebContents]] = await Promise.all([ emittedOnce(app, 'web-contents-created'), emittedOnce(ipcMain, 'answer') ]); const webPreferences = childWebContents.getLastWebPreferences(); expect(webPreferences.contextIsolation).to.equal(false); }); it('should set ipc event sender correctly', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); let childWc: WebContents | null = null; w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload, contextIsolation: false } } })); w.webContents.on('did-create-window', (win) => { childWc = win.webContents; expect(w.webContents).to.not.equal(childWc); }); ipcMain.once('parent-ready', function (event) { expect(event.sender).to.equal(w.webContents, 'sender should be the parent'); event.sender.send('verified'); }); ipcMain.once('child-ready', function (event) { expect(childWc).to.not.be.null('child webcontents should be available'); expect(event.sender).to.equal(childWc, 'sender should be the child'); event.sender.send('verified'); }); const done = Promise.all([ 'parent-answer', 'child-answer' ].map(name => emittedOnce(ipcMain, name))); w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'verify-ipc-sender' }); await done; }); describe('event handling', () => { let w: BrowserWindow = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); }); it('works for window events', async () => { const pageTitleUpdated = emittedOnce(w, 'page-title-updated'); w.loadURL('data:text/html,<script>document.title = \'changed\'</script>'); await pageTitleUpdated; }); it('works for stop events', async () => { const done = Promise.all([ 'did-navigate', 'did-fail-load', 'did-stop-loading' ].map(name => emittedOnce(w.webContents, name))); w.loadURL('data:text/html,<script>stop()</script>'); await done; }); it('works for web contents events', async () => { const done = Promise.all([ 'did-finish-load', 'did-frame-finish-load', 'did-navigate-in-page', 'will-navigate', 'did-start-loading', 'did-stop-loading', 'did-frame-finish-load', 'dom-ready' ].map(name => emittedOnce(w.webContents, name))); w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'webcontents-events' }); await done; }); }); it('supports calling preventDefault on new-window events', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const initialWebContents = webContents.getAllWebContents().map((i) => i.id); w.webContents.once('new-window', (e) => { e.preventDefault(); // We need to give it some time so the windows get properly disposed (at least on OSX). setTimeout(() => { const currentWebContents = webContents.getAllWebContents().map((i) => i.id); try { expect(currentWebContents).to.deep.equal(initialWebContents); done(); } catch (error) { done(e); } }, 100); }); w.loadFile(path.join(fixtures, 'pages', 'window-open.html')); }); it('validates process APIs access in sandboxed renderer', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.once('preload-error', (event, preloadPath, error) => { throw error; }); process.env.sandboxmain = 'foo'; w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test.hasCrash).to.be.true('has crash'); expect(test.hasHang).to.be.true('has hang'); expect(test.heapStatistics).to.be.an('object'); expect(test.blinkMemoryInfo).to.be.an('object'); expect(test.processMemoryInfo).to.be.an('object'); expect(test.systemVersion).to.be.a('string'); expect(test.cpuUsage).to.be.an('object'); expect(test.ioCounters).to.be.an('object'); expect(test.uptime).to.be.a('number'); expect(test.arch).to.equal(process.arch); expect(test.platform).to.equal(process.platform); expect(test.env).to.deep.equal(process.env); expect(test.execPath).to.equal(process.helperExecPath); expect(test.sandboxed).to.be.true('sandboxed'); expect(test.contextIsolated).to.be.false('contextIsolated'); expect(test.type).to.equal('renderer'); expect(test.version).to.equal(process.version); expect(test.versions).to.deep.equal(process.versions); expect(test.contextId).to.be.a('string'); if (process.platform === 'linux' && test.osSandbox) { expect(test.creationTime).to.be.null('creation time'); expect(test.systemMemoryInfo).to.be.null('system memory info'); } else { expect(test.creationTime).to.be.a('number'); expect(test.systemMemoryInfo).to.be.an('object'); } }); it('webview in sandbox renderer', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, webviewTag: true, contextIsolation: false } }); const didAttachWebview = emittedOnce(w.webContents, 'did-attach-webview'); const webviewDomReady = emittedOnce(ipcMain, 'webview-dom-ready'); w.loadFile(path.join(fixtures, 'pages', 'webview-did-attach-event.html')); const [, webContents] = await didAttachWebview; const [, id] = await webviewDomReady; expect(webContents.id).to.equal(id); }); }); describe('child windows', () => { let w: BrowserWindow = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, // tests relies on preloads in opened windows nodeIntegrationInSubFrames: true, contextIsolation: false } }); }); it('opens window of about:blank with cross-scripting enabled', async () => { const answer = emittedOnce(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-blank.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('opens window of same domain with cross-scripting enabled', async () => { const answer = emittedOnce(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-file.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('blocks accessing cross-origin frames', async () => { const answer = emittedOnce(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-cross-origin.html')); const [, content] = await answer; expect(content).to.equal('Blocked a frame with origin "file://" from accessing a cross-origin frame.'); }); it('opens window from <iframe> tags', async () => { const answer = emittedOnce(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-iframe.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('opens window with cross-scripting enabled from isolated context', async () => { const w = new BrowserWindow({ show: false, webPreferences: { preload: path.join(fixtures, 'api', 'native-window-open-isolated-preload.js') } }); w.loadFile(path.join(fixtures, 'api', 'native-window-open-isolated.html')); const [, content] = await emittedOnce(ipcMain, 'answer'); expect(content).to.equal('Hello'); }); ifit(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('loads native addons correctly after reload', async () => { w.loadFile(path.join(__dirname, 'fixtures', 'api', 'native-window-open-native-addon.html')); { const [, content] = await emittedOnce(ipcMain, 'answer'); expect(content).to.equal('function'); } w.reload(); { const [, content] = await emittedOnce(ipcMain, 'answer'); expect(content).to.equal('function'); } }); it('<webview> works in a scriptable popup', async () => { const preload = path.join(fixtures, 'api', 'new-window-webview-preload.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegrationInSubFrames: true, webviewTag: true, contextIsolation: false, preload } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { show: false, webPreferences: { contextIsolation: false, webviewTag: true, nodeIntegrationInSubFrames: true } } })); w.webContents.once('new-window', (event, url, frameName, disposition, options) => { options.show = false; }); const webviewLoaded = emittedOnce(ipcMain, 'webview-loaded'); w.loadFile(path.join(fixtures, 'api', 'new-window-webview.html')); await webviewLoaded; }); it('should open windows with the options configured via new-window event listeners', async () => { const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath, contextIsolation: false } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [[, childWebContents]] = await Promise.all([ emittedOnce(app, 'web-contents-created'), emittedOnce(ipcMain, 'answer') ]); const webPreferences = childWebContents.getLastWebPreferences(); expect(webPreferences.contextIsolation).to.equal(false); }); describe('window.location', () => { const protocols = [ ['foo', path.join(fixtures, 'api', 'window-open-location-change.html')], ['bar', path.join(fixtures, 'api', 'window-open-location-final.html')] ]; beforeEach(() => { for (const [scheme, path] of protocols) { protocol.registerBufferProtocol(scheme, (request, callback) => { callback({ mimeType: 'text/html', data: fs.readFileSync(path) }); }); } }); afterEach(() => { for (const [scheme] of protocols) { protocol.unregisterProtocol(scheme); } }); it('retains the original web preferences when window.location is changed to a new origin', async () => { const w = new BrowserWindow({ show: false, webPreferences: { // test relies on preloads in opened window nodeIntegrationInSubFrames: true, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: path.join(mainFixtures, 'api', 'window-open-preload.js'), contextIsolation: false, nodeIntegrationInSubFrames: true } } })); w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html')); const [, { nodeIntegration, typeofProcess }] = await emittedOnce(ipcMain, 'answer'); expect(nodeIntegration).to.be.false(); expect(typeofProcess).to.eql('undefined'); }); it('window.opener is not null when window.location is changed to a new origin', async () => { const w = new BrowserWindow({ show: false, webPreferences: { // test relies on preloads in opened window nodeIntegrationInSubFrames: true } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: path.join(mainFixtures, 'api', 'window-open-preload.js') } } })); w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html')); const [, { windowOpenerIsNull }] = await emittedOnce(ipcMain, 'answer'); expect(windowOpenerIsNull).to.be.false('window.opener is null'); }); }); }); describe('"disableHtmlFullscreenWindowResize" option', () => { it('prevents window from resizing when set', async () => { const w = new BrowserWindow({ show: false, webPreferences: { disableHtmlFullscreenWindowResize: true } }); await w.loadURL('about:blank'); const size = w.getSize(); const enterHtmlFullScreen = emittedOnce(w.webContents, 'enter-html-full-screen'); w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true); await enterHtmlFullScreen; expect(w.getSize()).to.deep.equal(size); }); }); }); describe('beforeunload handler', function () { let w: BrowserWindow = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(closeAllWindows); it('returning undefined would not prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html')); const wait = emittedOnce(w, 'closed'); w.close(); await wait; }); it('returning false would prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); const [, proceed] = await emittedOnce(w.webContents, 'before-unload-fired'); expect(proceed).to.equal(false); }); it('returning empty string would prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-empty-string.html')); w.close(); const [, proceed] = await emittedOnce(w.webContents, 'before-unload-fired'); expect(proceed).to.equal(false); }); it('emits for each close attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const destroyListener = () => { expect.fail('Close was not prevented'); }; w.webContents.once('destroyed', destroyListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await emittedOnce(w.webContents, 'console-message'); w.close(); await emittedOnce(w.webContents, 'before-unload-fired'); w.close(); await emittedOnce(w.webContents, 'before-unload-fired'); w.webContents.removeListener('destroyed', destroyListener); const wait = emittedOnce(w, 'closed'); w.close(); await wait; }); it('emits for each reload attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const navigationListener = () => { expect.fail('Reload was not prevented'); }; w.webContents.once('did-start-navigation', navigationListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await emittedOnce(w.webContents, 'console-message'); w.reload(); // Chromium does not emit 'before-unload-fired' on WebContents for // navigations, so we have to use other ways to know if beforeunload // is fired. await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.reload(); await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.webContents.removeListener('did-start-navigation', navigationListener); w.reload(); await emittedOnce(w.webContents, 'did-finish-load'); }); it('emits for each navigation attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const navigationListener = () => { expect.fail('Reload was not prevented'); }; w.webContents.once('did-start-navigation', navigationListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await emittedOnce(w.webContents, 'console-message'); w.loadURL('about:blank'); // Chromium does not emit 'before-unload-fired' on WebContents for // navigations, so we have to use other ways to know if beforeunload // is fired. await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.loadURL('about:blank'); await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.webContents.removeListener('did-start-navigation', navigationListener); await w.loadURL('about:blank'); }); }); describe('document.visibilityState/hidden', () => { afterEach(closeAllWindows); it('visibilityState is initially visible despite window being hidden', async () => { const w = new BrowserWindow({ show: false, width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); let readyToShow = false; w.once('ready-to-show', () => { readyToShow = true; }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(readyToShow).to.be.false('ready to show'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform !== 'win32')('visibilityState changes when window is hidden', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.hide(); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform !== 'win32')('visibilityState changes when window is shown', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); if (process.platform === 'darwin') { // See https://github.com/electron/electron/issues/8664 await emittedOnce(w, 'show'); } w.hide(); w.show(); const [, visibilityState] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); }); ifit(process.platform !== 'win32')('visibilityState changes when window is shown inactive', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); if (process.platform === 'darwin') { // See https://github.com/electron/electron/issues/8664 await emittedOnce(w, 'show'); } w.hide(); w.showInactive(); const [, visibilityState] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform === 'darwin')('visibilityState changes when window is minimized', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.minimize(); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } }); // FIXME(MarshallOfSound): This test fails locally 100% of the time, on CI it started failing // when we introduced the compositor recycling patch. Should figure out how to fix this it.skip('visibilityState remains visible if backgroundThrottling is disabled', async () => { const w = new BrowserWindow({ show: false, width: 100, height: 100, webPreferences: { backgroundThrottling: false, nodeIntegration: true } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } ipcMain.once('pong', (event, visibilityState, hidden) => { throw new Error(`Unexpected visibility change event. visibilityState: ${visibilityState} hidden: ${hidden}`); }); try { const shown1 = emittedOnce(w, 'show'); w.show(); await shown1; const hidden = emittedOnce(w, 'hide'); w.hide(); await hidden; const shown2 = emittedOnce(w, 'show'); w.show(); await shown2; } finally { ipcMain.removeAllListeners('pong'); } }); }); describe('new-window event', () => { afterEach(closeAllWindows); it('emits when window.open is called', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); w.webContents.once('new-window', (e, url, frameName, disposition, options) => { e.preventDefault(); try { expect(url).to.equal('http://host/'); expect(frameName).to.equal('host'); expect((options as any)['this-is-not-a-standard-feature']).to.equal(true); done(); } catch (e) { done(e); } }); w.loadFile(path.join(fixtures, 'pages', 'window-open.html')); }); it('emits when window.open is called with no webPreferences', (done) => { const w = new BrowserWindow({ show: false }); w.webContents.once('new-window', function (e, url, frameName, disposition, options) { e.preventDefault(); try { expect(url).to.equal('http://host/'); expect(frameName).to.equal('host'); expect((options as any)['this-is-not-a-standard-feature']).to.equal(true); done(); } catch (e) { done(e); } }); w.loadFile(path.join(fixtures, 'pages', 'window-open.html')); }); it('emits when link with target is called', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); w.webContents.once('new-window', (e, url, frameName) => { e.preventDefault(); try { expect(url).to.equal('http://host/'); expect(frameName).to.equal('target'); done(); } catch (e) { done(e); } }); w.loadFile(path.join(fixtures, 'pages', 'target-name.html')); }); it('includes all properties', async () => { const w = new BrowserWindow({ show: false }); const p = new Promise<{ url: string, frameName: string, disposition: string, options: BrowserWindowConstructorOptions, additionalFeatures: string[], referrer: Electron.Referrer, postBody: Electron.PostBody }>((resolve) => { w.webContents.once('new-window', (e, url, frameName, disposition, options, additionalFeatures, referrer, postBody) => { e.preventDefault(); resolve({ url, frameName, disposition, options, additionalFeatures, referrer, postBody }); }); }); w.loadURL(`data:text/html,${encodeURIComponent(` <form target="_blank" method="POST" id="form" action="http://example.com/test"> <input type="text" name="post-test-key" value="post-test-value"></input> </form> <script>form.submit()</script> `)}`); const { url, frameName, disposition, options, additionalFeatures, referrer, postBody } = await p; expect(url).to.equal('http://example.com/test'); expect(frameName).to.equal(''); expect(disposition).to.equal('foreground-tab'); expect(options).to.be.an('object').not.null(); expect(referrer.policy).to.equal('strict-origin-when-cross-origin'); expect(referrer.url).to.equal(''); expect(additionalFeatures).to.deep.equal([]); expect(postBody.data).to.have.length(1); expect(postBody.data[0].type).to.equal('rawData'); expect((postBody.data[0] as any).bytes).to.deep.equal(Buffer.from('post-test-key=post-test-value')); expect(postBody.contentType).to.equal('application/x-www-form-urlencoded'); }); }); ifdescribe(process.platform !== 'linux')('max/minimize events', () => { afterEach(closeAllWindows); it('emits an event when window is maximized', async () => { const w = new BrowserWindow({ show: false }); const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; }); it('emits an event when a transparent window is maximized', async () => { const w = new BrowserWindow({ show: false, frame: false, transparent: true }); const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; }); it('emits only one event when frameless window is maximized', () => { const w = new BrowserWindow({ show: false, frame: false }); let emitted = 0; w.on('maximize', () => emitted++); w.show(); w.maximize(); expect(emitted).to.equal(1); }); it('emits an event when window is unmaximized', async () => { const w = new BrowserWindow({ show: false }); const unmaximize = emittedOnce(w, 'unmaximize'); w.show(); w.maximize(); w.unmaximize(); await unmaximize; }); it('emits an event when a transparent window is unmaximized', async () => { const w = new BrowserWindow({ show: false, frame: false, transparent: true }); const maximize = emittedOnce(w, 'maximize'); const unmaximize = emittedOnce(w, 'unmaximize'); w.show(); w.maximize(); await maximize; w.unmaximize(); await unmaximize; }); it('emits an event when window is minimized', async () => { const w = new BrowserWindow({ show: false }); const minimize = emittedOnce(w, 'minimize'); w.show(); w.minimize(); await minimize; }); }); describe('beginFrameSubscription method', () => { it('does not crash when callback returns nothing', (done) => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); w.webContents.on('dom-ready', () => { w.webContents.beginFrameSubscription(function () { // Pending endFrameSubscription to next tick can reliably reproduce // a crash which happens when nothing is returned in the callback. setTimeout(() => { w.webContents.endFrameSubscription(); done(); }); }); }); }); it('subscribes to frame updates', (done) => { const w = new BrowserWindow({ show: false }); let called = false; w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); w.webContents.on('dom-ready', () => { w.webContents.beginFrameSubscription(function (data) { // This callback might be called twice. if (called) return; called = true; try { expect(data.constructor.name).to.equal('NativeImage'); expect(data.isEmpty()).to.be.false('data is empty'); done(); } catch (e) { done(e); } finally { w.webContents.endFrameSubscription(); } }); }); }); it('subscribes to frame updates (only dirty rectangle)', (done) => { const w = new BrowserWindow({ show: false }); let called = false; let gotInitialFullSizeFrame = false; const [contentWidth, contentHeight] = w.getContentSize(); w.webContents.on('did-finish-load', () => { w.webContents.beginFrameSubscription(true, (image, rect) => { if (image.isEmpty()) { // Chromium sometimes sends a 0x0 frame at the beginning of the // page load. return; } if (rect.height === contentHeight && rect.width === contentWidth && !gotInitialFullSizeFrame) { // The initial frame is full-size, but we're looking for a call // with just the dirty-rect. The next frame should be a smaller // rect. gotInitialFullSizeFrame = true; return; } // This callback might be called twice. if (called) return; // We asked for just the dirty rectangle, so we expect to receive a // rect smaller than the full size. // TODO(jeremy): this is failing on windows currently; investigate. // assert(rect.width < contentWidth || rect.height < contentHeight) called = true; try { const expectedSize = rect.width * rect.height * 4; expect(image.getBitmap()).to.be.an.instanceOf(Buffer).with.lengthOf(expectedSize); done(); } catch (e) { done(e); } finally { w.webContents.endFrameSubscription(); } }); }); w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); }); it('throws error when subscriber is not well defined', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.webContents.beginFrameSubscription(true, true as any); // TODO(zcbenz): gin is weak at guessing parameter types, we should // upstream native_mate's implementation to gin. }).to.throw('Error processing argument at index 1, conversion failure from '); }); }); describe('savePage method', () => { const savePageDir = path.join(fixtures, 'save_page'); const savePageHtmlPath = path.join(savePageDir, 'save_page.html'); const savePageJsPath = path.join(savePageDir, 'save_page_files', 'test.js'); const savePageCssPath = path.join(savePageDir, 'save_page_files', 'test.css'); afterEach(() => { closeAllWindows(); try { fs.unlinkSync(savePageCssPath); fs.unlinkSync(savePageJsPath); fs.unlinkSync(savePageHtmlPath); fs.rmdirSync(path.join(savePageDir, 'save_page_files')); fs.rmdirSync(savePageDir); } catch {} }); it('should throw when passing relative paths', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await expect( w.webContents.savePage('save_page.html', 'HTMLComplete') ).to.eventually.be.rejectedWith('Path must be absolute'); await expect( w.webContents.savePage('save_page.html', 'HTMLOnly') ).to.eventually.be.rejectedWith('Path must be absolute'); await expect( w.webContents.savePage('save_page.html', 'MHTML') ).to.eventually.be.rejectedWith('Path must be absolute'); }); it('should save page to disk with HTMLOnly', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'HTMLOnly'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.false('js path'); expect(fs.existsSync(savePageCssPath)).to.be.false('css path'); }); it('should save page to disk with MHTML', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'MHTML'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.false('js path'); expect(fs.existsSync(savePageCssPath)).to.be.false('css path'); }); it('should save page to disk with HTMLComplete', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'HTMLComplete'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.true('js path'); expect(fs.existsSync(savePageCssPath)).to.be.true('css path'); }); }); describe('BrowserWindow options argument is optional', () => { afterEach(closeAllWindows); it('should create a window with default size (800x600)', () => { const w = new BrowserWindow(); expect(w.getSize()).to.deep.equal([800, 600]); }); }); describe('BrowserWindow.restore()', () => { afterEach(closeAllWindows); it('should restore the previous window size', () => { const w = new BrowserWindow({ minWidth: 800, width: 800 }); const initialSize = w.getSize(); w.minimize(); w.restore(); expectBoundsEqual(w.getSize(), initialSize); }); it('does not crash when restoring hidden minimized window', () => { const w = new BrowserWindow({}); w.minimize(); w.hide(); w.show(); }); }); // 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 = emittedOnce(w, 'hide'); let shown = emittedOnce(w, 'show'); const maximize = emittedOnce(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 = emittedOnce(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 = emittedOnce(w, 'minimize'); w.minimize(); await minimize; w.unmaximize(); await delay(1000); expect(w.isMinimized()).to.be.true(); }); it('should not change the size or position of a normal window', async () => { const w = new BrowserWindow(); const initialSize = w.getSize(); const initialPosition = w.getPosition(); w.unmaximize(); await delay(1000); expectBoundsEqual(w.getSize(), initialSize); expectBoundsEqual(w.getPosition(), initialPosition); }); 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 delay(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 = emittedOnce(w, 'show'); // start fullscreen and hidden w.setFullScreen(true); w.show(); await shown; const leftFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leftFullScreen; expect(w.isVisible()).to.be.true('visible'); expect(w.isFullScreen()).to.be.false('fullscreen'); }); it('should keep window hidden if already in hidden state', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const leftFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leftFullScreen; expect(w.isVisible()).to.be.false('visible'); expect(w.isFullScreen()).to.be.false('fullscreen'); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setFullScreen(false) when HTML fullscreen', () => { it('exits HTML fullscreen when window leaves fullscreen', async () => { const w = new BrowserWindow(); await w.loadURL('about:blank'); await w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true); await emittedOnce(w, 'enter-full-screen'); // Wait a tick for the full-screen state to 'stick' await delay(); w.setFullScreen(false); await emittedOnce(w, 'leave-html-full-screen'); }); }); }); describe('parent window', () => { afterEach(closeAllWindows); ifit(process.platform === 'darwin')('sheet-begin event emits when window opens a sheet', async () => { const w = new BrowserWindow(); const sheetBegin = emittedOnce(w, 'sheet-begin'); // eslint-disable-next-line no-new new BrowserWindow({ modal: true, parent: w }); await sheetBegin; }); ifit(process.platform === 'darwin')('sheet-end event emits when window has closed a sheet', async () => { const w = new BrowserWindow(); const sheet = new BrowserWindow({ modal: true, parent: w }); const sheetEnd = emittedOnce(w, 'sheet-end'); sheet.close(); await sheetEnd; }); describe('parent option', () => { it('sets parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(c.getParentWindow()).to.equal(w); }); it('adds window to child windows of parent', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(w.getChildWindows()).to.deep.equal([c]); }); it('removes from child windows of parent when window is closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); const closed = emittedOnce(c, 'closed'); c.close(); await closed; // The child window list is not immediately cleared, so wait a tick until it's ready. await delay(); expect(w.getChildWindows().length).to.equal(0); }); it('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 delay(); 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 = emittedOnce(c, 'closed'); c.setParentWindow(w); c.close(); await closed; // The child window list is not immediately cleared, so wait a tick until it's ready. await delay(); expect(w.getChildWindows().length).to.equal(0); }); }); describe('modal option', () => { it('does not freeze or crash', async () => { const parentWindow = new BrowserWindow(); const createTwo = async () => { const two = new BrowserWindow({ width: 300, height: 200, parent: parentWindow, modal: true, show: false }); const twoShown = emittedOnce(two, 'show'); two.show(); await twoShown; setTimeout(() => two.close(), 500); await emittedOnce(two, 'closed'); }; const one = new BrowserWindow({ width: 600, height: 400, parent: parentWindow, modal: true, show: false }); const oneShown = emittedOnce(one, 'show'); one.show(); await oneShown; setTimeout(() => one.destroy(), 500); await emittedOnce(one, 'closed'); await createTwo(); }); ifit(process.platform !== 'darwin')('disables parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); expect(w.isEnabled()).to.be.true('w.isEnabled'); c.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); }); ifit(process.platform !== 'darwin')('re-enables an enabled parent window when closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const closed = emittedOnce(c, 'closed'); c.show(); c.close(); await closed; expect(w.isEnabled()).to.be.true('w.isEnabled'); }); ifit(process.platform !== 'darwin')('does not re-enable a disabled parent window when closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const closed = emittedOnce(c, 'closed'); w.setEnabled(false); c.show(); c.close(); await closed; expect(w.isEnabled()).to.be.false('w.isEnabled'); }); ifit(process.platform !== 'darwin')('disables parent window recursively', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const c2 = new BrowserWindow({ show: false, parent: w, modal: true }); c.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c2.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c.destroy(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c2.destroy(); expect(w.isEnabled()).to.be.true('w.isEnabled'); }); }); }); describe('window states', () => { afterEach(closeAllWindows); it('does not resize frameless windows when states change', () => { const w = new BrowserWindow({ frame: false, width: 300, height: 200, show: false }); w.minimizable = false; w.minimizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.resizable = false; w.resizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.maximizable = false; w.maximizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.fullScreenable = false; w.fullScreenable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.closable = false; w.closable = true; expect(w.getSize()).to.deep.equal([300, 200]); }); describe('resizable state', () => { it('with properties', () => { it('can be set with resizable constructor option', () => { const w = new BrowserWindow({ show: false, resizable: false }); expect(w.resizable).to.be.false('resizable'); if (process.platform === 'darwin') { expect(w.maximizable).to.to.true('maximizable'); } }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.resizable).to.be.true('resizable'); w.resizable = false; expect(w.resizable).to.be.false('resizable'); w.resizable = true; expect(w.resizable).to.be.true('resizable'); }); }); it('with functions', () => { it('can be set with resizable constructor option', () => { const w = new BrowserWindow({ show: false, resizable: false }); expect(w.isResizable()).to.be.false('resizable'); if (process.platform === 'darwin') { expect(w.isMaximizable()).to.to.true('maximizable'); } }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isResizable()).to.be.true('resizable'); w.setResizable(false); expect(w.isResizable()).to.be.false('resizable'); w.setResizable(true); expect(w.isResizable()).to.be.true('resizable'); }); }); it('works for a frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); expect(w.resizable).to.be.true('resizable'); if (process.platform === 'win32') { const w = new BrowserWindow({ show: false, thickFrame: false }); expect(w.resizable).to.be.false('resizable'); } }); // On Linux there is no "resizable" property of a window. ifit(process.platform !== 'linux')('does affect maximizability when disabled and enabled', () => { const w = new BrowserWindow({ show: false }); expect(w.resizable).to.be.true('resizable'); expect(w.maximizable).to.be.true('maximizable'); w.resizable = false; expect(w.maximizable).to.be.false('not maximizable'); w.resizable = true; expect(w.maximizable).to.be.true('maximizable'); }); ifit(process.platform === 'win32')('works for a window smaller than 64x64', () => { const w = new BrowserWindow({ show: false, frame: false, resizable: false, transparent: true }); w.setContentSize(60, 60); expectBoundsEqual(w.getContentSize(), [60, 60]); w.setContentSize(30, 30); expectBoundsEqual(w.getContentSize(), [30, 30]); w.setContentSize(10, 10); expectBoundsEqual(w.getContentSize(), [10, 10]); }); }); describe('loading main frame state', () => { let server: http.Server = null as unknown as http.Server; let serverUrl: string = null as unknown as string; before((done) => { server = http.createServer((request, response) => { response.end(); }).listen(0, '127.0.0.1', () => { serverUrl = 'http://127.0.0.1:' + (server.address() as AddressInfo).port; done(); }); }); after(() => { server.close(); }); it('is true when the main frame is loading', async () => { const w = new BrowserWindow({ show: false }); const didStartLoading = emittedOnce(w.webContents, 'did-start-loading'); w.webContents.loadURL(serverUrl); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame'); }); it('is false when only a subframe is loading', async () => { const w = new BrowserWindow({ show: false }); const didStopLoading = emittedOnce(w.webContents, 'did-stop-loading'); w.webContents.loadURL(serverUrl); await didStopLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); const didStartLoading = emittedOnce(w.webContents, 'did-start-loading'); w.webContents.executeJavaScript(` var iframe = document.createElement('iframe') iframe.src = '${serverUrl}/page2' document.body.appendChild(iframe) `); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); }); it('is true when navigating to pages from the same origin', async () => { const w = new BrowserWindow({ show: false }); const didStopLoading = emittedOnce(w.webContents, 'did-stop-loading'); w.webContents.loadURL(serverUrl); await didStopLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); const didStartLoading = emittedOnce(w.webContents, 'did-start-loading'); w.webContents.loadURL(`${serverUrl}/page2`); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame'); }); }); }); ifdescribe(process.platform !== 'linux')('window states (excluding Linux)', () => { // Not implemented on Linux. afterEach(closeAllWindows); describe('movable state', () => { it('with properties', () => { it('can be set with movable constructor option', () => { const w = new BrowserWindow({ show: false, movable: false }); expect(w.movable).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.movable).to.be.true('movable'); w.movable = false; expect(w.movable).to.be.false('movable'); w.movable = true; expect(w.movable).to.be.true('movable'); }); }); it('with functions', () => { it('can be set with movable constructor option', () => { const w = new BrowserWindow({ show: false, movable: false }); expect(w.isMovable()).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMovable()).to.be.true('movable'); w.setMovable(false); expect(w.isMovable()).to.be.false('movable'); w.setMovable(true); expect(w.isMovable()).to.be.true('movable'); }); }); }); describe('visibleOnAllWorkspaces state', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.visibleOnAllWorkspaces).to.be.false(); w.visibleOnAllWorkspaces = true; expect(w.visibleOnAllWorkspaces).to.be.true(); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isVisibleOnAllWorkspaces()).to.be.false(); w.setVisibleOnAllWorkspaces(true); expect(w.isVisibleOnAllWorkspaces()).to.be.true(); }); }); }); ifdescribe(process.platform === 'darwin')('documentEdited state', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.documentEdited).to.be.false(); w.documentEdited = true; expect(w.documentEdited).to.be.true(); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isDocumentEdited()).to.be.false(); w.setDocumentEdited(true); expect(w.isDocumentEdited()).to.be.true(); }); }); }); ifdescribe(process.platform === 'darwin')('representedFilename', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.representedFilename).to.eql(''); w.representedFilename = 'a name'; expect(w.representedFilename).to.eql('a name'); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.getRepresentedFilename()).to.eql(''); w.setRepresentedFilename('a name'); expect(w.getRepresentedFilename()).to.eql('a name'); }); }); }); describe('native window title', () => { it('with properties', () => { it('can be set with title constructor option', () => { const w = new BrowserWindow({ show: false, title: 'mYtItLe' }); expect(w.title).to.eql('mYtItLe'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.title).to.eql('Electron Test Main'); w.title = 'NEW TITLE'; expect(w.title).to.eql('NEW TITLE'); }); }); it('with functions', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, title: 'mYtItLe' }); expect(w.getTitle()).to.eql('mYtItLe'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.getTitle()).to.eql('Electron Test Main'); w.setTitle('NEW TITLE'); expect(w.getTitle()).to.eql('NEW TITLE'); }); }); }); describe('minimizable state', () => { it('with properties', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, minimizable: false }); expect(w.minimizable).to.be.false('minimizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.minimizable).to.be.true('minimizable'); w.minimizable = false; expect(w.minimizable).to.be.false('minimizable'); w.minimizable = true; expect(w.minimizable).to.be.true('minimizable'); }); }); it('with functions', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, minimizable: false }); expect(w.isMinimizable()).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMinimizable()).to.be.true('isMinimizable'); w.setMinimizable(false); expect(w.isMinimizable()).to.be.false('isMinimizable'); w.setMinimizable(true); expect(w.isMinimizable()).to.be.true('isMinimizable'); }); }); }); describe('maximizable state (property)', () => { it('with properties', () => { it('can be set with maximizable constructor option', () => { const w = new BrowserWindow({ show: false, maximizable: false }); expect(w.maximizable).to.be.false('maximizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.maximizable).to.be.true('maximizable'); w.maximizable = false; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; expect(w.maximizable).to.be.true('maximizable'); }); it('is not affected when changing other states', () => { const w = new BrowserWindow({ show: false }); w.maximizable = false; expect(w.maximizable).to.be.false('maximizable'); w.minimizable = false; expect(w.maximizable).to.be.false('maximizable'); w.closable = false; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; expect(w.maximizable).to.be.true('maximizable'); w.closable = true; expect(w.maximizable).to.be.true('maximizable'); w.fullScreenable = false; expect(w.maximizable).to.be.true('maximizable'); }); }); it('with functions', () => { it('can be set with maximizable constructor option', () => { const w = new BrowserWindow({ show: false, maximizable: false }); expect(w.isMaximizable()).to.be.false('isMaximizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setMaximizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); it('is not affected when changing other states', () => { const w = new BrowserWindow({ show: false }); w.setMaximizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMinimizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setClosable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setClosable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setFullScreenable(false); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); }); }); ifdescribe(process.platform === 'win32')('maximizable state', () => { it('with properties', () => { it('is reset to its former state', () => { const w = new BrowserWindow({ show: false }); w.maximizable = false; w.resizable = false; w.resizable = true; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; w.resizable = false; w.resizable = true; expect(w.maximizable).to.be.true('maximizable'); }); }); it('with functions', () => { it('is reset to its former state', () => { const w = new BrowserWindow({ show: false }); w.setMaximizable(false); w.setResizable(false); w.setResizable(true); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); w.setResizable(false); w.setResizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); }); }); ifdescribe(process.platform !== 'darwin')('menuBarVisible state', () => { describe('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.menuBarVisible).to.be.true(); w.menuBarVisible = false; expect(w.menuBarVisible).to.be.false(); w.menuBarVisible = true; expect(w.menuBarVisible).to.be.true(); }); }); describe('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); w.setMenuBarVisibility(false); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); w.setMenuBarVisibility(true); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); }); }); }); ifdescribe(process.platform === 'darwin')('fullscreenable state', () => { it('with functions', () => { it('can be set with fullscreenable constructor option', () => { const w = new BrowserWindow({ show: false, fullscreenable: false }); expect(w.isFullScreenable()).to.be.false('isFullScreenable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isFullScreenable()).to.be.true('isFullScreenable'); w.setFullScreenable(false); expect(w.isFullScreenable()).to.be.false('isFullScreenable'); w.setFullScreenable(true); expect(w.isFullScreenable()).to.be.true('isFullScreenable'); }); }); }); // fullscreen events are dispatched eagerly and twiddling things too fast can confuse poor Electron ifdescribe(process.platform === 'darwin')('kiosk state', () => { it('with properties', () => { it('can be set with a constructor property', () => { const w = new BrowserWindow({ kiosk: true }); expect(w.kiosk).to.be.true(); }); it('can be changed ', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.kiosk = true; expect(w.isKiosk()).to.be.true('isKiosk'); await enterFullScreen; await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.kiosk = false; expect(w.isKiosk()).to.be.false('isKiosk'); await leaveFullScreen; }); }); it('with functions', () => { it('can be set with a constructor property', () => { const w = new BrowserWindow({ kiosk: true }); expect(w.isKiosk()).to.be.true(); }); it('can be changed ', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setKiosk(true); expect(w.isKiosk()).to.be.true('isKiosk'); await enterFullScreen; await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setKiosk(false); expect(w.isKiosk()).to.be.false('isKiosk'); await leaveFullScreen; }); }); }); ifdescribe(process.platform === 'darwin')('fullscreen state with resizable set', () => { it('resizable flag should be set to true and restored', async () => { const w = new BrowserWindow({ resizable: false }); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.resizable).to.be.true('resizable'); await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.resizable).to.be.false('resizable'); }); }); ifdescribe(process.platform === 'darwin')('fullscreen state', () => { it('should not cause a crash if called when exiting fullscreen', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; }); it('can be changed with setFullScreen method', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('isFullScreen'); }); it('handles several transitions starting with fullscreen', async () => { const w = new BrowserWindow({ fullscreen: true, show: true }); expect(w.isFullScreen()).to.be.true('not fullscreen'); w.setFullScreen(false); w.setFullScreen(true); const enterFullScreen = emittedNTimes(w, 'enter-full-screen', 2); await enterFullScreen; expect(w.isFullScreen()).to.be.true('not fullscreen'); await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); }); it('handles several transitions in close proximity', async () => { const w = new BrowserWindow(); expect(w.isFullScreen()).to.be.false('is fullscreen'); w.setFullScreen(true); w.setFullScreen(false); w.setFullScreen(true); const enterFullScreen = emittedNTimes(w, 'enter-full-screen', 2); await enterFullScreen; expect(w.isFullScreen()).to.be.true('not fullscreen'); }); it('does not crash when exiting simpleFullScreen (properties)', async () => { const w = new BrowserWindow(); w.setSimpleFullScreen(true); await delay(1000); w.setFullScreen(!w.isFullScreen()); }); it('does not crash when exiting simpleFullScreen (functions)', async () => { const w = new BrowserWindow(); w.simpleFullScreen = true; await delay(1000); w.setFullScreen(!w.isFullScreen()); }); it('should not be changed by setKiosk method', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await delay(); w.setKiosk(true); await delay(); w.setKiosk(false); expect(w.isFullScreen()).to.be.true('isFullScreen'); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('isFullScreen'); }); // FIXME: https://github.com/electron/electron/issues/30140 xit('multiple windows inherit correct fullscreen state', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await delay(); const w2 = new BrowserWindow({ show: false }); const enterFullScreen2 = emittedOnce(w2, 'enter-full-screen'); w2.show(); await enterFullScreen2; expect(w2.isFullScreen()).to.be.true('isFullScreen'); }); }); describe('closable state', () => { it('with properties', () => { it('can be set with closable constructor option', () => { const w = new BrowserWindow({ show: false, closable: false }); expect(w.closable).to.be.false('closable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.closable).to.be.true('closable'); w.closable = false; expect(w.closable).to.be.false('closable'); w.closable = true; expect(w.closable).to.be.true('closable'); }); }); it('with functions', () => { it('can be set with closable constructor option', () => { const w = new BrowserWindow({ show: false, closable: false }); expect(w.isClosable()).to.be.false('isClosable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isClosable()).to.be.true('isClosable'); w.setClosable(false); expect(w.isClosable()).to.be.false('isClosable'); w.setClosable(true); expect(w.isClosable()).to.be.true('isClosable'); }); }); }); describe('hasShadow state', () => { it('with properties', () => { it('returns a boolean on all platforms', () => { const w = new BrowserWindow({ show: false }); expect(w.shadow).to.be.a('boolean'); }); // On Windows there's no shadow by default & it can't be changed dynamically. it('can be changed with hasShadow option', () => { const hasShadow = process.platform !== 'darwin'; const w = new BrowserWindow({ show: false, hasShadow }); expect(w.shadow).to.equal(hasShadow); }); it('can be changed with setHasShadow method', () => { const w = new BrowserWindow({ show: false }); w.shadow = false; expect(w.shadow).to.be.false('hasShadow'); w.shadow = true; expect(w.shadow).to.be.true('hasShadow'); w.shadow = false; expect(w.shadow).to.be.false('hasShadow'); }); }); describe('with functions', () => { it('returns a boolean on all platforms', () => { const w = new BrowserWindow({ show: false }); const hasShadow = w.hasShadow(); expect(hasShadow).to.be.a('boolean'); }); // On Windows there's no shadow by default & it can't be changed dynamically. it('can be changed with hasShadow option', () => { const hasShadow = process.platform !== 'darwin'; const w = new BrowserWindow({ show: false, hasShadow }); expect(w.hasShadow()).to.equal(hasShadow); }); it('can be changed with setHasShadow method', () => { const w = new BrowserWindow({ show: false }); w.setHasShadow(false); expect(w.hasShadow()).to.be.false('hasShadow'); w.setHasShadow(true); expect(w.hasShadow()).to.be.true('hasShadow'); w.setHasShadow(false); expect(w.hasShadow()).to.be.false('hasShadow'); }); }); }); }); describe('window.getMediaSourceId()', () => { afterEach(closeAllWindows); it('returns valid source id', async () => { const w = new BrowserWindow({ show: false }); const shown = emittedOnce(w, 'show'); w.show(); await shown; // Check format 'window:1234:0'. const sourceId = w.getMediaSourceId(); expect(sourceId).to.match(/^window:\d+:\d+$/); }); }); ifdescribe(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('window.getNativeWindowHandle()', () => { afterEach(closeAllWindows); it('returns valid handle', () => { const w = new BrowserWindow({ show: false }); // The module's source code is hosted at // https://github.com/electron/node-is-valid-window const isValidWindow = require('is-valid-window'); expect(isValidWindow(w.getNativeWindowHandle())).to.be.true('is valid window'); }); }); ifdescribe(process.platform === 'darwin')('previewFile', () => { afterEach(closeAllWindows); it('opens the path in Quick Look on macOS', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.previewFile(__filename); w.closeFilePreview(); }).to.not.throw(); }); }); describe('contextIsolation option with and without sandbox option', () => { const expectedContextData = { preloadContext: { preloadProperty: 'number', pageProperty: 'undefined', typeofRequire: 'function', typeofProcess: 'object', typeofArrayPush: 'function', typeofFunctionApply: 'function', typeofPreloadExecuteJavaScriptProperty: 'undefined' }, pageContext: { preloadProperty: 'undefined', pageProperty: 'string', typeofRequire: 'undefined', typeofProcess: 'undefined', typeofArrayPush: 'number', typeofFunctionApply: 'boolean', typeofPreloadExecuteJavaScriptProperty: 'number', typeofOpenedWindow: 'object' } }; afterEach(closeAllWindows); it('separates the page context from the Electron/preload context', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = emittedOnce(ipcMain, 'isolated-world'); iw.loadFile(path.join(fixtures, 'api', 'isolated.html')); const [, data] = await p; expect(data).to.deep.equal(expectedContextData); }); it('recreates the contexts on reload', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); await iw.loadFile(path.join(fixtures, 'api', 'isolated.html')); const isolatedWorld = emittedOnce(ipcMain, 'isolated-world'); iw.webContents.reload(); const [, data] = await isolatedWorld; expect(data).to.deep.equal(expectedContextData); }); it('enables context isolation on child windows', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const browserWindowCreated = emittedOnce(app, 'browser-window-created'); iw.loadFile(path.join(fixtures, 'pages', 'window-open.html')); const [, window] = await browserWindowCreated; expect(window.webContents.getLastWebPreferences().contextIsolation).to.be.true('contextIsolation'); }); it('separates the page context from the Electron/preload context with sandbox on', async () => { const ws = new BrowserWindow({ show: false, webPreferences: { sandbox: true, contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = emittedOnce(ipcMain, 'isolated-world'); ws.loadFile(path.join(fixtures, 'api', 'isolated.html')); const [, data] = await p; expect(data).to.deep.equal(expectedContextData); }); it('recreates the contexts on reload with sandbox on', async () => { const ws = new BrowserWindow({ show: false, webPreferences: { sandbox: true, contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); await ws.loadFile(path.join(fixtures, 'api', 'isolated.html')); const isolatedWorld = emittedOnce(ipcMain, 'isolated-world'); ws.webContents.reload(); const [, data] = await isolatedWorld; expect(data).to.deep.equal(expectedContextData); }); it('supports fetch api', async () => { const fetchWindow = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-fetch-preload.js') } }); const p = emittedOnce(ipcMain, 'isolated-fetch-error'); fetchWindow.loadURL('about:blank'); const [, error] = await p; expect(error).to.equal('Failed to fetch'); }); it('doesn\'t break ipc serialization', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = emittedOnce(ipcMain, 'isolated-world'); iw.loadURL('about:blank'); iw.webContents.executeJavaScript(` const opened = window.open() openedLocation = opened.location.href opened.close() window.postMessage({openedLocation}, '*') `); const [, data] = await p; expect(data.pageContext.openedLocation).to.equal('about:blank'); }); it('reports process.contextIsolated', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-process.js') } }); const p = emittedOnce(ipcMain, 'context-isolation'); iw.loadURL('about:blank'); const [, contextIsolation] = await p; expect(contextIsolation).to.be.true('contextIsolation'); }); }); it('reloading does not cause Node.js module API hangs after reload', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); let count = 0; ipcMain.on('async-node-api-done', () => { if (count === 3) { ipcMain.removeAllListeners('async-node-api-done'); done(); } else { count++; w.reload(); } }); w.loadFile(path.join(fixtures, 'pages', 'send-after-node.html')); }); describe('window.webContents.focus()', () => { afterEach(closeAllWindows); it('focuses window', async () => { const w1 = new BrowserWindow({ x: 100, y: 300, width: 300, height: 200 }); w1.loadURL('about:blank'); const w2 = new BrowserWindow({ x: 300, y: 300, width: 300, height: 200 }); w2.loadURL('about:blank'); const w1Focused = emittedOnce(w1, 'focus'); w1.webContents.focus(); await w1Focused; expect(w1.webContents.isFocused()).to.be.true('focuses window'); }); }); ifdescribe(features.isOffscreenRenderingEnabled())('offscreen rendering', () => { let w: BrowserWindow; beforeEach(function () { w = new BrowserWindow({ width: 100, height: 100, show: false, webPreferences: { backgroundThrottling: false, offscreen: true } }); }); afterEach(closeAllWindows); it('creates offscreen window with correct size', async () => { const paint = emittedOnce(w.webContents, 'paint'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); const [,, data] = await paint; expect(data.constructor.name).to.equal('NativeImage'); expect(data.isEmpty()).to.be.false('data is empty'); const size = data.getSize(); const { scaleFactor } = screen.getPrimaryDisplay(); expect(size.width).to.be.closeTo(100 * scaleFactor, 2); expect(size.height).to.be.closeTo(100 * scaleFactor, 2); }); it('does not crash after navigation', () => { w.webContents.loadURL('about:blank'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); }); describe('window.webContents.isOffscreen()', () => { it('is true for offscreen type', () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); expect(w.webContents.isOffscreen()).to.be.true('isOffscreen'); }); it('is false for regular window', () => { const c = new BrowserWindow({ show: false }); expect(c.webContents.isOffscreen()).to.be.false('isOffscreen'); c.destroy(); }); }); describe('window.webContents.isPainting()', () => { it('returns whether is currently painting', async () => { const paint = emittedOnce(w.webContents, 'paint'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await paint; expect(w.webContents.isPainting()).to.be.true('isPainting'); }); }); describe('window.webContents.stopPainting()', () => { it('stops painting', async () => { const domReady = emittedOnce(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.stopPainting(); expect(w.webContents.isPainting()).to.be.false('isPainting'); }); }); describe('window.webContents.startPainting()', () => { it('starts painting', async () => { const domReady = emittedOnce(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.stopPainting(); w.webContents.startPainting(); await emittedOnce(w.webContents, 'paint'); expect(w.webContents.isPainting()).to.be.true('isPainting'); }); }); describe('frameRate APIs', () => { it('has default frame rate (function)', async () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await emittedOnce(w.webContents, 'paint'); expect(w.webContents.getFrameRate()).to.equal(60); }); it('has default frame rate (property)', async () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await emittedOnce(w.webContents, 'paint'); expect(w.webContents.frameRate).to.equal(60); }); it('sets custom frame rate (function)', async () => { const domReady = emittedOnce(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.setFrameRate(30); await emittedOnce(w.webContents, 'paint'); expect(w.webContents.getFrameRate()).to.equal(30); }); it('sets custom frame rate (property)', async () => { const domReady = emittedOnce(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.frameRate = 30; await emittedOnce(w.webContents, 'paint'); expect(w.webContents.frameRate).to.equal(30); }); }); }); describe('"transparent" option', () => { afterEach(closeAllWindows); // Only applicable on Windows where transparent windows can't be maximized. ifit(process.platform === 'win32')('can show maximized frameless window', async () => { const display = screen.getPrimaryDisplay(); const w = new BrowserWindow({ ...display.bounds, frame: false, transparent: true, show: true }); w.loadURL('about:blank'); await emittedOnce(w, 'ready-to-show'); expect(w.isMaximized()).to.be.true(); // Fails when the transparent HWND is in an invalid maximized state. expect(w.getBounds()).to.deep.equal(display.workArea); const newBounds = { width: 256, height: 256, x: 0, y: 0 }; w.setBounds(newBounds); expect(w.getBounds()).to.deep.equal(newBounds); }); // Linux and arm64 platforms (WOA and macOS) do not return any capture sources ifit(process.platform !== 'linux' && process.arch !== 'arm64')('should not display a visible background', async () => { const display = screen.getPrimaryDisplay(); const backgroundWindow = new BrowserWindow({ ...display.bounds, frame: false, backgroundColor: CHROMA_COLOR_HEX, hasShadow: false }); await backgroundWindow.loadURL('about:blank'); const foregroundWindow = new BrowserWindow({ ...display.bounds, show: true, transparent: true, frame: false, hasShadow: false }); foregroundWindow.loadFile(path.join(__dirname, 'fixtures', 'pages', 'half-background-color.html')); await emittedOnce(foregroundWindow, 'ready-to-show'); const screenCapture = await captureScreen(); const leftHalfColor = getPixelColor(screenCapture, { x: display.size.width / 4, y: display.size.height / 2 }); const rightHalfColor = getPixelColor(screenCapture, { x: display.size.width - (display.size.width / 4), y: display.size.height / 2 }); expect(areColorsSimilar(leftHalfColor, CHROMA_COLOR_HEX)).to.be.true(); expect(areColorsSimilar(rightHalfColor, '#ff0000')).to.be.true(); }); }); describe('"backgroundColor" option', () => { afterEach(closeAllWindows); // Linux/WOA doesn't return any capture sources. ifit(process.platform !== 'linux' && (process.platform !== 'win32' || process.arch !== 'arm64'))('should display the set color', async () => { const display = screen.getPrimaryDisplay(); const w = new BrowserWindow({ ...display.bounds, show: true, backgroundColor: CHROMA_COLOR_HEX }); w.loadURL('about:blank'); await emittedOnce(w, 'ready-to-show'); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); expect(areColorsSimilar(centerColor, CHROMA_COLOR_HEX)).to.be.true(); }); }); });
closed
electron/electron
https://github.com/electron/electron
34,047
[Bug]: offscreen rendering doesn't render clicked INPUT SELECT dropdown
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 18.1.0 ### What operating system are you using? Ubuntu ### Operating System Version Ubuntu 20.04 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior Offscreen rendering paint events should receive events for SELECT input elements. ### Actual Behavior Sometimes an empty white box appears, or nothing happens. ### Testcase Gist URL https://gist.github.com/gtalusan/c0ad56685aeb3b2c1108fbccf6b451b4 ### Additional Information Here's a screenshot when the fiddle is run with `offscreen = false`: <img width="760" alt="Screen Shot 2022-05-03 at 9 54 42 AM" src="https://user-images.githubusercontent.com/355585/166471227-1e0e27b0-cc8b-4c8e-94e5-a4261e2437b6.png"> Here are the paint event images saved to PNGs when `offscreen = true`: ![0](https://user-images.githubusercontent.com/355585/166471435-209960eb-27e2-47f1-a758-1760a052f3d1.png) ![1](https://user-images.githubusercontent.com/355585/166471445-269fab98-f046-43d4-b72a-65a49c5bc067.png)
https://github.com/electron/electron/issues/34047
https://github.com/electron/electron/pull/34069
323f7d4c19b232ec5661d9d87fcecaf6918d8abf
90eb47f70ba0ba1b89933ba505f6cc8805411bcf
2022-05-03T14:23:00Z
c++
2022-05-05T13:53:39Z
shell/browser/osr/osr_render_widget_host_view.cc
// Copyright (c) 2016 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/osr/osr_render_widget_host_view.h" #include <algorithm> #include <memory> #include <utility> #include <vector> #include "base/callback_helpers.h" #include "base/location.h" #include "base/memory/ptr_util.h" #include "base/task/post_task.h" #include "base/task/single_thread_task_runner.h" #include "base/time/time.h" #include "components/viz/common/features.h" #include "components/viz/common/frame_sinks/begin_frame_args.h" #include "components/viz/common/frame_sinks/copy_output_request.h" #include "components/viz/common/frame_sinks/delay_based_time_source.h" #include "components/viz/common/quads/compositor_render_pass.h" #include "content/browser/renderer_host/cursor_manager.h" // nogncheck #include "content/browser/renderer_host/input/synthetic_gesture_target.h" // nogncheck #include "content/browser/renderer_host/render_widget_host_delegate.h" // nogncheck #include "content/browser/renderer_host/render_widget_host_owner_delegate.h" // nogncheck #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/context_factory.h" #include "content/public/browser/gpu_data_manager.h" #include "content/public/browser/render_process_host.h" #include "gpu/command_buffer/client/gl_helper.h" #include "media/base/video_frame.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "third_party/blink/public/common/input/web_input_event.h" #include "third_party/skia/include/core/SkCanvas.h" #include "ui/compositor/compositor.h" #include "ui/compositor/layer.h" #include "ui/compositor/layer_type.h" #include "ui/display/screen.h" #include "ui/events/base_event_utils.h" #include "ui/events/event_constants.h" #include "ui/gfx/canvas.h" #include "ui/gfx/geometry/dip_util.h" #include "ui/gfx/geometry/size_conversions.h" #include "ui/gfx/image/image_skia.h" #include "ui/gfx/native_widget_types.h" #include "ui/gfx/skbitmap_operations.h" #include "ui/latency/latency_info.h" namespace electron { namespace { const float kDefaultScaleFactor = 1.0; ui::MouseEvent UiMouseEventFromWebMouseEvent(blink::WebMouseEvent event) { ui::EventType type = ui::EventType::ET_UNKNOWN; switch (event.GetType()) { case blink::WebInputEvent::Type::kMouseDown: type = ui::EventType::ET_MOUSE_PRESSED; break; case blink::WebInputEvent::Type::kMouseUp: type = ui::EventType::ET_MOUSE_RELEASED; break; case blink::WebInputEvent::Type::kMouseMove: type = ui::EventType::ET_MOUSE_MOVED; break; case blink::WebInputEvent::Type::kMouseEnter: type = ui::EventType::ET_MOUSE_ENTERED; break; case blink::WebInputEvent::Type::kMouseLeave: type = ui::EventType::ET_MOUSE_EXITED; break; case blink::WebInputEvent::Type::kMouseWheel: type = ui::EventType::ET_MOUSEWHEEL; break; default: type = ui::EventType::ET_UNKNOWN; break; } int button_flags = 0; switch (event.button) { case blink::WebMouseEvent::Button::kBack: button_flags |= ui::EventFlags::EF_BACK_MOUSE_BUTTON; break; case blink::WebMouseEvent::Button::kForward: button_flags |= ui::EventFlags::EF_FORWARD_MOUSE_BUTTON; break; case blink::WebMouseEvent::Button::kLeft: button_flags |= ui::EventFlags::EF_LEFT_MOUSE_BUTTON; break; case blink::WebMouseEvent::Button::kMiddle: button_flags |= ui::EventFlags::EF_MIDDLE_MOUSE_BUTTON; break; case blink::WebMouseEvent::Button::kRight: button_flags |= ui::EventFlags::EF_RIGHT_MOUSE_BUTTON; break; default: button_flags = 0; break; } ui::MouseEvent ui_event(type, gfx::Point(std::floor(event.PositionInWidget().x()), std::floor(event.PositionInWidget().y())), gfx::Point(std::floor(event.PositionInWidget().x()), std::floor(event.PositionInWidget().y())), ui::EventTimeForNow(), button_flags, button_flags); ui_event.SetClickCount(event.click_count); return ui_event; } ui::MouseWheelEvent UiMouseWheelEventFromWebMouseEvent( blink::WebMouseWheelEvent event) { return ui::MouseWheelEvent(UiMouseEventFromWebMouseEvent(event), std::floor(event.delta_x), std::floor(event.delta_y)); } } // namespace class ElectronDelegatedFrameHostClient : public content::DelegatedFrameHostClient { public: explicit ElectronDelegatedFrameHostClient(OffScreenRenderWidgetHostView* view) : view_(view) {} // disable copy ElectronDelegatedFrameHostClient(const ElectronDelegatedFrameHostClient&) = delete; ElectronDelegatedFrameHostClient& operator=( const ElectronDelegatedFrameHostClient&) = delete; ui::Layer* DelegatedFrameHostGetLayer() const override { return view_->GetRootLayer(); } bool DelegatedFrameHostIsVisible() const override { return view_->IsShowing(); } SkColor DelegatedFrameHostGetGutterColor() const override { if (view_->render_widget_host()->delegate() && view_->render_widget_host()->delegate()->IsFullscreen()) { return SK_ColorWHITE; } return *view_->GetBackgroundColor(); } void OnFrameTokenChanged(uint32_t frame_token, base::TimeTicks activation_time) override { view_->render_widget_host()->DidProcessFrame(frame_token, activation_time); } float GetDeviceScaleFactor() const override { return view_->GetDeviceScaleFactor(); } std::vector<viz::SurfaceId> CollectSurfaceIdsForEviction() override { return view_->render_widget_host()->CollectSurfaceIdsForEviction(); } bool ShouldShowStaleContentOnEviction() override { return false; } void InvalidateLocalSurfaceIdOnEviction() override {} private: OffScreenRenderWidgetHostView* const view_; }; OffScreenRenderWidgetHostView::OffScreenRenderWidgetHostView( bool transparent, bool painting, int frame_rate, const OnPaintCallback& callback, content::RenderWidgetHost* host, OffScreenRenderWidgetHostView* parent_host_view, gfx::Size initial_size) : content::RenderWidgetHostViewBase(host), render_widget_host_(content::RenderWidgetHostImpl::From(host)), parent_host_view_(parent_host_view), transparent_(transparent), callback_(callback), frame_rate_(frame_rate), size_(initial_size), painting_(painting), cursor_manager_(std::make_unique<content::CursorManager>(this)), mouse_wheel_phase_handler_(this), backing_(std::make_unique<SkBitmap>()) { DCHECK(render_widget_host_); DCHECK(!render_widget_host_->GetView()); // Initialize a screen_infos_ struct as needed, to cache the scale factor. if (screen_infos_.screen_infos.empty()) { UpdateScreenInfo(); } screen_infos_.mutable_current().device_scale_factor = kDefaultScaleFactor; delegated_frame_host_allocator_.GenerateId(); delegated_frame_host_surface_id_ = delegated_frame_host_allocator_.GetCurrentLocalSurfaceId(); compositor_allocator_.GenerateId(); compositor_surface_id_ = compositor_allocator_.GetCurrentLocalSurfaceId(); delegated_frame_host_client_ = std::make_unique<ElectronDelegatedFrameHostClient>(this); delegated_frame_host_ = std::make_unique<content::DelegatedFrameHost>( AllocateFrameSinkId(), delegated_frame_host_client_.get(), true /* should_register_frame_sink_id */); root_layer_ = std::make_unique<ui::Layer>(ui::LAYER_SOLID_COLOR); bool opaque = SkColorGetA(background_color_) == SK_AlphaOPAQUE; GetRootLayer()->SetFillsBoundsOpaquely(opaque); GetRootLayer()->SetColor(background_color_); ui::ContextFactory* context_factory = content::GetContextFactory(); compositor_ = std::make_unique<ui::Compositor>( context_factory->AllocateFrameSinkId(), context_factory, base::ThreadTaskRunnerHandle::Get(), false /* enable_pixel_canvas */, false /* use_external_begin_frame_control */); compositor_->SetAcceleratedWidget(gfx::kNullAcceleratedWidget); compositor_->SetDelegate(this); compositor_->SetRootLayer(root_layer_.get()); ResizeRootLayer(false); render_widget_host_->SetView(this); if (content::GpuDataManager::GetInstance()->HardwareAccelerationEnabled()) { video_consumer_ = std::make_unique<OffScreenVideoConsumer>( this, base::BindRepeating(&OffScreenRenderWidgetHostView::OnPaint, weak_ptr_factory_.GetWeakPtr())); video_consumer_->SetActive(IsPainting()); video_consumer_->SetFrameRate(GetFrameRate()); } } OffScreenRenderWidgetHostView::~OffScreenRenderWidgetHostView() { // Marking the DelegatedFrameHost as removed from the window hierarchy is // necessary to remove all connections to its old ui::Compositor. if (is_showing_) delegated_frame_host_->WasHidden( content::DelegatedFrameHost::HiddenCause::kOther); delegated_frame_host_->DetachFromCompositor(); delegated_frame_host_.reset(); compositor_.reset(); root_layer_.reset(); } void OffScreenRenderWidgetHostView::InitAsChild(gfx::NativeView) { DCHECK(parent_host_view_); if (parent_host_view_->child_host_view_) { parent_host_view_->child_host_view_->CancelWidget(); } parent_host_view_->set_child_host_view(this); parent_host_view_->Hide(); ResizeRootLayer(false); SetPainting(parent_host_view_->IsPainting()); } void OffScreenRenderWidgetHostView::SetSize(const gfx::Size& size) { size_ = size; SynchronizeVisualProperties(); } void OffScreenRenderWidgetHostView::SetBounds(const gfx::Rect& new_bounds) { SetSize(new_bounds.size()); } gfx::NativeView OffScreenRenderWidgetHostView::GetNativeView() { return gfx::NativeView(); } gfx::NativeViewAccessible OffScreenRenderWidgetHostView::GetNativeViewAccessible() { return gfx::NativeViewAccessible(); } ui::TextInputClient* OffScreenRenderWidgetHostView::GetTextInputClient() { return nullptr; } void OffScreenRenderWidgetHostView::Focus() {} bool OffScreenRenderWidgetHostView::HasFocus() { return false; } bool OffScreenRenderWidgetHostView::IsSurfaceAvailableForCopy() { return GetDelegatedFrameHost()->CanCopyFromCompositingSurface(); } void OffScreenRenderWidgetHostView::ShowWithVisibility( content::PageVisibilityState /*page_visibility*/) { if (is_showing_) return; is_showing_ = true; delegated_frame_host_->AttachToCompositor(compositor_.get()); delegated_frame_host_->WasShown(GetLocalSurfaceId(), GetRootLayer()->bounds().size(), {}); if (render_widget_host_) render_widget_host_->WasShown({}); } void OffScreenRenderWidgetHostView::Hide() { if (!is_showing_) return; if (render_widget_host_) render_widget_host_->WasHidden(); // TODO(deermichel): correct or kOther? GetDelegatedFrameHost()->WasHidden( content::DelegatedFrameHost::HiddenCause::kOccluded); GetDelegatedFrameHost()->DetachFromCompositor(); is_showing_ = false; } bool OffScreenRenderWidgetHostView::IsShowing() { return is_showing_; } void OffScreenRenderWidgetHostView::EnsureSurfaceSynchronizedForWebTest() { ++latest_capture_sequence_number_; SynchronizeVisualProperties(); } gfx::Rect OffScreenRenderWidgetHostView::GetViewBounds() { if (IsPopupWidget()) return popup_position_; return gfx::Rect(size_); } void OffScreenRenderWidgetHostView::SetBackgroundColor(SkColor color) { // The renderer will feed its color back to us with the first CompositorFrame. // We short-cut here to show a sensible color before that happens. UpdateBackgroundColorFromRenderer(color); if (render_widget_host_ && render_widget_host_->owner_delegate()) { render_widget_host_->owner_delegate()->SetBackgroundOpaque( SkColorGetA(color) == SK_AlphaOPAQUE); } } absl::optional<SkColor> OffScreenRenderWidgetHostView::GetBackgroundColor() { return background_color_; } void OffScreenRenderWidgetHostView::UpdateBackgroundColor() {} gfx::Size OffScreenRenderWidgetHostView::GetVisibleViewportSize() { return size_; } void OffScreenRenderWidgetHostView::SetInsets(const gfx::Insets& insets) {} blink::mojom::PointerLockResult OffScreenRenderWidgetHostView::LockMouse( bool request_unadjusted_movement) { return blink::mojom::PointerLockResult::kUnsupportedOptions; } blink::mojom::PointerLockResult OffScreenRenderWidgetHostView::ChangeMouseLock( bool request_unadjusted_movement) { return blink::mojom::PointerLockResult::kUnsupportedOptions; } void OffScreenRenderWidgetHostView::UnlockMouse() {} void OffScreenRenderWidgetHostView::TakeFallbackContentFrom( content::RenderWidgetHostView* view) { DCHECK(!static_cast<content::RenderWidgetHostViewBase*>(view) ->IsRenderWidgetHostViewChildFrame()); auto* view_osr = static_cast<OffScreenRenderWidgetHostView*>(view); SetBackgroundColor(view_osr->background_color_); if (GetDelegatedFrameHost() && view_osr->GetDelegatedFrameHost()) { GetDelegatedFrameHost()->TakeFallbackContentFrom( view_osr->GetDelegatedFrameHost()); } host()->GetContentRenderingTimeoutFrom(view_osr->host()); } void OffScreenRenderWidgetHostView::ResetFallbackToFirstNavigationSurface() { GetDelegatedFrameHost()->ResetFallbackToFirstNavigationSurface(); } void OffScreenRenderWidgetHostView::InitAsPopup( content::RenderWidgetHostView* parent_host_view, const gfx::Rect& pos, const gfx::Rect& anchor_rect) { DCHECK_EQ(parent_host_view_, parent_host_view); DCHECK_EQ(widget_type_, content::WidgetType::kPopup); if (parent_host_view_->popup_host_view_) { parent_host_view_->popup_host_view_->CancelWidget(); } parent_host_view_->set_popup_host_view(this); parent_callback_ = base::BindRepeating(&OffScreenRenderWidgetHostView::OnPopupPaint, parent_host_view_->weak_ptr_factory_.GetWeakPtr()); popup_position_ = pos; ResizeRootLayer(false); SetPainting(parent_host_view_->IsPainting()); if (video_consumer_) { video_consumer_->SizeChanged(); } Show(); } void OffScreenRenderWidgetHostView::UpdateCursor(const content::WebCursor&) {} content::CursorManager* OffScreenRenderWidgetHostView::GetCursorManager() { return cursor_manager_.get(); } void OffScreenRenderWidgetHostView::SetIsLoading(bool loading) {} void OffScreenRenderWidgetHostView::TextInputStateChanged( const ui::mojom::TextInputState& params) {} void OffScreenRenderWidgetHostView::ImeCancelComposition() {} void OffScreenRenderWidgetHostView::RenderProcessGone() { Destroy(); } void OffScreenRenderWidgetHostView::Destroy() { if (!is_destroyed_) { is_destroyed_ = true; if (parent_host_view_ != nullptr) { CancelWidget(); } else { if (popup_host_view_) popup_host_view_->CancelWidget(); if (child_host_view_) child_host_view_->CancelWidget(); if (!guest_host_views_.empty()) { // Guest RWHVs will be destroyed when the associated RWHVGuest is // destroyed. This parent RWHV may be destroyed first, so disassociate // the guest RWHVs here without destroying them. for (auto* guest_host_view : guest_host_views_) guest_host_view->parent_host_view_ = nullptr; guest_host_views_.clear(); } for (auto* proxy_view : proxy_views_) proxy_view->RemoveObserver(); Hide(); } } delete this; } void OffScreenRenderWidgetHostView::UpdateTooltipUnderCursor( const std::u16string&) {} uint32_t OffScreenRenderWidgetHostView::GetCaptureSequenceNumber() const { return latest_capture_sequence_number_; } void OffScreenRenderWidgetHostView::CopyFromSurface( const gfx::Rect& src_rect, const gfx::Size& output_size, base::OnceCallback<void(const SkBitmap&)> callback) { GetDelegatedFrameHost()->CopyFromCompositingSurface(src_rect, output_size, std::move(callback)); } display::ScreenInfo OffScreenRenderWidgetHostView::GetScreenInfo() const { display::ScreenInfo screen_info; screen_info.depth = 24; screen_info.depth_per_component = 8; screen_info.orientation_angle = 0; screen_info.device_scale_factor = GetDeviceScaleFactor(); screen_info.orientation_type = display::mojom::ScreenOrientation::kLandscapePrimary; screen_info.rect = gfx::Rect(size_); screen_info.available_rect = gfx::Rect(size_); return screen_info; } void OffScreenRenderWidgetHostView::TransformPointToRootSurface( gfx::PointF* point) {} gfx::Rect OffScreenRenderWidgetHostView::GetBoundsInRootWindow() { return gfx::Rect(size_); } absl::optional<content::DisplayFeature> OffScreenRenderWidgetHostView::GetDisplayFeature() { return absl::nullopt; } void OffScreenRenderWidgetHostView::SetDisplayFeatureForTesting( const content::DisplayFeature* display_feature) {} viz::SurfaceId OffScreenRenderWidgetHostView::GetCurrentSurfaceId() const { return GetDelegatedFrameHost() ? GetDelegatedFrameHost()->GetCurrentSurfaceId() : viz::SurfaceId(); } std::unique_ptr<content::SyntheticGestureTarget> OffScreenRenderWidgetHostView::CreateSyntheticGestureTarget() { NOTIMPLEMENTED(); return nullptr; } void OffScreenRenderWidgetHostView::ImeCompositionRangeChanged( const gfx::Range&, const std::vector<gfx::Rect>&) {} gfx::Size OffScreenRenderWidgetHostView::GetCompositorViewportPixelSize() { return gfx::ScaleToCeiledSize(GetRequestedRendererSize(), GetDeviceScaleFactor()); } ui::Compositor* OffScreenRenderWidgetHostView::GetCompositor() { return compositor_.get(); } content::RenderWidgetHostViewBase* OffScreenRenderWidgetHostView::CreateViewForWidget( content::RenderWidgetHost* render_widget_host, content::RenderWidgetHost* embedder_render_widget_host, content::WebContentsView* web_contents_view) { if (render_widget_host->GetView()) { return static_cast<content::RenderWidgetHostViewBase*>( render_widget_host->GetView()); } OffScreenRenderWidgetHostView* embedder_host_view = nullptr; if (embedder_render_widget_host) { embedder_host_view = static_cast<OffScreenRenderWidgetHostView*>( embedder_render_widget_host->GetView()); } return new OffScreenRenderWidgetHostView( transparent_, true, embedder_host_view->GetFrameRate(), callback_, render_widget_host, embedder_host_view, size()); } const viz::FrameSinkId& OffScreenRenderWidgetHostView::GetFrameSinkId() const { return GetDelegatedFrameHost()->frame_sink_id(); } void OffScreenRenderWidgetHostView::DidNavigate() { ResizeRootLayer(true); if (delegated_frame_host_) delegated_frame_host_->DidNavigate(); } bool OffScreenRenderWidgetHostView::TransformPointToCoordSpaceForView( const gfx::PointF& point, RenderWidgetHostViewBase* target_view, gfx::PointF* transformed_point) { if (target_view == this) { *transformed_point = point; return true; } return false; } void OffScreenRenderWidgetHostView::CancelWidget() { if (render_widget_host_) render_widget_host_->LostCapture(); Hide(); if (parent_host_view_) { if (parent_host_view_->popup_host_view_ == this) { parent_host_view_->set_popup_host_view(nullptr); } else if (parent_host_view_->child_host_view_ == this) { parent_host_view_->set_child_host_view(nullptr); parent_host_view_->Show(); } else { parent_host_view_->RemoveGuestHostView(this); } parent_host_view_ = nullptr; } if (render_widget_host_ && !is_destroyed_) { is_destroyed_ = true; // Results in a call to Destroy(). render_widget_host_->ShutdownAndDestroyWidget(true); } } void OffScreenRenderWidgetHostView::AddGuestHostView( OffScreenRenderWidgetHostView* guest_host) { guest_host_views_.insert(guest_host); } void OffScreenRenderWidgetHostView::RemoveGuestHostView( OffScreenRenderWidgetHostView* guest_host) { guest_host_views_.erase(guest_host); } void OffScreenRenderWidgetHostView::AddViewProxy(OffscreenViewProxy* proxy) { proxy->SetObserver(this); proxy_views_.insert(proxy); } void OffScreenRenderWidgetHostView::RemoveViewProxy(OffscreenViewProxy* proxy) { proxy->RemoveObserver(); proxy_views_.erase(proxy); } void OffScreenRenderWidgetHostView::ProxyViewDestroyed( OffscreenViewProxy* proxy) { proxy_views_.erase(proxy); Invalidate(); } bool OffScreenRenderWidgetHostView::IsOffscreen() const { return true; } std::unique_ptr<viz::HostDisplayClient> OffScreenRenderWidgetHostView::CreateHostDisplayClient( ui::Compositor* compositor) { host_display_client_ = new OffScreenHostDisplayClient( gfx::kNullAcceleratedWidget, base::BindRepeating(&OffScreenRenderWidgetHostView::OnPaint, weak_ptr_factory_.GetWeakPtr())); host_display_client_->SetActive(IsPainting()); return base::WrapUnique(host_display_client_); } bool OffScreenRenderWidgetHostView::InstallTransparency() { if (transparent_) { SetBackgroundColor(SkColor()); compositor_->SetBackgroundColor(SK_ColorTRANSPARENT); return true; } return false; } #if BUILDFLAG(IS_MAC) void OffScreenRenderWidgetHostView::SetActive(bool active) {} void OffScreenRenderWidgetHostView::ShowDefinitionForSelection() {} void OffScreenRenderWidgetHostView::SpeakSelection() {} void OffScreenRenderWidgetHostView::SetWindowFrameInScreen( const gfx::Rect& rect) {} void OffScreenRenderWidgetHostView::ShowSharePicker( const std::string& title, const std::string& text, const std::string& url, const std::vector<std::string>& file_paths, blink::mojom::ShareService::ShareCallback callback) {} bool OffScreenRenderWidgetHostView::UpdateNSViewAndDisplay() { return false; } #endif void OffScreenRenderWidgetHostView::OnPaint(const gfx::Rect& damage_rect, const SkBitmap& bitmap) { backing_ = std::make_unique<SkBitmap>(); backing_->allocN32Pixels(bitmap.width(), bitmap.height(), !transparent_); bitmap.readPixels(backing_->pixmap()); if (IsPopupWidget() && parent_callback_) { parent_callback_.Run(this->popup_position_); } else { CompositeFrame(damage_rect); } } gfx::Size OffScreenRenderWidgetHostView::SizeInPixels() { float sf = GetDeviceScaleFactor(); if (IsPopupWidget()) { return gfx::ToFlooredSize( gfx::ConvertSizeToPixels(popup_position_.size(), sf)); } else { return gfx::ToFlooredSize( gfx::ConvertSizeToPixels(GetViewBounds().size(), sf)); } } void OffScreenRenderWidgetHostView::CompositeFrame( const gfx::Rect& damage_rect) { HoldResize(); gfx::Size size_in_pixels = SizeInPixels(); SkBitmap frame; // Optimize for the case when there is no popup if (proxy_views_.empty() && !popup_host_view_) { frame = GetBacking(); } else { float sf = GetDeviceScaleFactor(); frame.allocN32Pixels(size_in_pixels.width(), size_in_pixels.height(), false); if (!GetBacking().drawsNothing()) { SkCanvas canvas(frame); canvas.writePixels(GetBacking(), 0, 0); if (popup_host_view_ && !popup_host_view_->GetBacking().drawsNothing()) { gfx::Rect rect = popup_host_view_->popup_position_; gfx::Point origin_in_pixels = gfx::ToFlooredPoint(gfx::ConvertPointToPixels(rect.origin(), sf)); canvas.writePixels(popup_host_view_->GetBacking(), origin_in_pixels.x(), origin_in_pixels.y()); } for (auto* proxy_view : proxy_views_) { gfx::Rect rect = proxy_view->GetBounds(); gfx::Point origin_in_pixels = gfx::ToFlooredPoint(gfx::ConvertPointToPixels(rect.origin(), sf)); canvas.writePixels(*proxy_view->GetBitmap(), origin_in_pixels.x(), origin_in_pixels.y()); } } } paint_callback_running_ = true; callback_.Run(gfx::IntersectRects(gfx::Rect(size_in_pixels), damage_rect), frame); paint_callback_running_ = false; ReleaseResize(); } void OffScreenRenderWidgetHostView::OnPopupPaint(const gfx::Rect& damage_rect) { InvalidateBounds(gfx::ToEnclosingRect( gfx::ConvertRectToPixels(damage_rect, GetDeviceScaleFactor()))); } void OffScreenRenderWidgetHostView::OnProxyViewPaint( const gfx::Rect& damage_rect) { InvalidateBounds(gfx::ToEnclosingRect( gfx::ConvertRectToPixels(damage_rect, GetDeviceScaleFactor()))); } void OffScreenRenderWidgetHostView::HoldResize() { if (!hold_resize_) hold_resize_ = true; } void OffScreenRenderWidgetHostView::ReleaseResize() { if (!hold_resize_) return; hold_resize_ = false; if (pending_resize_) { pending_resize_ = false; base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce( &OffScreenRenderWidgetHostView::SynchronizeVisualProperties, weak_ptr_factory_.GetWeakPtr())); } } void OffScreenRenderWidgetHostView::SynchronizeVisualProperties() { if (hold_resize_) { if (!pending_resize_) pending_resize_ = true; return; } ResizeRootLayer(true); } void OffScreenRenderWidgetHostView::SendMouseEvent( const blink::WebMouseEvent& event) { for (auto* proxy_view : proxy_views_) { gfx::Rect bounds = proxy_view->GetBounds(); if (bounds.Contains(event.PositionInWidget().x(), event.PositionInWidget().y())) { blink::WebMouseEvent proxy_event(event); proxy_event.SetPositionInWidget( proxy_event.PositionInWidget().x() - bounds.x(), proxy_event.PositionInWidget().y() - bounds.y()); ui::MouseEvent ui_event = UiMouseEventFromWebMouseEvent(proxy_event); proxy_view->OnEvent(&ui_event); return; } } if (!IsPopupWidget()) { if (popup_host_view_ && popup_host_view_->popup_position_.Contains( event.PositionInWidget().x(), event.PositionInWidget().y())) { blink::WebMouseEvent popup_event(event); popup_event.SetPositionInWidget( popup_event.PositionInWidget().x() - popup_host_view_->popup_position_.x(), popup_event.PositionInWidget().y() - popup_host_view_->popup_position_.y()); popup_host_view_->ProcessMouseEvent(popup_event, ui::LatencyInfo()); return; } } if (!render_widget_host_) return; render_widget_host_->ForwardMouseEvent(event); } void OffScreenRenderWidgetHostView::SendMouseWheelEvent( const blink::WebMouseWheelEvent& event) { for (auto* proxy_view : proxy_views_) { gfx::Rect bounds = proxy_view->GetBounds(); if (bounds.Contains(event.PositionInWidget().x(), event.PositionInWidget().y())) { blink::WebMouseWheelEvent proxy_event(event); proxy_event.SetPositionInWidget( proxy_event.PositionInWidget().x() - bounds.x(), proxy_event.PositionInWidget().y() - bounds.y()); ui::MouseWheelEvent ui_event = UiMouseWheelEventFromWebMouseEvent(proxy_event); proxy_view->OnEvent(&ui_event); return; } } blink::WebMouseWheelEvent mouse_wheel_event(event); bool should_route_event = render_widget_host_->delegate() && render_widget_host_->delegate()->GetInputEventRouter(); mouse_wheel_phase_handler_.SendWheelEndForTouchpadScrollingIfNeeded( should_route_event); mouse_wheel_phase_handler_.AddPhaseIfNeededAndScheduleEndEvent( mouse_wheel_event, false); if (!IsPopupWidget()) { if (popup_host_view_) { if (popup_host_view_->popup_position_.Contains( mouse_wheel_event.PositionInWidget().x(), mouse_wheel_event.PositionInWidget().y())) { blink::WebMouseWheelEvent popup_mouse_wheel_event(mouse_wheel_event); popup_mouse_wheel_event.SetPositionInWidget( mouse_wheel_event.PositionInWidget().x() - popup_host_view_->popup_position_.x(), mouse_wheel_event.PositionInWidget().y() - popup_host_view_->popup_position_.y()); popup_mouse_wheel_event.SetPositionInScreen( popup_mouse_wheel_event.PositionInWidget().x(), popup_mouse_wheel_event.PositionInWidget().y()); popup_host_view_->SendMouseWheelEvent(popup_mouse_wheel_event); return; } else { // Scrolling outside of the popup widget so destroy it. // Execute asynchronously to avoid deleting the widget from inside some // other callback. base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&OffScreenRenderWidgetHostView::CancelWidget, popup_host_view_->weak_ptr_factory_.GetWeakPtr())); } } else if (!guest_host_views_.empty()) { for (auto* guest_host_view : guest_host_views_) { if (!guest_host_view->render_widget_host_ || !guest_host_view->render_widget_host_->GetView()) { continue; } const gfx::Rect& guest_bounds = guest_host_view->render_widget_host_->GetView()->GetViewBounds(); if (guest_bounds.Contains(mouse_wheel_event.PositionInWidget().x(), mouse_wheel_event.PositionInWidget().y())) { blink::WebMouseWheelEvent guest_mouse_wheel_event(mouse_wheel_event); guest_mouse_wheel_event.SetPositionInWidget( mouse_wheel_event.PositionInWidget().x() - guest_bounds.x(), mouse_wheel_event.PositionInWidget().y() - guest_bounds.y()); guest_mouse_wheel_event.SetPositionInScreen( guest_mouse_wheel_event.PositionInWidget().x(), guest_mouse_wheel_event.PositionInWidget().y()); guest_host_view->SendMouseWheelEvent(guest_mouse_wheel_event); return; } } } } if (!render_widget_host_) return; render_widget_host_->ForwardWheelEvent(event); } void OffScreenRenderWidgetHostView::SetPainting(bool painting) { painting_ = painting; if (popup_host_view_) { popup_host_view_->SetPainting(painting); } for (auto* guest_host_view : guest_host_views_) guest_host_view->SetPainting(painting); if (video_consumer_) { video_consumer_->SetActive(IsPainting()); } else if (host_display_client_) { host_display_client_->SetActive(IsPainting()); } } bool OffScreenRenderWidgetHostView::IsPainting() const { return painting_; } void OffScreenRenderWidgetHostView::SetFrameRate(int frame_rate) { if (parent_host_view_) { if (parent_host_view_->GetFrameRate() == GetFrameRate()) return; frame_rate_ = parent_host_view_->GetFrameRate(); } else { if (frame_rate <= 0) frame_rate = 1; if (frame_rate > 240) frame_rate = 240; frame_rate_ = frame_rate; } SetupFrameRate(true); if (video_consumer_) { video_consumer_->SetFrameRate(GetFrameRate()); } for (auto* guest_host_view : guest_host_views_) guest_host_view->SetFrameRate(frame_rate); } int OffScreenRenderWidgetHostView::GetFrameRate() const { return frame_rate_; } ui::Layer* OffScreenRenderWidgetHostView::GetRootLayer() const { return root_layer_.get(); } const viz::LocalSurfaceId& OffScreenRenderWidgetHostView::GetLocalSurfaceId() const { return delegated_frame_host_surface_id_; } content::DelegatedFrameHost* OffScreenRenderWidgetHostView::GetDelegatedFrameHost() const { return delegated_frame_host_.get(); } void OffScreenRenderWidgetHostView::SetupFrameRate(bool force) { if (!force && frame_rate_threshold_us_ != 0) return; frame_rate_threshold_us_ = 1000000 / frame_rate_; if (compositor_) { compositor_->SetDisplayVSyncParameters( base::TimeTicks::Now(), base::Microseconds(frame_rate_threshold_us_)); } } void OffScreenRenderWidgetHostView::Invalidate() { InvalidateBounds(gfx::Rect(GetRequestedRendererSize())); } void OffScreenRenderWidgetHostView::InvalidateBounds(const gfx::Rect& bounds) { CompositeFrame(bounds); } void OffScreenRenderWidgetHostView::ResizeRootLayer(bool force) { SetupFrameRate(false); display::Display display = display::Screen::GetScreen()->GetDisplayNearestView(GetNativeView()); const float scaleFactor = display.device_scale_factor(); float sf = GetDeviceScaleFactor(); const bool scaleFactorDidChange = scaleFactor != sf; // Initialize a screen_infos_ struct as needed, to cache the scale factor. if (screen_infos_.screen_infos.empty()) { UpdateScreenInfo(); } screen_infos_.mutable_current().device_scale_factor = scaleFactor; gfx::Size size; if (!IsPopupWidget()) size = GetViewBounds().size(); else size = popup_position_.size(); if (!force && !scaleFactorDidChange && size == GetRootLayer()->bounds().size()) return; GetRootLayer()->SetBounds(gfx::Rect(size)); const gfx::Size& size_in_pixels = gfx::ToFlooredSize(gfx::ConvertSizeToPixels(size, sf)); if (compositor_) { compositor_allocator_.GenerateId(); compositor_surface_id_ = compositor_allocator_.GetCurrentLocalSurfaceId(); compositor_->SetScaleAndSize(sf, size_in_pixels, compositor_surface_id_); } delegated_frame_host_allocator_.GenerateId(); delegated_frame_host_surface_id_ = delegated_frame_host_allocator_.GetCurrentLocalSurfaceId(); GetDelegatedFrameHost()->EmbedSurface( delegated_frame_host_surface_id_, size, cc::DeadlinePolicy::UseDefaultDeadline()); // Note that |render_widget_host_| will retrieve resize parameters from the // DelegatedFrameHost, so it must have SynchronizeVisualProperties called // after. if (render_widget_host_) { render_widget_host_->SynchronizeVisualProperties(); } } viz::FrameSinkId OffScreenRenderWidgetHostView::AllocateFrameSinkId() { return viz::FrameSinkId( base::checked_cast<uint32_t>(render_widget_host_->GetProcess()->GetID()), base::checked_cast<uint32_t>(render_widget_host_->GetRoutingID())); } void OffScreenRenderWidgetHostView::UpdateBackgroundColorFromRenderer( SkColor color) { if (color == background_color_) return; background_color_ = color; bool opaque = SkColorGetA(color) == SK_AlphaOPAQUE; GetRootLayer()->SetFillsBoundsOpaquely(opaque); GetRootLayer()->SetColor(color); } void OffScreenRenderWidgetHostView::NotifyHostAndDelegateOnWasShown( blink::mojom::RecordContentToVisibleTimeRequestPtr) { NOTREACHED(); } void OffScreenRenderWidgetHostView::RequestPresentationTimeFromHostOrDelegate( blink::mojom::RecordContentToVisibleTimeRequestPtr) { NOTREACHED(); } void OffScreenRenderWidgetHostView:: CancelPresentationTimeRequestForHostAndDelegate() { NOTREACHED(); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
34,047
[Bug]: offscreen rendering doesn't render clicked INPUT SELECT dropdown
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 18.1.0 ### What operating system are you using? Ubuntu ### Operating System Version Ubuntu 20.04 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior Offscreen rendering paint events should receive events for SELECT input elements. ### Actual Behavior Sometimes an empty white box appears, or nothing happens. ### Testcase Gist URL https://gist.github.com/gtalusan/c0ad56685aeb3b2c1108fbccf6b451b4 ### Additional Information Here's a screenshot when the fiddle is run with `offscreen = false`: <img width="760" alt="Screen Shot 2022-05-03 at 9 54 42 AM" src="https://user-images.githubusercontent.com/355585/166471227-1e0e27b0-cc8b-4c8e-94e5-a4261e2437b6.png"> Here are the paint event images saved to PNGs when `offscreen = true`: ![0](https://user-images.githubusercontent.com/355585/166471435-209960eb-27e2-47f1-a758-1760a052f3d1.png) ![1](https://user-images.githubusercontent.com/355585/166471445-269fab98-f046-43d4-b72a-65a49c5bc067.png)
https://github.com/electron/electron/issues/34047
https://github.com/electron/electron/pull/34069
323f7d4c19b232ec5661d9d87fcecaf6918d8abf
90eb47f70ba0ba1b89933ba505f6cc8805411bcf
2022-05-03T14:23:00Z
c++
2022-05-05T13:53:39Z
shell/browser/osr/osr_render_widget_host_view.h
// Copyright (c) 2016 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_OSR_OSR_RENDER_WIDGET_HOST_VIEW_H_ #define ELECTRON_SHELL_BROWSER_OSR_OSR_RENDER_WIDGET_HOST_VIEW_H_ #include <memory> #include <set> #include <string> #include <vector> #include "build/build_config.h" #if BUILDFLAG(IS_WIN) #include <windows.h> #endif #include "base/process/kill.h" #include "base/threading/thread.h" #include "base/time/time.h" #include "components/viz/common/quads/compositor_frame.h" #include "components/viz/common/surfaces/parent_local_surface_id_allocator.h" #include "content/browser/renderer_host/delegated_frame_host.h" // nogncheck #include "content/browser/renderer_host/input/mouse_wheel_phase_handler.h" // nogncheck #include "content/browser/renderer_host/render_widget_host_impl.h" // nogncheck #include "content/browser/renderer_host/render_widget_host_view_base.h" // nogncheck #include "content/browser/web_contents/web_contents_view.h" // nogncheck #include "shell/browser/osr/osr_host_display_client.h" #include "shell/browser/osr/osr_video_consumer.h" #include "shell/browser/osr/osr_view_proxy.h" #include "third_party/blink/public/mojom/widget/record_content_to_visible_time_request.mojom-forward.h" #include "third_party/blink/public/platform/web_vector.h" #include "third_party/skia/include/core/SkBitmap.h" #include "ui/base/ime/text_input_client.h" #include "ui/compositor/compositor.h" #include "ui/compositor/layer_delegate.h" #include "ui/compositor/layer_owner.h" #include "ui/gfx/geometry/point.h" #include "components/viz/host/host_display_client.h" #if BUILDFLAG(IS_WIN) #include "ui/gfx/win/window_impl.h" #endif namespace content { class CursorManager; } namespace electron { class ElectronCopyFrameGenerator; class ElectronBeginFrameTimer; class ElectronDelegatedFrameHostClient; typedef base::RepeatingCallback<void(const gfx::Rect&, const SkBitmap&)> OnPaintCallback; typedef base::RepeatingCallback<void(const gfx::Rect&)> OnPopupPaintCallback; class OffScreenRenderWidgetHostView : public content::RenderWidgetHostViewBase, public ui::CompositorDelegate, public OffscreenViewProxyObserver { public: OffScreenRenderWidgetHostView(bool transparent, bool painting, int frame_rate, const OnPaintCallback& callback, content::RenderWidgetHost* render_widget_host, OffScreenRenderWidgetHostView* parent_host_view, gfx::Size initial_size); ~OffScreenRenderWidgetHostView() override; // disable copy OffScreenRenderWidgetHostView(const OffScreenRenderWidgetHostView&) = delete; OffScreenRenderWidgetHostView& operator=( const OffScreenRenderWidgetHostView&) = delete; // content::RenderWidgetHostView: void InitAsChild(gfx::NativeView) override; void SetSize(const gfx::Size&) override; void SetBounds(const gfx::Rect&) override; gfx::NativeView GetNativeView(void) override; gfx::NativeViewAccessible GetNativeViewAccessible(void) override; ui::TextInputClient* GetTextInputClient() override; void Focus(void) override; bool HasFocus(void) override; uint32_t GetCaptureSequenceNumber() const override; bool IsSurfaceAvailableForCopy(void) override; void Hide(void) override; bool IsShowing(void) override; void EnsureSurfaceSynchronizedForWebTest() override; gfx::Rect GetViewBounds(void) override; gfx::Size GetVisibleViewportSize() override; void SetInsets(const gfx::Insets&) override; void SetBackgroundColor(SkColor color) override; absl::optional<SkColor> GetBackgroundColor() override; void UpdateBackgroundColor() override; blink::mojom::PointerLockResult LockMouse( bool request_unadjusted_movement) override; blink::mojom::PointerLockResult ChangeMouseLock( bool request_unadjusted_movement) override; void UnlockMouse(void) override; void TakeFallbackContentFrom(content::RenderWidgetHostView* view) override; #if BUILDFLAG(IS_MAC) void SetActive(bool active) override; void ShowDefinitionForSelection() override; void SpeakSelection() override; void SetWindowFrameInScreen(const gfx::Rect& rect) override; void ShowSharePicker( const std::string& title, const std::string& text, const std::string& url, const std::vector<std::string>& file_paths, blink::mojom::ShareService::ShareCallback callback) override; bool UpdateNSViewAndDisplay(); #endif // BUILDFLAG(IS_MAC) // content::RenderWidgetHostViewBase: void ResetFallbackToFirstNavigationSurface() override; void InitAsPopup(content::RenderWidgetHostView* parent_host_view, const gfx::Rect& pos, const gfx::Rect& anchor_rect) override; void UpdateCursor(const content::WebCursor&) override; void SetIsLoading(bool is_loading) override; void TextInputStateChanged(const ui::mojom::TextInputState& params) override; void ImeCancelComposition(void) override; void RenderProcessGone() override; void ShowWithVisibility(content::PageVisibilityState page_visibility) final; void Destroy(void) override; void UpdateTooltipUnderCursor(const std::u16string&) override; content::CursorManager* GetCursorManager() override; void CopyFromSurface( const gfx::Rect& src_rect, const gfx::Size& output_size, base::OnceCallback<void(const SkBitmap&)> callback) override; display::ScreenInfo GetScreenInfo() const override; void TransformPointToRootSurface(gfx::PointF* point) override; gfx::Rect GetBoundsInRootWindow(void) override; absl::optional<content::DisplayFeature> GetDisplayFeature() override; void SetDisplayFeatureForTesting( const content::DisplayFeature* display_feature) override; void NotifyHostAndDelegateOnWasShown( blink::mojom::RecordContentToVisibleTimeRequestPtr) final; void RequestPresentationTimeFromHostOrDelegate( blink::mojom::RecordContentToVisibleTimeRequestPtr) final; void CancelPresentationTimeRequestForHostAndDelegate() final; viz::SurfaceId GetCurrentSurfaceId() const override; std::unique_ptr<content::SyntheticGestureTarget> CreateSyntheticGestureTarget() override; void ImeCompositionRangeChanged(const gfx::Range&, const std::vector<gfx::Rect>&) override; gfx::Size GetCompositorViewportPixelSize() override; ui::Compositor* GetCompositor() override; content::RenderWidgetHostViewBase* CreateViewForWidget( content::RenderWidgetHost*, content::RenderWidgetHost*, content::WebContentsView*) override; const viz::LocalSurfaceId& GetLocalSurfaceId() const override; const viz::FrameSinkId& GetFrameSinkId() const override; void DidNavigate() override; bool TransformPointToCoordSpaceForView( const gfx::PointF& point, RenderWidgetHostViewBase* target_view, gfx::PointF* transformed_point) override; // ui::CompositorDelegate: bool IsOffscreen() const override; std::unique_ptr<viz::HostDisplayClient> CreateHostDisplayClient( ui::Compositor* compositor) override; bool InstallTransparency(); void CancelWidget(); void AddGuestHostView(OffScreenRenderWidgetHostView* guest_host); void RemoveGuestHostView(OffScreenRenderWidgetHostView* guest_host); void AddViewProxy(OffscreenViewProxy* proxy); void RemoveViewProxy(OffscreenViewProxy* proxy); void ProxyViewDestroyed(OffscreenViewProxy* proxy) override; void OnPaint(const gfx::Rect& damage_rect, const SkBitmap& bitmap); void OnPopupPaint(const gfx::Rect& damage_rect); void OnProxyViewPaint(const gfx::Rect& damage_rect) override; gfx::Size SizeInPixels(); void CompositeFrame(const gfx::Rect& damage_rect); bool IsPopupWidget() const { return widget_type_ == content::WidgetType::kPopup; } const SkBitmap& GetBacking() { return *backing_.get(); } void HoldResize(); void ReleaseResize(); void SynchronizeVisualProperties(); void SendMouseEvent(const blink::WebMouseEvent& event); void SendMouseWheelEvent(const blink::WebMouseWheelEvent& event); void SetPainting(bool painting); bool IsPainting() const; void SetFrameRate(int frame_rate); int GetFrameRate() const; ui::Layer* GetRootLayer() const; content::DelegatedFrameHost* GetDelegatedFrameHost() const; void Invalidate(); void InvalidateBounds(const gfx::Rect&); content::RenderWidgetHostImpl* render_widget_host() const { return render_widget_host_; } gfx::Size size() const { return size_; } void set_popup_host_view(OffScreenRenderWidgetHostView* popup_view) { popup_host_view_ = popup_view; } void set_child_host_view(OffScreenRenderWidgetHostView* child_view) { child_host_view_ = child_view; } private: void SetupFrameRate(bool force); void ResizeRootLayer(bool force); viz::FrameSinkId AllocateFrameSinkId(); // Applies background color without notifying the RenderWidget about // opaqueness changes. void UpdateBackgroundColorFromRenderer(SkColor color); // Weak ptrs. content::RenderWidgetHostImpl* render_widget_host_; OffScreenRenderWidgetHostView* parent_host_view_ = nullptr; OffScreenRenderWidgetHostView* popup_host_view_ = nullptr; OffScreenRenderWidgetHostView* child_host_view_ = nullptr; std::set<OffScreenRenderWidgetHostView*> guest_host_views_; std::set<OffscreenViewProxy*> proxy_views_; const bool transparent_; OnPaintCallback callback_; OnPopupPaintCallback parent_callback_; int frame_rate_ = 0; int frame_rate_threshold_us_ = 0; base::Time last_time_ = base::Time::Now(); gfx::Vector2dF last_scroll_offset_; gfx::Size size_; bool painting_; bool is_showing_ = false; bool is_destroyed_ = false; gfx::Rect popup_position_; bool hold_resize_ = false; bool pending_resize_ = false; bool paint_callback_running_ = false; viz::LocalSurfaceId delegated_frame_host_surface_id_; viz::ParentLocalSurfaceIdAllocator delegated_frame_host_allocator_; viz::LocalSurfaceId compositor_surface_id_; viz::ParentLocalSurfaceIdAllocator compositor_allocator_; std::unique_ptr<ui::Layer> root_layer_; std::unique_ptr<ui::Compositor> compositor_; std::unique_ptr<content::DelegatedFrameHost> delegated_frame_host_; std::unique_ptr<content::CursorManager> cursor_manager_; OffScreenHostDisplayClient* host_display_client_; std::unique_ptr<OffScreenVideoConsumer> video_consumer_; std::unique_ptr<ElectronDelegatedFrameHostClient> delegated_frame_host_client_; content::MouseWheelPhaseHandler mouse_wheel_phase_handler_; // Latest capture sequence number which is incremented when the caller // requests surfaces be synchronized via // EnsureSurfaceSynchronizedForWebTest(). uint32_t latest_capture_sequence_number_ = 0u; SkColor background_color_ = SkColor(); std::unique_ptr<SkBitmap> backing_; base::WeakPtrFactory<OffScreenRenderWidgetHostView> weak_ptr_factory_{this}; }; } // namespace electron #endif // ELECTRON_SHELL_BROWSER_OSR_OSR_RENDER_WIDGET_HOST_VIEW_H_
closed
electron/electron
https://github.com/electron/electron
34,047
[Bug]: offscreen rendering doesn't render clicked INPUT SELECT dropdown
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 18.1.0 ### What operating system are you using? Ubuntu ### Operating System Version Ubuntu 20.04 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior Offscreen rendering paint events should receive events for SELECT input elements. ### Actual Behavior Sometimes an empty white box appears, or nothing happens. ### Testcase Gist URL https://gist.github.com/gtalusan/c0ad56685aeb3b2c1108fbccf6b451b4 ### Additional Information Here's a screenshot when the fiddle is run with `offscreen = false`: <img width="760" alt="Screen Shot 2022-05-03 at 9 54 42 AM" src="https://user-images.githubusercontent.com/355585/166471227-1e0e27b0-cc8b-4c8e-94e5-a4261e2437b6.png"> Here are the paint event images saved to PNGs when `offscreen = true`: ![0](https://user-images.githubusercontent.com/355585/166471435-209960eb-27e2-47f1-a758-1760a052f3d1.png) ![1](https://user-images.githubusercontent.com/355585/166471445-269fab98-f046-43d4-b72a-65a49c5bc067.png)
https://github.com/electron/electron/issues/34047
https://github.com/electron/electron/pull/34069
323f7d4c19b232ec5661d9d87fcecaf6918d8abf
90eb47f70ba0ba1b89933ba505f6cc8805411bcf
2022-05-03T14:23:00Z
c++
2022-05-05T13:53:39Z
shell/browser/osr/osr_video_consumer.cc
// Copyright (c) 2019 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/osr/osr_video_consumer.h" #include <utility> #include "media/base/video_frame_metadata.h" #include "media/capture/mojom/video_capture_buffer.mojom.h" #include "media/capture/mojom/video_capture_types.mojom.h" #include "services/viz/privileged/mojom/compositing/frame_sink_video_capture.mojom-shared.h" #include "shell/browser/osr/osr_render_widget_host_view.h" #include "ui/gfx/skbitmap_operations.h" namespace electron { OffScreenVideoConsumer::OffScreenVideoConsumer( OffScreenRenderWidgetHostView* view, OnPaintCallback callback) : callback_(callback), view_(view), video_capturer_(view->CreateVideoCapturer()) { video_capturer_->SetResolutionConstraints(view_->SizeInPixels(), view_->SizeInPixels(), true); video_capturer_->SetAutoThrottlingEnabled(false); video_capturer_->SetMinSizeChangePeriod(base::TimeDelta()); video_capturer_->SetFormat(media::PIXEL_FORMAT_ARGB); SetFrameRate(view_->GetFrameRate()); } OffScreenVideoConsumer::~OffScreenVideoConsumer() = default; void OffScreenVideoConsumer::SetActive(bool active) { if (active) { video_capturer_->Start(this, viz::mojom::BufferFormatPreference::kDefault); } else { video_capturer_->Stop(); } } void OffScreenVideoConsumer::SetFrameRate(int frame_rate) { video_capturer_->SetMinCapturePeriod(base::Seconds(1) / frame_rate); } void OffScreenVideoConsumer::SizeChanged() { video_capturer_->SetResolutionConstraints(view_->SizeInPixels(), view_->SizeInPixels(), true); video_capturer_->RequestRefreshFrame(); } void OffScreenVideoConsumer::OnFrameCaptured( ::media::mojom::VideoBufferHandlePtr data, ::media::mojom::VideoFrameInfoPtr info, const gfx::Rect& content_rect, mojo::PendingRemote<viz::mojom::FrameSinkVideoConsumerFrameCallbacks> callbacks) { auto& data_region = data->get_read_only_shmem_region(); if (!CheckContentRect(content_rect)) { gfx::Size view_size = view_->SizeInPixels(); video_capturer_->SetResolutionConstraints(view_size, view_size, true); video_capturer_->RequestRefreshFrame(); return; } mojo::Remote<viz::mojom::FrameSinkVideoConsumerFrameCallbacks> callbacks_remote(std::move(callbacks)); if (!data_region.IsValid()) { callbacks_remote->Done(); return; } base::ReadOnlySharedMemoryMapping mapping = data_region.Map(); if (!mapping.IsValid()) { DLOG(ERROR) << "Shared memory mapping failed."; callbacks_remote->Done(); return; } if (mapping.size() < media::VideoFrame::AllocationSize(info->pixel_format, info->coded_size)) { DLOG(ERROR) << "Shared memory size was less than expected."; callbacks_remote->Done(); return; } // The SkBitmap's pixels will be marked as immutable, but the installPixels() // API requires a non-const pointer. So, cast away the const. void* const pixels = const_cast<void*>(mapping.memory()); // Call installPixels() with a |releaseProc| that: 1) notifies the capturer // that this consumer has finished with the frame, and 2) releases the shared // memory mapping. struct FramePinner { // Keeps the shared memory that backs |frame_| mapped. base::ReadOnlySharedMemoryMapping mapping; // Prevents FrameSinkVideoCapturer from recycling the shared memory that // backs |frame_|. mojo::PendingRemote<viz::mojom::FrameSinkVideoConsumerFrameCallbacks> releaser; }; SkBitmap bitmap; bitmap.installPixels( SkImageInfo::MakeN32(content_rect.width(), content_rect.height(), kPremul_SkAlphaType), pixels, media::VideoFrame::RowBytes(media::VideoFrame::kARGBPlane, info->pixel_format, info->coded_size.width()), [](void* addr, void* context) { delete static_cast<FramePinner*>(context); }, new FramePinner{std::move(mapping), callbacks_remote.Unbind()}); bitmap.setImmutable(); absl::optional<gfx::Rect> update_rect = info->metadata.capture_update_rect; if (!update_rect.has_value() || update_rect->IsEmpty()) { update_rect = content_rect; } callback_.Run(*update_rect, bitmap); } void OffScreenVideoConsumer::OnFrameWithEmptyRegionCapture() {} void OffScreenVideoConsumer::OnStopped() {} void OffScreenVideoConsumer::OnLog(const std::string& message) {} bool OffScreenVideoConsumer::CheckContentRect(const gfx::Rect& content_rect) { gfx::Size view_size = view_->SizeInPixels(); gfx::Size content_size = content_rect.size(); if (std::abs(view_size.width() - content_size.width()) > 2) { return false; } if (std::abs(view_size.height() - content_size.height()) > 2) { return false; } return true; } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
34,047
[Bug]: offscreen rendering doesn't render clicked INPUT SELECT dropdown
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 18.1.0 ### What operating system are you using? Ubuntu ### Operating System Version Ubuntu 20.04 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior Offscreen rendering paint events should receive events for SELECT input elements. ### Actual Behavior Sometimes an empty white box appears, or nothing happens. ### Testcase Gist URL https://gist.github.com/gtalusan/c0ad56685aeb3b2c1108fbccf6b451b4 ### Additional Information Here's a screenshot when the fiddle is run with `offscreen = false`: <img width="760" alt="Screen Shot 2022-05-03 at 9 54 42 AM" src="https://user-images.githubusercontent.com/355585/166471227-1e0e27b0-cc8b-4c8e-94e5-a4261e2437b6.png"> Here are the paint event images saved to PNGs when `offscreen = true`: ![0](https://user-images.githubusercontent.com/355585/166471435-209960eb-27e2-47f1-a758-1760a052f3d1.png) ![1](https://user-images.githubusercontent.com/355585/166471445-269fab98-f046-43d4-b72a-65a49c5bc067.png)
https://github.com/electron/electron/issues/34047
https://github.com/electron/electron/pull/34069
323f7d4c19b232ec5661d9d87fcecaf6918d8abf
90eb47f70ba0ba1b89933ba505f6cc8805411bcf
2022-05-03T14:23:00Z
c++
2022-05-05T13:53:39Z
shell/browser/osr/osr_video_consumer.h
// Copyright (c) 2019 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_OSR_OSR_VIDEO_CONSUMER_H_ #define ELECTRON_SHELL_BROWSER_OSR_OSR_VIDEO_CONSUMER_H_ #include <memory> #include <string> #include "base/callback.h" #include "base/memory/weak_ptr.h" #include "components/viz/host/client_frame_sink_video_capturer.h" #include "media/capture/mojom/video_capture_buffer.mojom-forward.h" #include "media/capture/mojom/video_capture_types.mojom.h" namespace electron { class OffScreenRenderWidgetHostView; typedef base::RepeatingCallback<void(const gfx::Rect&, const SkBitmap&)> OnPaintCallback; class OffScreenVideoConsumer : public viz::mojom::FrameSinkVideoConsumer { public: OffScreenVideoConsumer(OffScreenRenderWidgetHostView* view, OnPaintCallback callback); ~OffScreenVideoConsumer() override; // disable copy OffScreenVideoConsumer(const OffScreenVideoConsumer&) = delete; OffScreenVideoConsumer& operator=(const OffScreenVideoConsumer&) = delete; void SetActive(bool active); void SetFrameRate(int frame_rate); void SizeChanged(); private: // viz::mojom::FrameSinkVideoConsumer implementation. void OnFrameCaptured( ::media::mojom::VideoBufferHandlePtr data, ::media::mojom::VideoFrameInfoPtr info, const gfx::Rect& content_rect, mojo::PendingRemote<viz::mojom::FrameSinkVideoConsumerFrameCallbacks> callbacks) override; void OnFrameWithEmptyRegionCapture() override; void OnStopped() override; void OnLog(const std::string& message) override; bool CheckContentRect(const gfx::Rect& content_rect); OnPaintCallback callback_; OffScreenRenderWidgetHostView* view_; std::unique_ptr<viz::ClientFrameSinkVideoCapturer> video_capturer_; base::WeakPtrFactory<OffScreenVideoConsumer> weak_ptr_factory_{this}; }; } // namespace electron #endif // ELECTRON_SHELL_BROWSER_OSR_OSR_VIDEO_CONSUMER_H_
closed
electron/electron
https://github.com/electron/electron
34,047
[Bug]: offscreen rendering doesn't render clicked INPUT SELECT dropdown
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 18.1.0 ### What operating system are you using? Ubuntu ### Operating System Version Ubuntu 20.04 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior Offscreen rendering paint events should receive events for SELECT input elements. ### Actual Behavior Sometimes an empty white box appears, or nothing happens. ### Testcase Gist URL https://gist.github.com/gtalusan/c0ad56685aeb3b2c1108fbccf6b451b4 ### Additional Information Here's a screenshot when the fiddle is run with `offscreen = false`: <img width="760" alt="Screen Shot 2022-05-03 at 9 54 42 AM" src="https://user-images.githubusercontent.com/355585/166471227-1e0e27b0-cc8b-4c8e-94e5-a4261e2437b6.png"> Here are the paint event images saved to PNGs when `offscreen = true`: ![0](https://user-images.githubusercontent.com/355585/166471435-209960eb-27e2-47f1-a758-1760a052f3d1.png) ![1](https://user-images.githubusercontent.com/355585/166471445-269fab98-f046-43d4-b72a-65a49c5bc067.png)
https://github.com/electron/electron/issues/34047
https://github.com/electron/electron/pull/34069
323f7d4c19b232ec5661d9d87fcecaf6918d8abf
90eb47f70ba0ba1b89933ba505f6cc8805411bcf
2022-05-03T14:23:00Z
c++
2022-05-05T13:53:39Z
shell/browser/osr/osr_render_widget_host_view.cc
// Copyright (c) 2016 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/osr/osr_render_widget_host_view.h" #include <algorithm> #include <memory> #include <utility> #include <vector> #include "base/callback_helpers.h" #include "base/location.h" #include "base/memory/ptr_util.h" #include "base/task/post_task.h" #include "base/task/single_thread_task_runner.h" #include "base/time/time.h" #include "components/viz/common/features.h" #include "components/viz/common/frame_sinks/begin_frame_args.h" #include "components/viz/common/frame_sinks/copy_output_request.h" #include "components/viz/common/frame_sinks/delay_based_time_source.h" #include "components/viz/common/quads/compositor_render_pass.h" #include "content/browser/renderer_host/cursor_manager.h" // nogncheck #include "content/browser/renderer_host/input/synthetic_gesture_target.h" // nogncheck #include "content/browser/renderer_host/render_widget_host_delegate.h" // nogncheck #include "content/browser/renderer_host/render_widget_host_owner_delegate.h" // nogncheck #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/context_factory.h" #include "content/public/browser/gpu_data_manager.h" #include "content/public/browser/render_process_host.h" #include "gpu/command_buffer/client/gl_helper.h" #include "media/base/video_frame.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "third_party/blink/public/common/input/web_input_event.h" #include "third_party/skia/include/core/SkCanvas.h" #include "ui/compositor/compositor.h" #include "ui/compositor/layer.h" #include "ui/compositor/layer_type.h" #include "ui/display/screen.h" #include "ui/events/base_event_utils.h" #include "ui/events/event_constants.h" #include "ui/gfx/canvas.h" #include "ui/gfx/geometry/dip_util.h" #include "ui/gfx/geometry/size_conversions.h" #include "ui/gfx/image/image_skia.h" #include "ui/gfx/native_widget_types.h" #include "ui/gfx/skbitmap_operations.h" #include "ui/latency/latency_info.h" namespace electron { namespace { const float kDefaultScaleFactor = 1.0; ui::MouseEvent UiMouseEventFromWebMouseEvent(blink::WebMouseEvent event) { ui::EventType type = ui::EventType::ET_UNKNOWN; switch (event.GetType()) { case blink::WebInputEvent::Type::kMouseDown: type = ui::EventType::ET_MOUSE_PRESSED; break; case blink::WebInputEvent::Type::kMouseUp: type = ui::EventType::ET_MOUSE_RELEASED; break; case blink::WebInputEvent::Type::kMouseMove: type = ui::EventType::ET_MOUSE_MOVED; break; case blink::WebInputEvent::Type::kMouseEnter: type = ui::EventType::ET_MOUSE_ENTERED; break; case blink::WebInputEvent::Type::kMouseLeave: type = ui::EventType::ET_MOUSE_EXITED; break; case blink::WebInputEvent::Type::kMouseWheel: type = ui::EventType::ET_MOUSEWHEEL; break; default: type = ui::EventType::ET_UNKNOWN; break; } int button_flags = 0; switch (event.button) { case blink::WebMouseEvent::Button::kBack: button_flags |= ui::EventFlags::EF_BACK_MOUSE_BUTTON; break; case blink::WebMouseEvent::Button::kForward: button_flags |= ui::EventFlags::EF_FORWARD_MOUSE_BUTTON; break; case blink::WebMouseEvent::Button::kLeft: button_flags |= ui::EventFlags::EF_LEFT_MOUSE_BUTTON; break; case blink::WebMouseEvent::Button::kMiddle: button_flags |= ui::EventFlags::EF_MIDDLE_MOUSE_BUTTON; break; case blink::WebMouseEvent::Button::kRight: button_flags |= ui::EventFlags::EF_RIGHT_MOUSE_BUTTON; break; default: button_flags = 0; break; } ui::MouseEvent ui_event(type, gfx::Point(std::floor(event.PositionInWidget().x()), std::floor(event.PositionInWidget().y())), gfx::Point(std::floor(event.PositionInWidget().x()), std::floor(event.PositionInWidget().y())), ui::EventTimeForNow(), button_flags, button_flags); ui_event.SetClickCount(event.click_count); return ui_event; } ui::MouseWheelEvent UiMouseWheelEventFromWebMouseEvent( blink::WebMouseWheelEvent event) { return ui::MouseWheelEvent(UiMouseEventFromWebMouseEvent(event), std::floor(event.delta_x), std::floor(event.delta_y)); } } // namespace class ElectronDelegatedFrameHostClient : public content::DelegatedFrameHostClient { public: explicit ElectronDelegatedFrameHostClient(OffScreenRenderWidgetHostView* view) : view_(view) {} // disable copy ElectronDelegatedFrameHostClient(const ElectronDelegatedFrameHostClient&) = delete; ElectronDelegatedFrameHostClient& operator=( const ElectronDelegatedFrameHostClient&) = delete; ui::Layer* DelegatedFrameHostGetLayer() const override { return view_->GetRootLayer(); } bool DelegatedFrameHostIsVisible() const override { return view_->IsShowing(); } SkColor DelegatedFrameHostGetGutterColor() const override { if (view_->render_widget_host()->delegate() && view_->render_widget_host()->delegate()->IsFullscreen()) { return SK_ColorWHITE; } return *view_->GetBackgroundColor(); } void OnFrameTokenChanged(uint32_t frame_token, base::TimeTicks activation_time) override { view_->render_widget_host()->DidProcessFrame(frame_token, activation_time); } float GetDeviceScaleFactor() const override { return view_->GetDeviceScaleFactor(); } std::vector<viz::SurfaceId> CollectSurfaceIdsForEviction() override { return view_->render_widget_host()->CollectSurfaceIdsForEviction(); } bool ShouldShowStaleContentOnEviction() override { return false; } void InvalidateLocalSurfaceIdOnEviction() override {} private: OffScreenRenderWidgetHostView* const view_; }; OffScreenRenderWidgetHostView::OffScreenRenderWidgetHostView( bool transparent, bool painting, int frame_rate, const OnPaintCallback& callback, content::RenderWidgetHost* host, OffScreenRenderWidgetHostView* parent_host_view, gfx::Size initial_size) : content::RenderWidgetHostViewBase(host), render_widget_host_(content::RenderWidgetHostImpl::From(host)), parent_host_view_(parent_host_view), transparent_(transparent), callback_(callback), frame_rate_(frame_rate), size_(initial_size), painting_(painting), cursor_manager_(std::make_unique<content::CursorManager>(this)), mouse_wheel_phase_handler_(this), backing_(std::make_unique<SkBitmap>()) { DCHECK(render_widget_host_); DCHECK(!render_widget_host_->GetView()); // Initialize a screen_infos_ struct as needed, to cache the scale factor. if (screen_infos_.screen_infos.empty()) { UpdateScreenInfo(); } screen_infos_.mutable_current().device_scale_factor = kDefaultScaleFactor; delegated_frame_host_allocator_.GenerateId(); delegated_frame_host_surface_id_ = delegated_frame_host_allocator_.GetCurrentLocalSurfaceId(); compositor_allocator_.GenerateId(); compositor_surface_id_ = compositor_allocator_.GetCurrentLocalSurfaceId(); delegated_frame_host_client_ = std::make_unique<ElectronDelegatedFrameHostClient>(this); delegated_frame_host_ = std::make_unique<content::DelegatedFrameHost>( AllocateFrameSinkId(), delegated_frame_host_client_.get(), true /* should_register_frame_sink_id */); root_layer_ = std::make_unique<ui::Layer>(ui::LAYER_SOLID_COLOR); bool opaque = SkColorGetA(background_color_) == SK_AlphaOPAQUE; GetRootLayer()->SetFillsBoundsOpaquely(opaque); GetRootLayer()->SetColor(background_color_); ui::ContextFactory* context_factory = content::GetContextFactory(); compositor_ = std::make_unique<ui::Compositor>( context_factory->AllocateFrameSinkId(), context_factory, base::ThreadTaskRunnerHandle::Get(), false /* enable_pixel_canvas */, false /* use_external_begin_frame_control */); compositor_->SetAcceleratedWidget(gfx::kNullAcceleratedWidget); compositor_->SetDelegate(this); compositor_->SetRootLayer(root_layer_.get()); ResizeRootLayer(false); render_widget_host_->SetView(this); if (content::GpuDataManager::GetInstance()->HardwareAccelerationEnabled()) { video_consumer_ = std::make_unique<OffScreenVideoConsumer>( this, base::BindRepeating(&OffScreenRenderWidgetHostView::OnPaint, weak_ptr_factory_.GetWeakPtr())); video_consumer_->SetActive(IsPainting()); video_consumer_->SetFrameRate(GetFrameRate()); } } OffScreenRenderWidgetHostView::~OffScreenRenderWidgetHostView() { // Marking the DelegatedFrameHost as removed from the window hierarchy is // necessary to remove all connections to its old ui::Compositor. if (is_showing_) delegated_frame_host_->WasHidden( content::DelegatedFrameHost::HiddenCause::kOther); delegated_frame_host_->DetachFromCompositor(); delegated_frame_host_.reset(); compositor_.reset(); root_layer_.reset(); } void OffScreenRenderWidgetHostView::InitAsChild(gfx::NativeView) { DCHECK(parent_host_view_); if (parent_host_view_->child_host_view_) { parent_host_view_->child_host_view_->CancelWidget(); } parent_host_view_->set_child_host_view(this); parent_host_view_->Hide(); ResizeRootLayer(false); SetPainting(parent_host_view_->IsPainting()); } void OffScreenRenderWidgetHostView::SetSize(const gfx::Size& size) { size_ = size; SynchronizeVisualProperties(); } void OffScreenRenderWidgetHostView::SetBounds(const gfx::Rect& new_bounds) { SetSize(new_bounds.size()); } gfx::NativeView OffScreenRenderWidgetHostView::GetNativeView() { return gfx::NativeView(); } gfx::NativeViewAccessible OffScreenRenderWidgetHostView::GetNativeViewAccessible() { return gfx::NativeViewAccessible(); } ui::TextInputClient* OffScreenRenderWidgetHostView::GetTextInputClient() { return nullptr; } void OffScreenRenderWidgetHostView::Focus() {} bool OffScreenRenderWidgetHostView::HasFocus() { return false; } bool OffScreenRenderWidgetHostView::IsSurfaceAvailableForCopy() { return GetDelegatedFrameHost()->CanCopyFromCompositingSurface(); } void OffScreenRenderWidgetHostView::ShowWithVisibility( content::PageVisibilityState /*page_visibility*/) { if (is_showing_) return; is_showing_ = true; delegated_frame_host_->AttachToCompositor(compositor_.get()); delegated_frame_host_->WasShown(GetLocalSurfaceId(), GetRootLayer()->bounds().size(), {}); if (render_widget_host_) render_widget_host_->WasShown({}); } void OffScreenRenderWidgetHostView::Hide() { if (!is_showing_) return; if (render_widget_host_) render_widget_host_->WasHidden(); // TODO(deermichel): correct or kOther? GetDelegatedFrameHost()->WasHidden( content::DelegatedFrameHost::HiddenCause::kOccluded); GetDelegatedFrameHost()->DetachFromCompositor(); is_showing_ = false; } bool OffScreenRenderWidgetHostView::IsShowing() { return is_showing_; } void OffScreenRenderWidgetHostView::EnsureSurfaceSynchronizedForWebTest() { ++latest_capture_sequence_number_; SynchronizeVisualProperties(); } gfx::Rect OffScreenRenderWidgetHostView::GetViewBounds() { if (IsPopupWidget()) return popup_position_; return gfx::Rect(size_); } void OffScreenRenderWidgetHostView::SetBackgroundColor(SkColor color) { // The renderer will feed its color back to us with the first CompositorFrame. // We short-cut here to show a sensible color before that happens. UpdateBackgroundColorFromRenderer(color); if (render_widget_host_ && render_widget_host_->owner_delegate()) { render_widget_host_->owner_delegate()->SetBackgroundOpaque( SkColorGetA(color) == SK_AlphaOPAQUE); } } absl::optional<SkColor> OffScreenRenderWidgetHostView::GetBackgroundColor() { return background_color_; } void OffScreenRenderWidgetHostView::UpdateBackgroundColor() {} gfx::Size OffScreenRenderWidgetHostView::GetVisibleViewportSize() { return size_; } void OffScreenRenderWidgetHostView::SetInsets(const gfx::Insets& insets) {} blink::mojom::PointerLockResult OffScreenRenderWidgetHostView::LockMouse( bool request_unadjusted_movement) { return blink::mojom::PointerLockResult::kUnsupportedOptions; } blink::mojom::PointerLockResult OffScreenRenderWidgetHostView::ChangeMouseLock( bool request_unadjusted_movement) { return blink::mojom::PointerLockResult::kUnsupportedOptions; } void OffScreenRenderWidgetHostView::UnlockMouse() {} void OffScreenRenderWidgetHostView::TakeFallbackContentFrom( content::RenderWidgetHostView* view) { DCHECK(!static_cast<content::RenderWidgetHostViewBase*>(view) ->IsRenderWidgetHostViewChildFrame()); auto* view_osr = static_cast<OffScreenRenderWidgetHostView*>(view); SetBackgroundColor(view_osr->background_color_); if (GetDelegatedFrameHost() && view_osr->GetDelegatedFrameHost()) { GetDelegatedFrameHost()->TakeFallbackContentFrom( view_osr->GetDelegatedFrameHost()); } host()->GetContentRenderingTimeoutFrom(view_osr->host()); } void OffScreenRenderWidgetHostView::ResetFallbackToFirstNavigationSurface() { GetDelegatedFrameHost()->ResetFallbackToFirstNavigationSurface(); } void OffScreenRenderWidgetHostView::InitAsPopup( content::RenderWidgetHostView* parent_host_view, const gfx::Rect& pos, const gfx::Rect& anchor_rect) { DCHECK_EQ(parent_host_view_, parent_host_view); DCHECK_EQ(widget_type_, content::WidgetType::kPopup); if (parent_host_view_->popup_host_view_) { parent_host_view_->popup_host_view_->CancelWidget(); } parent_host_view_->set_popup_host_view(this); parent_callback_ = base::BindRepeating(&OffScreenRenderWidgetHostView::OnPopupPaint, parent_host_view_->weak_ptr_factory_.GetWeakPtr()); popup_position_ = pos; ResizeRootLayer(false); SetPainting(parent_host_view_->IsPainting()); if (video_consumer_) { video_consumer_->SizeChanged(); } Show(); } void OffScreenRenderWidgetHostView::UpdateCursor(const content::WebCursor&) {} content::CursorManager* OffScreenRenderWidgetHostView::GetCursorManager() { return cursor_manager_.get(); } void OffScreenRenderWidgetHostView::SetIsLoading(bool loading) {} void OffScreenRenderWidgetHostView::TextInputStateChanged( const ui::mojom::TextInputState& params) {} void OffScreenRenderWidgetHostView::ImeCancelComposition() {} void OffScreenRenderWidgetHostView::RenderProcessGone() { Destroy(); } void OffScreenRenderWidgetHostView::Destroy() { if (!is_destroyed_) { is_destroyed_ = true; if (parent_host_view_ != nullptr) { CancelWidget(); } else { if (popup_host_view_) popup_host_view_->CancelWidget(); if (child_host_view_) child_host_view_->CancelWidget(); if (!guest_host_views_.empty()) { // Guest RWHVs will be destroyed when the associated RWHVGuest is // destroyed. This parent RWHV may be destroyed first, so disassociate // the guest RWHVs here without destroying them. for (auto* guest_host_view : guest_host_views_) guest_host_view->parent_host_view_ = nullptr; guest_host_views_.clear(); } for (auto* proxy_view : proxy_views_) proxy_view->RemoveObserver(); Hide(); } } delete this; } void OffScreenRenderWidgetHostView::UpdateTooltipUnderCursor( const std::u16string&) {} uint32_t OffScreenRenderWidgetHostView::GetCaptureSequenceNumber() const { return latest_capture_sequence_number_; } void OffScreenRenderWidgetHostView::CopyFromSurface( const gfx::Rect& src_rect, const gfx::Size& output_size, base::OnceCallback<void(const SkBitmap&)> callback) { GetDelegatedFrameHost()->CopyFromCompositingSurface(src_rect, output_size, std::move(callback)); } display::ScreenInfo OffScreenRenderWidgetHostView::GetScreenInfo() const { display::ScreenInfo screen_info; screen_info.depth = 24; screen_info.depth_per_component = 8; screen_info.orientation_angle = 0; screen_info.device_scale_factor = GetDeviceScaleFactor(); screen_info.orientation_type = display::mojom::ScreenOrientation::kLandscapePrimary; screen_info.rect = gfx::Rect(size_); screen_info.available_rect = gfx::Rect(size_); return screen_info; } void OffScreenRenderWidgetHostView::TransformPointToRootSurface( gfx::PointF* point) {} gfx::Rect OffScreenRenderWidgetHostView::GetBoundsInRootWindow() { return gfx::Rect(size_); } absl::optional<content::DisplayFeature> OffScreenRenderWidgetHostView::GetDisplayFeature() { return absl::nullopt; } void OffScreenRenderWidgetHostView::SetDisplayFeatureForTesting( const content::DisplayFeature* display_feature) {} viz::SurfaceId OffScreenRenderWidgetHostView::GetCurrentSurfaceId() const { return GetDelegatedFrameHost() ? GetDelegatedFrameHost()->GetCurrentSurfaceId() : viz::SurfaceId(); } std::unique_ptr<content::SyntheticGestureTarget> OffScreenRenderWidgetHostView::CreateSyntheticGestureTarget() { NOTIMPLEMENTED(); return nullptr; } void OffScreenRenderWidgetHostView::ImeCompositionRangeChanged( const gfx::Range&, const std::vector<gfx::Rect>&) {} gfx::Size OffScreenRenderWidgetHostView::GetCompositorViewportPixelSize() { return gfx::ScaleToCeiledSize(GetRequestedRendererSize(), GetDeviceScaleFactor()); } ui::Compositor* OffScreenRenderWidgetHostView::GetCompositor() { return compositor_.get(); } content::RenderWidgetHostViewBase* OffScreenRenderWidgetHostView::CreateViewForWidget( content::RenderWidgetHost* render_widget_host, content::RenderWidgetHost* embedder_render_widget_host, content::WebContentsView* web_contents_view) { if (render_widget_host->GetView()) { return static_cast<content::RenderWidgetHostViewBase*>( render_widget_host->GetView()); } OffScreenRenderWidgetHostView* embedder_host_view = nullptr; if (embedder_render_widget_host) { embedder_host_view = static_cast<OffScreenRenderWidgetHostView*>( embedder_render_widget_host->GetView()); } return new OffScreenRenderWidgetHostView( transparent_, true, embedder_host_view->GetFrameRate(), callback_, render_widget_host, embedder_host_view, size()); } const viz::FrameSinkId& OffScreenRenderWidgetHostView::GetFrameSinkId() const { return GetDelegatedFrameHost()->frame_sink_id(); } void OffScreenRenderWidgetHostView::DidNavigate() { ResizeRootLayer(true); if (delegated_frame_host_) delegated_frame_host_->DidNavigate(); } bool OffScreenRenderWidgetHostView::TransformPointToCoordSpaceForView( const gfx::PointF& point, RenderWidgetHostViewBase* target_view, gfx::PointF* transformed_point) { if (target_view == this) { *transformed_point = point; return true; } return false; } void OffScreenRenderWidgetHostView::CancelWidget() { if (render_widget_host_) render_widget_host_->LostCapture(); Hide(); if (parent_host_view_) { if (parent_host_view_->popup_host_view_ == this) { parent_host_view_->set_popup_host_view(nullptr); } else if (parent_host_view_->child_host_view_ == this) { parent_host_view_->set_child_host_view(nullptr); parent_host_view_->Show(); } else { parent_host_view_->RemoveGuestHostView(this); } parent_host_view_ = nullptr; } if (render_widget_host_ && !is_destroyed_) { is_destroyed_ = true; // Results in a call to Destroy(). render_widget_host_->ShutdownAndDestroyWidget(true); } } void OffScreenRenderWidgetHostView::AddGuestHostView( OffScreenRenderWidgetHostView* guest_host) { guest_host_views_.insert(guest_host); } void OffScreenRenderWidgetHostView::RemoveGuestHostView( OffScreenRenderWidgetHostView* guest_host) { guest_host_views_.erase(guest_host); } void OffScreenRenderWidgetHostView::AddViewProxy(OffscreenViewProxy* proxy) { proxy->SetObserver(this); proxy_views_.insert(proxy); } void OffScreenRenderWidgetHostView::RemoveViewProxy(OffscreenViewProxy* proxy) { proxy->RemoveObserver(); proxy_views_.erase(proxy); } void OffScreenRenderWidgetHostView::ProxyViewDestroyed( OffscreenViewProxy* proxy) { proxy_views_.erase(proxy); Invalidate(); } bool OffScreenRenderWidgetHostView::IsOffscreen() const { return true; } std::unique_ptr<viz::HostDisplayClient> OffScreenRenderWidgetHostView::CreateHostDisplayClient( ui::Compositor* compositor) { host_display_client_ = new OffScreenHostDisplayClient( gfx::kNullAcceleratedWidget, base::BindRepeating(&OffScreenRenderWidgetHostView::OnPaint, weak_ptr_factory_.GetWeakPtr())); host_display_client_->SetActive(IsPainting()); return base::WrapUnique(host_display_client_); } bool OffScreenRenderWidgetHostView::InstallTransparency() { if (transparent_) { SetBackgroundColor(SkColor()); compositor_->SetBackgroundColor(SK_ColorTRANSPARENT); return true; } return false; } #if BUILDFLAG(IS_MAC) void OffScreenRenderWidgetHostView::SetActive(bool active) {} void OffScreenRenderWidgetHostView::ShowDefinitionForSelection() {} void OffScreenRenderWidgetHostView::SpeakSelection() {} void OffScreenRenderWidgetHostView::SetWindowFrameInScreen( const gfx::Rect& rect) {} void OffScreenRenderWidgetHostView::ShowSharePicker( const std::string& title, const std::string& text, const std::string& url, const std::vector<std::string>& file_paths, blink::mojom::ShareService::ShareCallback callback) {} bool OffScreenRenderWidgetHostView::UpdateNSViewAndDisplay() { return false; } #endif void OffScreenRenderWidgetHostView::OnPaint(const gfx::Rect& damage_rect, const SkBitmap& bitmap) { backing_ = std::make_unique<SkBitmap>(); backing_->allocN32Pixels(bitmap.width(), bitmap.height(), !transparent_); bitmap.readPixels(backing_->pixmap()); if (IsPopupWidget() && parent_callback_) { parent_callback_.Run(this->popup_position_); } else { CompositeFrame(damage_rect); } } gfx::Size OffScreenRenderWidgetHostView::SizeInPixels() { float sf = GetDeviceScaleFactor(); if (IsPopupWidget()) { return gfx::ToFlooredSize( gfx::ConvertSizeToPixels(popup_position_.size(), sf)); } else { return gfx::ToFlooredSize( gfx::ConvertSizeToPixels(GetViewBounds().size(), sf)); } } void OffScreenRenderWidgetHostView::CompositeFrame( const gfx::Rect& damage_rect) { HoldResize(); gfx::Size size_in_pixels = SizeInPixels(); SkBitmap frame; // Optimize for the case when there is no popup if (proxy_views_.empty() && !popup_host_view_) { frame = GetBacking(); } else { float sf = GetDeviceScaleFactor(); frame.allocN32Pixels(size_in_pixels.width(), size_in_pixels.height(), false); if (!GetBacking().drawsNothing()) { SkCanvas canvas(frame); canvas.writePixels(GetBacking(), 0, 0); if (popup_host_view_ && !popup_host_view_->GetBacking().drawsNothing()) { gfx::Rect rect = popup_host_view_->popup_position_; gfx::Point origin_in_pixels = gfx::ToFlooredPoint(gfx::ConvertPointToPixels(rect.origin(), sf)); canvas.writePixels(popup_host_view_->GetBacking(), origin_in_pixels.x(), origin_in_pixels.y()); } for (auto* proxy_view : proxy_views_) { gfx::Rect rect = proxy_view->GetBounds(); gfx::Point origin_in_pixels = gfx::ToFlooredPoint(gfx::ConvertPointToPixels(rect.origin(), sf)); canvas.writePixels(*proxy_view->GetBitmap(), origin_in_pixels.x(), origin_in_pixels.y()); } } } paint_callback_running_ = true; callback_.Run(gfx::IntersectRects(gfx::Rect(size_in_pixels), damage_rect), frame); paint_callback_running_ = false; ReleaseResize(); } void OffScreenRenderWidgetHostView::OnPopupPaint(const gfx::Rect& damage_rect) { InvalidateBounds(gfx::ToEnclosingRect( gfx::ConvertRectToPixels(damage_rect, GetDeviceScaleFactor()))); } void OffScreenRenderWidgetHostView::OnProxyViewPaint( const gfx::Rect& damage_rect) { InvalidateBounds(gfx::ToEnclosingRect( gfx::ConvertRectToPixels(damage_rect, GetDeviceScaleFactor()))); } void OffScreenRenderWidgetHostView::HoldResize() { if (!hold_resize_) hold_resize_ = true; } void OffScreenRenderWidgetHostView::ReleaseResize() { if (!hold_resize_) return; hold_resize_ = false; if (pending_resize_) { pending_resize_ = false; base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce( &OffScreenRenderWidgetHostView::SynchronizeVisualProperties, weak_ptr_factory_.GetWeakPtr())); } } void OffScreenRenderWidgetHostView::SynchronizeVisualProperties() { if (hold_resize_) { if (!pending_resize_) pending_resize_ = true; return; } ResizeRootLayer(true); } void OffScreenRenderWidgetHostView::SendMouseEvent( const blink::WebMouseEvent& event) { for (auto* proxy_view : proxy_views_) { gfx::Rect bounds = proxy_view->GetBounds(); if (bounds.Contains(event.PositionInWidget().x(), event.PositionInWidget().y())) { blink::WebMouseEvent proxy_event(event); proxy_event.SetPositionInWidget( proxy_event.PositionInWidget().x() - bounds.x(), proxy_event.PositionInWidget().y() - bounds.y()); ui::MouseEvent ui_event = UiMouseEventFromWebMouseEvent(proxy_event); proxy_view->OnEvent(&ui_event); return; } } if (!IsPopupWidget()) { if (popup_host_view_ && popup_host_view_->popup_position_.Contains( event.PositionInWidget().x(), event.PositionInWidget().y())) { blink::WebMouseEvent popup_event(event); popup_event.SetPositionInWidget( popup_event.PositionInWidget().x() - popup_host_view_->popup_position_.x(), popup_event.PositionInWidget().y() - popup_host_view_->popup_position_.y()); popup_host_view_->ProcessMouseEvent(popup_event, ui::LatencyInfo()); return; } } if (!render_widget_host_) return; render_widget_host_->ForwardMouseEvent(event); } void OffScreenRenderWidgetHostView::SendMouseWheelEvent( const blink::WebMouseWheelEvent& event) { for (auto* proxy_view : proxy_views_) { gfx::Rect bounds = proxy_view->GetBounds(); if (bounds.Contains(event.PositionInWidget().x(), event.PositionInWidget().y())) { blink::WebMouseWheelEvent proxy_event(event); proxy_event.SetPositionInWidget( proxy_event.PositionInWidget().x() - bounds.x(), proxy_event.PositionInWidget().y() - bounds.y()); ui::MouseWheelEvent ui_event = UiMouseWheelEventFromWebMouseEvent(proxy_event); proxy_view->OnEvent(&ui_event); return; } } blink::WebMouseWheelEvent mouse_wheel_event(event); bool should_route_event = render_widget_host_->delegate() && render_widget_host_->delegate()->GetInputEventRouter(); mouse_wheel_phase_handler_.SendWheelEndForTouchpadScrollingIfNeeded( should_route_event); mouse_wheel_phase_handler_.AddPhaseIfNeededAndScheduleEndEvent( mouse_wheel_event, false); if (!IsPopupWidget()) { if (popup_host_view_) { if (popup_host_view_->popup_position_.Contains( mouse_wheel_event.PositionInWidget().x(), mouse_wheel_event.PositionInWidget().y())) { blink::WebMouseWheelEvent popup_mouse_wheel_event(mouse_wheel_event); popup_mouse_wheel_event.SetPositionInWidget( mouse_wheel_event.PositionInWidget().x() - popup_host_view_->popup_position_.x(), mouse_wheel_event.PositionInWidget().y() - popup_host_view_->popup_position_.y()); popup_mouse_wheel_event.SetPositionInScreen( popup_mouse_wheel_event.PositionInWidget().x(), popup_mouse_wheel_event.PositionInWidget().y()); popup_host_view_->SendMouseWheelEvent(popup_mouse_wheel_event); return; } else { // Scrolling outside of the popup widget so destroy it. // Execute asynchronously to avoid deleting the widget from inside some // other callback. base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&OffScreenRenderWidgetHostView::CancelWidget, popup_host_view_->weak_ptr_factory_.GetWeakPtr())); } } else if (!guest_host_views_.empty()) { for (auto* guest_host_view : guest_host_views_) { if (!guest_host_view->render_widget_host_ || !guest_host_view->render_widget_host_->GetView()) { continue; } const gfx::Rect& guest_bounds = guest_host_view->render_widget_host_->GetView()->GetViewBounds(); if (guest_bounds.Contains(mouse_wheel_event.PositionInWidget().x(), mouse_wheel_event.PositionInWidget().y())) { blink::WebMouseWheelEvent guest_mouse_wheel_event(mouse_wheel_event); guest_mouse_wheel_event.SetPositionInWidget( mouse_wheel_event.PositionInWidget().x() - guest_bounds.x(), mouse_wheel_event.PositionInWidget().y() - guest_bounds.y()); guest_mouse_wheel_event.SetPositionInScreen( guest_mouse_wheel_event.PositionInWidget().x(), guest_mouse_wheel_event.PositionInWidget().y()); guest_host_view->SendMouseWheelEvent(guest_mouse_wheel_event); return; } } } } if (!render_widget_host_) return; render_widget_host_->ForwardWheelEvent(event); } void OffScreenRenderWidgetHostView::SetPainting(bool painting) { painting_ = painting; if (popup_host_view_) { popup_host_view_->SetPainting(painting); } for (auto* guest_host_view : guest_host_views_) guest_host_view->SetPainting(painting); if (video_consumer_) { video_consumer_->SetActive(IsPainting()); } else if (host_display_client_) { host_display_client_->SetActive(IsPainting()); } } bool OffScreenRenderWidgetHostView::IsPainting() const { return painting_; } void OffScreenRenderWidgetHostView::SetFrameRate(int frame_rate) { if (parent_host_view_) { if (parent_host_view_->GetFrameRate() == GetFrameRate()) return; frame_rate_ = parent_host_view_->GetFrameRate(); } else { if (frame_rate <= 0) frame_rate = 1; if (frame_rate > 240) frame_rate = 240; frame_rate_ = frame_rate; } SetupFrameRate(true); if (video_consumer_) { video_consumer_->SetFrameRate(GetFrameRate()); } for (auto* guest_host_view : guest_host_views_) guest_host_view->SetFrameRate(frame_rate); } int OffScreenRenderWidgetHostView::GetFrameRate() const { return frame_rate_; } ui::Layer* OffScreenRenderWidgetHostView::GetRootLayer() const { return root_layer_.get(); } const viz::LocalSurfaceId& OffScreenRenderWidgetHostView::GetLocalSurfaceId() const { return delegated_frame_host_surface_id_; } content::DelegatedFrameHost* OffScreenRenderWidgetHostView::GetDelegatedFrameHost() const { return delegated_frame_host_.get(); } void OffScreenRenderWidgetHostView::SetupFrameRate(bool force) { if (!force && frame_rate_threshold_us_ != 0) return; frame_rate_threshold_us_ = 1000000 / frame_rate_; if (compositor_) { compositor_->SetDisplayVSyncParameters( base::TimeTicks::Now(), base::Microseconds(frame_rate_threshold_us_)); } } void OffScreenRenderWidgetHostView::Invalidate() { InvalidateBounds(gfx::Rect(GetRequestedRendererSize())); } void OffScreenRenderWidgetHostView::InvalidateBounds(const gfx::Rect& bounds) { CompositeFrame(bounds); } void OffScreenRenderWidgetHostView::ResizeRootLayer(bool force) { SetupFrameRate(false); display::Display display = display::Screen::GetScreen()->GetDisplayNearestView(GetNativeView()); const float scaleFactor = display.device_scale_factor(); float sf = GetDeviceScaleFactor(); const bool scaleFactorDidChange = scaleFactor != sf; // Initialize a screen_infos_ struct as needed, to cache the scale factor. if (screen_infos_.screen_infos.empty()) { UpdateScreenInfo(); } screen_infos_.mutable_current().device_scale_factor = scaleFactor; gfx::Size size; if (!IsPopupWidget()) size = GetViewBounds().size(); else size = popup_position_.size(); if (!force && !scaleFactorDidChange && size == GetRootLayer()->bounds().size()) return; GetRootLayer()->SetBounds(gfx::Rect(size)); const gfx::Size& size_in_pixels = gfx::ToFlooredSize(gfx::ConvertSizeToPixels(size, sf)); if (compositor_) { compositor_allocator_.GenerateId(); compositor_surface_id_ = compositor_allocator_.GetCurrentLocalSurfaceId(); compositor_->SetScaleAndSize(sf, size_in_pixels, compositor_surface_id_); } delegated_frame_host_allocator_.GenerateId(); delegated_frame_host_surface_id_ = delegated_frame_host_allocator_.GetCurrentLocalSurfaceId(); GetDelegatedFrameHost()->EmbedSurface( delegated_frame_host_surface_id_, size, cc::DeadlinePolicy::UseDefaultDeadline()); // Note that |render_widget_host_| will retrieve resize parameters from the // DelegatedFrameHost, so it must have SynchronizeVisualProperties called // after. if (render_widget_host_) { render_widget_host_->SynchronizeVisualProperties(); } } viz::FrameSinkId OffScreenRenderWidgetHostView::AllocateFrameSinkId() { return viz::FrameSinkId( base::checked_cast<uint32_t>(render_widget_host_->GetProcess()->GetID()), base::checked_cast<uint32_t>(render_widget_host_->GetRoutingID())); } void OffScreenRenderWidgetHostView::UpdateBackgroundColorFromRenderer( SkColor color) { if (color == background_color_) return; background_color_ = color; bool opaque = SkColorGetA(color) == SK_AlphaOPAQUE; GetRootLayer()->SetFillsBoundsOpaquely(opaque); GetRootLayer()->SetColor(color); } void OffScreenRenderWidgetHostView::NotifyHostAndDelegateOnWasShown( blink::mojom::RecordContentToVisibleTimeRequestPtr) { NOTREACHED(); } void OffScreenRenderWidgetHostView::RequestPresentationTimeFromHostOrDelegate( blink::mojom::RecordContentToVisibleTimeRequestPtr) { NOTREACHED(); } void OffScreenRenderWidgetHostView:: CancelPresentationTimeRequestForHostAndDelegate() { NOTREACHED(); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
34,047
[Bug]: offscreen rendering doesn't render clicked INPUT SELECT dropdown
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 18.1.0 ### What operating system are you using? Ubuntu ### Operating System Version Ubuntu 20.04 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior Offscreen rendering paint events should receive events for SELECT input elements. ### Actual Behavior Sometimes an empty white box appears, or nothing happens. ### Testcase Gist URL https://gist.github.com/gtalusan/c0ad56685aeb3b2c1108fbccf6b451b4 ### Additional Information Here's a screenshot when the fiddle is run with `offscreen = false`: <img width="760" alt="Screen Shot 2022-05-03 at 9 54 42 AM" src="https://user-images.githubusercontent.com/355585/166471227-1e0e27b0-cc8b-4c8e-94e5-a4261e2437b6.png"> Here are the paint event images saved to PNGs when `offscreen = true`: ![0](https://user-images.githubusercontent.com/355585/166471435-209960eb-27e2-47f1-a758-1760a052f3d1.png) ![1](https://user-images.githubusercontent.com/355585/166471445-269fab98-f046-43d4-b72a-65a49c5bc067.png)
https://github.com/electron/electron/issues/34047
https://github.com/electron/electron/pull/34069
323f7d4c19b232ec5661d9d87fcecaf6918d8abf
90eb47f70ba0ba1b89933ba505f6cc8805411bcf
2022-05-03T14:23:00Z
c++
2022-05-05T13:53:39Z
shell/browser/osr/osr_render_widget_host_view.h
// Copyright (c) 2016 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_OSR_OSR_RENDER_WIDGET_HOST_VIEW_H_ #define ELECTRON_SHELL_BROWSER_OSR_OSR_RENDER_WIDGET_HOST_VIEW_H_ #include <memory> #include <set> #include <string> #include <vector> #include "build/build_config.h" #if BUILDFLAG(IS_WIN) #include <windows.h> #endif #include "base/process/kill.h" #include "base/threading/thread.h" #include "base/time/time.h" #include "components/viz/common/quads/compositor_frame.h" #include "components/viz/common/surfaces/parent_local_surface_id_allocator.h" #include "content/browser/renderer_host/delegated_frame_host.h" // nogncheck #include "content/browser/renderer_host/input/mouse_wheel_phase_handler.h" // nogncheck #include "content/browser/renderer_host/render_widget_host_impl.h" // nogncheck #include "content/browser/renderer_host/render_widget_host_view_base.h" // nogncheck #include "content/browser/web_contents/web_contents_view.h" // nogncheck #include "shell/browser/osr/osr_host_display_client.h" #include "shell/browser/osr/osr_video_consumer.h" #include "shell/browser/osr/osr_view_proxy.h" #include "third_party/blink/public/mojom/widget/record_content_to_visible_time_request.mojom-forward.h" #include "third_party/blink/public/platform/web_vector.h" #include "third_party/skia/include/core/SkBitmap.h" #include "ui/base/ime/text_input_client.h" #include "ui/compositor/compositor.h" #include "ui/compositor/layer_delegate.h" #include "ui/compositor/layer_owner.h" #include "ui/gfx/geometry/point.h" #include "components/viz/host/host_display_client.h" #if BUILDFLAG(IS_WIN) #include "ui/gfx/win/window_impl.h" #endif namespace content { class CursorManager; } namespace electron { class ElectronCopyFrameGenerator; class ElectronBeginFrameTimer; class ElectronDelegatedFrameHostClient; typedef base::RepeatingCallback<void(const gfx::Rect&, const SkBitmap&)> OnPaintCallback; typedef base::RepeatingCallback<void(const gfx::Rect&)> OnPopupPaintCallback; class OffScreenRenderWidgetHostView : public content::RenderWidgetHostViewBase, public ui::CompositorDelegate, public OffscreenViewProxyObserver { public: OffScreenRenderWidgetHostView(bool transparent, bool painting, int frame_rate, const OnPaintCallback& callback, content::RenderWidgetHost* render_widget_host, OffScreenRenderWidgetHostView* parent_host_view, gfx::Size initial_size); ~OffScreenRenderWidgetHostView() override; // disable copy OffScreenRenderWidgetHostView(const OffScreenRenderWidgetHostView&) = delete; OffScreenRenderWidgetHostView& operator=( const OffScreenRenderWidgetHostView&) = delete; // content::RenderWidgetHostView: void InitAsChild(gfx::NativeView) override; void SetSize(const gfx::Size&) override; void SetBounds(const gfx::Rect&) override; gfx::NativeView GetNativeView(void) override; gfx::NativeViewAccessible GetNativeViewAccessible(void) override; ui::TextInputClient* GetTextInputClient() override; void Focus(void) override; bool HasFocus(void) override; uint32_t GetCaptureSequenceNumber() const override; bool IsSurfaceAvailableForCopy(void) override; void Hide(void) override; bool IsShowing(void) override; void EnsureSurfaceSynchronizedForWebTest() override; gfx::Rect GetViewBounds(void) override; gfx::Size GetVisibleViewportSize() override; void SetInsets(const gfx::Insets&) override; void SetBackgroundColor(SkColor color) override; absl::optional<SkColor> GetBackgroundColor() override; void UpdateBackgroundColor() override; blink::mojom::PointerLockResult LockMouse( bool request_unadjusted_movement) override; blink::mojom::PointerLockResult ChangeMouseLock( bool request_unadjusted_movement) override; void UnlockMouse(void) override; void TakeFallbackContentFrom(content::RenderWidgetHostView* view) override; #if BUILDFLAG(IS_MAC) void SetActive(bool active) override; void ShowDefinitionForSelection() override; void SpeakSelection() override; void SetWindowFrameInScreen(const gfx::Rect& rect) override; void ShowSharePicker( const std::string& title, const std::string& text, const std::string& url, const std::vector<std::string>& file_paths, blink::mojom::ShareService::ShareCallback callback) override; bool UpdateNSViewAndDisplay(); #endif // BUILDFLAG(IS_MAC) // content::RenderWidgetHostViewBase: void ResetFallbackToFirstNavigationSurface() override; void InitAsPopup(content::RenderWidgetHostView* parent_host_view, const gfx::Rect& pos, const gfx::Rect& anchor_rect) override; void UpdateCursor(const content::WebCursor&) override; void SetIsLoading(bool is_loading) override; void TextInputStateChanged(const ui::mojom::TextInputState& params) override; void ImeCancelComposition(void) override; void RenderProcessGone() override; void ShowWithVisibility(content::PageVisibilityState page_visibility) final; void Destroy(void) override; void UpdateTooltipUnderCursor(const std::u16string&) override; content::CursorManager* GetCursorManager() override; void CopyFromSurface( const gfx::Rect& src_rect, const gfx::Size& output_size, base::OnceCallback<void(const SkBitmap&)> callback) override; display::ScreenInfo GetScreenInfo() const override; void TransformPointToRootSurface(gfx::PointF* point) override; gfx::Rect GetBoundsInRootWindow(void) override; absl::optional<content::DisplayFeature> GetDisplayFeature() override; void SetDisplayFeatureForTesting( const content::DisplayFeature* display_feature) override; void NotifyHostAndDelegateOnWasShown( blink::mojom::RecordContentToVisibleTimeRequestPtr) final; void RequestPresentationTimeFromHostOrDelegate( blink::mojom::RecordContentToVisibleTimeRequestPtr) final; void CancelPresentationTimeRequestForHostAndDelegate() final; viz::SurfaceId GetCurrentSurfaceId() const override; std::unique_ptr<content::SyntheticGestureTarget> CreateSyntheticGestureTarget() override; void ImeCompositionRangeChanged(const gfx::Range&, const std::vector<gfx::Rect>&) override; gfx::Size GetCompositorViewportPixelSize() override; ui::Compositor* GetCompositor() override; content::RenderWidgetHostViewBase* CreateViewForWidget( content::RenderWidgetHost*, content::RenderWidgetHost*, content::WebContentsView*) override; const viz::LocalSurfaceId& GetLocalSurfaceId() const override; const viz::FrameSinkId& GetFrameSinkId() const override; void DidNavigate() override; bool TransformPointToCoordSpaceForView( const gfx::PointF& point, RenderWidgetHostViewBase* target_view, gfx::PointF* transformed_point) override; // ui::CompositorDelegate: bool IsOffscreen() const override; std::unique_ptr<viz::HostDisplayClient> CreateHostDisplayClient( ui::Compositor* compositor) override; bool InstallTransparency(); void CancelWidget(); void AddGuestHostView(OffScreenRenderWidgetHostView* guest_host); void RemoveGuestHostView(OffScreenRenderWidgetHostView* guest_host); void AddViewProxy(OffscreenViewProxy* proxy); void RemoveViewProxy(OffscreenViewProxy* proxy); void ProxyViewDestroyed(OffscreenViewProxy* proxy) override; void OnPaint(const gfx::Rect& damage_rect, const SkBitmap& bitmap); void OnPopupPaint(const gfx::Rect& damage_rect); void OnProxyViewPaint(const gfx::Rect& damage_rect) override; gfx::Size SizeInPixels(); void CompositeFrame(const gfx::Rect& damage_rect); bool IsPopupWidget() const { return widget_type_ == content::WidgetType::kPopup; } const SkBitmap& GetBacking() { return *backing_.get(); } void HoldResize(); void ReleaseResize(); void SynchronizeVisualProperties(); void SendMouseEvent(const blink::WebMouseEvent& event); void SendMouseWheelEvent(const blink::WebMouseWheelEvent& event); void SetPainting(bool painting); bool IsPainting() const; void SetFrameRate(int frame_rate); int GetFrameRate() const; ui::Layer* GetRootLayer() const; content::DelegatedFrameHost* GetDelegatedFrameHost() const; void Invalidate(); void InvalidateBounds(const gfx::Rect&); content::RenderWidgetHostImpl* render_widget_host() const { return render_widget_host_; } gfx::Size size() const { return size_; } void set_popup_host_view(OffScreenRenderWidgetHostView* popup_view) { popup_host_view_ = popup_view; } void set_child_host_view(OffScreenRenderWidgetHostView* child_view) { child_host_view_ = child_view; } private: void SetupFrameRate(bool force); void ResizeRootLayer(bool force); viz::FrameSinkId AllocateFrameSinkId(); // Applies background color without notifying the RenderWidget about // opaqueness changes. void UpdateBackgroundColorFromRenderer(SkColor color); // Weak ptrs. content::RenderWidgetHostImpl* render_widget_host_; OffScreenRenderWidgetHostView* parent_host_view_ = nullptr; OffScreenRenderWidgetHostView* popup_host_view_ = nullptr; OffScreenRenderWidgetHostView* child_host_view_ = nullptr; std::set<OffScreenRenderWidgetHostView*> guest_host_views_; std::set<OffscreenViewProxy*> proxy_views_; const bool transparent_; OnPaintCallback callback_; OnPopupPaintCallback parent_callback_; int frame_rate_ = 0; int frame_rate_threshold_us_ = 0; base::Time last_time_ = base::Time::Now(); gfx::Vector2dF last_scroll_offset_; gfx::Size size_; bool painting_; bool is_showing_ = false; bool is_destroyed_ = false; gfx::Rect popup_position_; bool hold_resize_ = false; bool pending_resize_ = false; bool paint_callback_running_ = false; viz::LocalSurfaceId delegated_frame_host_surface_id_; viz::ParentLocalSurfaceIdAllocator delegated_frame_host_allocator_; viz::LocalSurfaceId compositor_surface_id_; viz::ParentLocalSurfaceIdAllocator compositor_allocator_; std::unique_ptr<ui::Layer> root_layer_; std::unique_ptr<ui::Compositor> compositor_; std::unique_ptr<content::DelegatedFrameHost> delegated_frame_host_; std::unique_ptr<content::CursorManager> cursor_manager_; OffScreenHostDisplayClient* host_display_client_; std::unique_ptr<OffScreenVideoConsumer> video_consumer_; std::unique_ptr<ElectronDelegatedFrameHostClient> delegated_frame_host_client_; content::MouseWheelPhaseHandler mouse_wheel_phase_handler_; // Latest capture sequence number which is incremented when the caller // requests surfaces be synchronized via // EnsureSurfaceSynchronizedForWebTest(). uint32_t latest_capture_sequence_number_ = 0u; SkColor background_color_ = SkColor(); std::unique_ptr<SkBitmap> backing_; base::WeakPtrFactory<OffScreenRenderWidgetHostView> weak_ptr_factory_{this}; }; } // namespace electron #endif // ELECTRON_SHELL_BROWSER_OSR_OSR_RENDER_WIDGET_HOST_VIEW_H_
closed
electron/electron
https://github.com/electron/electron
34,047
[Bug]: offscreen rendering doesn't render clicked INPUT SELECT dropdown
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 18.1.0 ### What operating system are you using? Ubuntu ### Operating System Version Ubuntu 20.04 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior Offscreen rendering paint events should receive events for SELECT input elements. ### Actual Behavior Sometimes an empty white box appears, or nothing happens. ### Testcase Gist URL https://gist.github.com/gtalusan/c0ad56685aeb3b2c1108fbccf6b451b4 ### Additional Information Here's a screenshot when the fiddle is run with `offscreen = false`: <img width="760" alt="Screen Shot 2022-05-03 at 9 54 42 AM" src="https://user-images.githubusercontent.com/355585/166471227-1e0e27b0-cc8b-4c8e-94e5-a4261e2437b6.png"> Here are the paint event images saved to PNGs when `offscreen = true`: ![0](https://user-images.githubusercontent.com/355585/166471435-209960eb-27e2-47f1-a758-1760a052f3d1.png) ![1](https://user-images.githubusercontent.com/355585/166471445-269fab98-f046-43d4-b72a-65a49c5bc067.png)
https://github.com/electron/electron/issues/34047
https://github.com/electron/electron/pull/34069
323f7d4c19b232ec5661d9d87fcecaf6918d8abf
90eb47f70ba0ba1b89933ba505f6cc8805411bcf
2022-05-03T14:23:00Z
c++
2022-05-05T13:53:39Z
shell/browser/osr/osr_video_consumer.cc
// Copyright (c) 2019 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/osr/osr_video_consumer.h" #include <utility> #include "media/base/video_frame_metadata.h" #include "media/capture/mojom/video_capture_buffer.mojom.h" #include "media/capture/mojom/video_capture_types.mojom.h" #include "services/viz/privileged/mojom/compositing/frame_sink_video_capture.mojom-shared.h" #include "shell/browser/osr/osr_render_widget_host_view.h" #include "ui/gfx/skbitmap_operations.h" namespace electron { OffScreenVideoConsumer::OffScreenVideoConsumer( OffScreenRenderWidgetHostView* view, OnPaintCallback callback) : callback_(callback), view_(view), video_capturer_(view->CreateVideoCapturer()) { video_capturer_->SetResolutionConstraints(view_->SizeInPixels(), view_->SizeInPixels(), true); video_capturer_->SetAutoThrottlingEnabled(false); video_capturer_->SetMinSizeChangePeriod(base::TimeDelta()); video_capturer_->SetFormat(media::PIXEL_FORMAT_ARGB); SetFrameRate(view_->GetFrameRate()); } OffScreenVideoConsumer::~OffScreenVideoConsumer() = default; void OffScreenVideoConsumer::SetActive(bool active) { if (active) { video_capturer_->Start(this, viz::mojom::BufferFormatPreference::kDefault); } else { video_capturer_->Stop(); } } void OffScreenVideoConsumer::SetFrameRate(int frame_rate) { video_capturer_->SetMinCapturePeriod(base::Seconds(1) / frame_rate); } void OffScreenVideoConsumer::SizeChanged() { video_capturer_->SetResolutionConstraints(view_->SizeInPixels(), view_->SizeInPixels(), true); video_capturer_->RequestRefreshFrame(); } void OffScreenVideoConsumer::OnFrameCaptured( ::media::mojom::VideoBufferHandlePtr data, ::media::mojom::VideoFrameInfoPtr info, const gfx::Rect& content_rect, mojo::PendingRemote<viz::mojom::FrameSinkVideoConsumerFrameCallbacks> callbacks) { auto& data_region = data->get_read_only_shmem_region(); if (!CheckContentRect(content_rect)) { gfx::Size view_size = view_->SizeInPixels(); video_capturer_->SetResolutionConstraints(view_size, view_size, true); video_capturer_->RequestRefreshFrame(); return; } mojo::Remote<viz::mojom::FrameSinkVideoConsumerFrameCallbacks> callbacks_remote(std::move(callbacks)); if (!data_region.IsValid()) { callbacks_remote->Done(); return; } base::ReadOnlySharedMemoryMapping mapping = data_region.Map(); if (!mapping.IsValid()) { DLOG(ERROR) << "Shared memory mapping failed."; callbacks_remote->Done(); return; } if (mapping.size() < media::VideoFrame::AllocationSize(info->pixel_format, info->coded_size)) { DLOG(ERROR) << "Shared memory size was less than expected."; callbacks_remote->Done(); return; } // The SkBitmap's pixels will be marked as immutable, but the installPixels() // API requires a non-const pointer. So, cast away the const. void* const pixels = const_cast<void*>(mapping.memory()); // Call installPixels() with a |releaseProc| that: 1) notifies the capturer // that this consumer has finished with the frame, and 2) releases the shared // memory mapping. struct FramePinner { // Keeps the shared memory that backs |frame_| mapped. base::ReadOnlySharedMemoryMapping mapping; // Prevents FrameSinkVideoCapturer from recycling the shared memory that // backs |frame_|. mojo::PendingRemote<viz::mojom::FrameSinkVideoConsumerFrameCallbacks> releaser; }; SkBitmap bitmap; bitmap.installPixels( SkImageInfo::MakeN32(content_rect.width(), content_rect.height(), kPremul_SkAlphaType), pixels, media::VideoFrame::RowBytes(media::VideoFrame::kARGBPlane, info->pixel_format, info->coded_size.width()), [](void* addr, void* context) { delete static_cast<FramePinner*>(context); }, new FramePinner{std::move(mapping), callbacks_remote.Unbind()}); bitmap.setImmutable(); absl::optional<gfx::Rect> update_rect = info->metadata.capture_update_rect; if (!update_rect.has_value() || update_rect->IsEmpty()) { update_rect = content_rect; } callback_.Run(*update_rect, bitmap); } void OffScreenVideoConsumer::OnFrameWithEmptyRegionCapture() {} void OffScreenVideoConsumer::OnStopped() {} void OffScreenVideoConsumer::OnLog(const std::string& message) {} bool OffScreenVideoConsumer::CheckContentRect(const gfx::Rect& content_rect) { gfx::Size view_size = view_->SizeInPixels(); gfx::Size content_size = content_rect.size(); if (std::abs(view_size.width() - content_size.width()) > 2) { return false; } if (std::abs(view_size.height() - content_size.height()) > 2) { return false; } return true; } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
34,047
[Bug]: offscreen rendering doesn't render clicked INPUT SELECT dropdown
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 18.1.0 ### What operating system are you using? Ubuntu ### Operating System Version Ubuntu 20.04 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior Offscreen rendering paint events should receive events for SELECT input elements. ### Actual Behavior Sometimes an empty white box appears, or nothing happens. ### Testcase Gist URL https://gist.github.com/gtalusan/c0ad56685aeb3b2c1108fbccf6b451b4 ### Additional Information Here's a screenshot when the fiddle is run with `offscreen = false`: <img width="760" alt="Screen Shot 2022-05-03 at 9 54 42 AM" src="https://user-images.githubusercontent.com/355585/166471227-1e0e27b0-cc8b-4c8e-94e5-a4261e2437b6.png"> Here are the paint event images saved to PNGs when `offscreen = true`: ![0](https://user-images.githubusercontent.com/355585/166471435-209960eb-27e2-47f1-a758-1760a052f3d1.png) ![1](https://user-images.githubusercontent.com/355585/166471445-269fab98-f046-43d4-b72a-65a49c5bc067.png)
https://github.com/electron/electron/issues/34047
https://github.com/electron/electron/pull/34069
323f7d4c19b232ec5661d9d87fcecaf6918d8abf
90eb47f70ba0ba1b89933ba505f6cc8805411bcf
2022-05-03T14:23:00Z
c++
2022-05-05T13:53:39Z
shell/browser/osr/osr_video_consumer.h
// Copyright (c) 2019 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_OSR_OSR_VIDEO_CONSUMER_H_ #define ELECTRON_SHELL_BROWSER_OSR_OSR_VIDEO_CONSUMER_H_ #include <memory> #include <string> #include "base/callback.h" #include "base/memory/weak_ptr.h" #include "components/viz/host/client_frame_sink_video_capturer.h" #include "media/capture/mojom/video_capture_buffer.mojom-forward.h" #include "media/capture/mojom/video_capture_types.mojom.h" namespace electron { class OffScreenRenderWidgetHostView; typedef base::RepeatingCallback<void(const gfx::Rect&, const SkBitmap&)> OnPaintCallback; class OffScreenVideoConsumer : public viz::mojom::FrameSinkVideoConsumer { public: OffScreenVideoConsumer(OffScreenRenderWidgetHostView* view, OnPaintCallback callback); ~OffScreenVideoConsumer() override; // disable copy OffScreenVideoConsumer(const OffScreenVideoConsumer&) = delete; OffScreenVideoConsumer& operator=(const OffScreenVideoConsumer&) = delete; void SetActive(bool active); void SetFrameRate(int frame_rate); void SizeChanged(); private: // viz::mojom::FrameSinkVideoConsumer implementation. void OnFrameCaptured( ::media::mojom::VideoBufferHandlePtr data, ::media::mojom::VideoFrameInfoPtr info, const gfx::Rect& content_rect, mojo::PendingRemote<viz::mojom::FrameSinkVideoConsumerFrameCallbacks> callbacks) override; void OnFrameWithEmptyRegionCapture() override; void OnStopped() override; void OnLog(const std::string& message) override; bool CheckContentRect(const gfx::Rect& content_rect); OnPaintCallback callback_; OffScreenRenderWidgetHostView* view_; std::unique_ptr<viz::ClientFrameSinkVideoCapturer> video_capturer_; base::WeakPtrFactory<OffScreenVideoConsumer> weak_ptr_factory_{this}; }; } // namespace electron #endif // ELECTRON_SHELL_BROWSER_OSR_OSR_VIDEO_CONSUMER_H_
closed
electron/electron
https://github.com/electron/electron
32,206
[Bug]: electron.safeStorage.isEncryptionAvailable() segfaults on Linux when called before creation of the first BrowserWindow
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Electron Version 15 and 16 ### What operating system are you using? Ubuntu ### Operating System Version Ubuntu 20.04 ### What arch are you using? x64 ### Last Known Working Electron version n/a ### Expected Behavior calling `electron.safeStorage.isEncryptionAvailable()` returns a boolean ### Actual Behavior calling `electron.safeStorage.isEncryptionAvailable()` segfaults immediately ### Testcase Gist URL https://github.com/ganthern/safe-storage-segfault ### Additional Information It also happens in a fresh openSUSE Leap 15.1.1 VM. The API should be available as soon as possible (preferrably before app ready) since it's useful for apps that run on startup without immediately opening BrowserWindows. For the record, it works as expected on MacOs and returns `false` on windows, which makes the current [documentation](https://www.electronjs.org/docs/latest/api/safe-storage#safestorageisencryptionavailable) of `isEncryptionAvailable` inaccurate.
https://github.com/electron/electron/issues/32206
https://github.com/electron/electron/pull/33913
6fea35271c67c6ad69cf026560cb221054a505a8
03e68e2efeee34715a5b37e6f7065ac8487f2485
2021-12-16T12:07:25Z
c++
2022-05-09T13:38:53Z
docs/api/safe-storage.md
# safeStorage > Allows access to simple encryption and decryption of strings for storage on the local machine. Process: [Main](../glossary.md#main-process) This module protects data stored on disk from being accessed by other applications or users with full disk access. Note that on Mac, access to the system Keychain is required and these calls can block the current thread to collect user input. The same is true for Linux, if a password management tool is available. ## Methods The `safeStorage` module has the following methods: ### `safeStorage.isEncryptionAvailable()` Returns `boolean` - Whether encryption is available. On Linux, returns true if the secret key is available. On MacOS, returns true if Keychain is available. On Windows, returns true once the app has emitted the `ready` event. ### `safeStorage.encryptString(plainText)` * `plainText` string Returns `Buffer` - An array of bytes representing the encrypted string. This function will throw an error if encryption fails. ### `safeStorage.decryptString(encrypted)` * `encrypted` Buffer Returns `string` - the decrypted string. Decrypts the encrypted buffer obtained with `safeStorage.encryptString` back into a string. This function will throw an error if decryption fails.
closed
electron/electron
https://github.com/electron/electron
32,206
[Bug]: electron.safeStorage.isEncryptionAvailable() segfaults on Linux when called before creation of the first BrowserWindow
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Electron Version 15 and 16 ### What operating system are you using? Ubuntu ### Operating System Version Ubuntu 20.04 ### What arch are you using? x64 ### Last Known Working Electron version n/a ### Expected Behavior calling `electron.safeStorage.isEncryptionAvailable()` returns a boolean ### Actual Behavior calling `electron.safeStorage.isEncryptionAvailable()` segfaults immediately ### Testcase Gist URL https://github.com/ganthern/safe-storage-segfault ### Additional Information It also happens in a fresh openSUSE Leap 15.1.1 VM. The API should be available as soon as possible (preferrably before app ready) since it's useful for apps that run on startup without immediately opening BrowserWindows. For the record, it works as expected on MacOs and returns `false` on windows, which makes the current [documentation](https://www.electronjs.org/docs/latest/api/safe-storage#safestorageisencryptionavailable) of `isEncryptionAvailable` inaccurate.
https://github.com/electron/electron/issues/32206
https://github.com/electron/electron/pull/33913
6fea35271c67c6ad69cf026560cb221054a505a8
03e68e2efeee34715a5b37e6f7065ac8487f2485
2021-12-16T12:07:25Z
c++
2022-05-09T13:38:53Z
shell/browser/api/electron_api_safe_storage.cc
// Copyright (c) 2021 Slack Technologies, 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_safe_storage.h" #include <string> #include <vector> #include "components/os_crypt/os_crypt.h" #include "shell/browser/browser.h" #include "shell/common/gin_converters/base_converter.h" #include "shell/common/gin_converters/callback_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/node_includes.h" #include "shell/common/platform_util.h" namespace electron { namespace safestorage { static const char* kEncryptionVersionPrefixV10 = "v10"; static const char* kEncryptionVersionPrefixV11 = "v11"; #if DCHECK_IS_ON() static bool electron_crypto_ready = false; void SetElectronCryptoReady(bool ready) { electron_crypto_ready = ready; } #endif bool IsEncryptionAvailable() { return OSCrypt::IsEncryptionAvailable(); } v8::Local<v8::Value> EncryptString(v8::Isolate* isolate, const std::string& plaintext) { if (!OSCrypt::IsEncryptionAvailable()) { gin_helper::ErrorThrower(isolate).ThrowError( "Error while decrypting the ciphertext provided to " "safeStorage.decryptString. " "Encryption is not available."); return v8::Local<v8::Value>(); } std::string ciphertext; bool encrypted = OSCrypt::EncryptString(plaintext, &ciphertext); if (!encrypted) { gin_helper::ErrorThrower(isolate).ThrowError( "Error while encrypting the text provided to " "safeStorage.encryptString."); return v8::Local<v8::Value>(); } return node::Buffer::Copy(isolate, ciphertext.c_str(), ciphertext.size()) .ToLocalChecked(); } std::string DecryptString(v8::Isolate* isolate, v8::Local<v8::Value> buffer) { if (!OSCrypt::IsEncryptionAvailable()) { gin_helper::ErrorThrower(isolate).ThrowError( "Error while decrypting the ciphertext provided to " "safeStorage.decryptString. " "Decryption is not available."); return ""; } if (!node::Buffer::HasInstance(buffer)) { gin_helper::ErrorThrower(isolate).ThrowError( "Expected the first argument of decryptString() to be a buffer"); return ""; } // ensures an error is thrown in Mac or Linux on // decryption failure, rather than failing silently const char* data = node::Buffer::Data(buffer); auto size = node::Buffer::Length(buffer); std::string ciphertext(data, size); if (ciphertext.empty()) { return ""; } if (ciphertext.find(kEncryptionVersionPrefixV10) != 0 && ciphertext.find(kEncryptionVersionPrefixV11) != 0) { gin_helper::ErrorThrower(isolate).ThrowError( "Error while decrypting the ciphertext provided to " "safeStorage.decryptString. " "Ciphertext does not appear to be encrypted."); return ""; } std::string plaintext; bool decrypted = OSCrypt::DecryptString(ciphertext, &plaintext); if (!decrypted) { gin_helper::ErrorThrower(isolate).ThrowError( "Error while decrypting the ciphertext provided to " "safeStorage.decryptString."); return ""; } return plaintext; } } // namespace safestorage } // namespace electron 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.SetMethod("isEncryptionAvailable", &electron::safestorage::IsEncryptionAvailable); dict.SetMethod("encryptString", &electron::safestorage::EncryptString); dict.SetMethod("decryptString", &electron::safestorage::DecryptString); } NODE_LINKED_MODULE_CONTEXT_AWARE(electron_browser_safe_storage, Initialize)
closed
electron/electron
https://github.com/electron/electron
32,206
[Bug]: electron.safeStorage.isEncryptionAvailable() segfaults on Linux when called before creation of the first BrowserWindow
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Electron Version 15 and 16 ### What operating system are you using? Ubuntu ### Operating System Version Ubuntu 20.04 ### What arch are you using? x64 ### Last Known Working Electron version n/a ### Expected Behavior calling `electron.safeStorage.isEncryptionAvailable()` returns a boolean ### Actual Behavior calling `electron.safeStorage.isEncryptionAvailable()` segfaults immediately ### Testcase Gist URL https://github.com/ganthern/safe-storage-segfault ### Additional Information It also happens in a fresh openSUSE Leap 15.1.1 VM. The API should be available as soon as possible (preferrably before app ready) since it's useful for apps that run on startup without immediately opening BrowserWindows. For the record, it works as expected on MacOs and returns `false` on windows, which makes the current [documentation](https://www.electronjs.org/docs/latest/api/safe-storage#safestorageisencryptionavailable) of `isEncryptionAvailable` inaccurate.
https://github.com/electron/electron/issues/32206
https://github.com/electron/electron/pull/33913
6fea35271c67c6ad69cf026560cb221054a505a8
03e68e2efeee34715a5b37e6f7065ac8487f2485
2021-12-16T12:07:25Z
c++
2022-05-09T13:38:53Z
spec-main/api-safe-storage-spec.ts
import * as cp from 'child_process'; import * as path from 'path'; import { safeStorage } from 'electron/main'; import { expect } from 'chai'; import { emittedOnce } from './events-helpers'; import { ifdescribe } from './spec-helpers'; import * as fs from 'fs'; /* isEncryptionAvailable returns false in Linux when running CI due to a mocked dbus. This stops * Chrome from reaching the system's keyring or libsecret. When running the tests with config.store * set to basic-text, a nullptr is returned from chromium, defaulting the available encryption to false. * * Because all encryption methods are gated by isEncryptionAvailable, the methods will never return the correct values * when run on CI and linux. */ ifdescribe(process.platform !== 'linux')('safeStorage module', () => { after(async () => { const pathToEncryptedString = path.resolve(__dirname, 'fixtures', 'api', 'safe-storage', 'encrypted.txt'); if (fs.existsSync(pathToEncryptedString)) { await fs.unlinkSync(pathToEncryptedString); } }); describe('SafeStorage.isEncryptionAvailable()', () => { it('should return true when encryption key is available (macOS, Windows)', () => { expect(safeStorage.isEncryptionAvailable()).to.equal(true); }); }); describe('SafeStorage.encryptString()', () => { it('valid input should correctly encrypt string', () => { const plaintext = 'plaintext'; const encrypted = safeStorage.encryptString(plaintext); expect(Buffer.isBuffer(encrypted)).to.equal(true); }); it('UTF-16 characters can be encrypted', () => { const plaintext = '€ - utf symbol'; const encrypted = safeStorage.encryptString(plaintext); expect(Buffer.isBuffer(encrypted)).to.equal(true); }); }); describe('SafeStorage.decryptString()', () => { it('valid input should correctly decrypt string', () => { const encrypted = safeStorage.encryptString('plaintext'); expect(safeStorage.decryptString(encrypted)).to.equal('plaintext'); }); it('UTF-16 characters can be decrypted', () => { const plaintext = '€ - utf symbol'; const encrypted = safeStorage.encryptString(plaintext); expect(safeStorage.decryptString(encrypted)).to.equal(plaintext); }); it('unencrypted input should throw', () => { const plaintextBuffer = Buffer.from('I am unencoded!', 'utf-8'); expect(() => { safeStorage.decryptString(plaintextBuffer); }).to.throw(Error); }); it('non-buffer input should throw', () => { const notABuffer = {} as any; expect(() => { safeStorage.decryptString(notABuffer); }).to.throw(Error); }); }); describe('safeStorage persists encryption key across app relaunch', () => { it('can decrypt after closing and reopening app', async () => { const fixturesPath = path.resolve(__dirname, 'fixtures'); const encryptAppPath = path.join(fixturesPath, 'api', 'safe-storage', 'encrypt-app'); const encryptAppProcess = cp.spawn(process.execPath, [encryptAppPath]); let stdout: string = ''; encryptAppProcess.stderr.on('data', data => { stdout += data; }); encryptAppProcess.stderr.on('data', data => { stdout += data; }); try { await emittedOnce(encryptAppProcess, 'exit'); const appPath = path.join(fixturesPath, 'api', 'safe-storage', 'decrypt-app'); const relaunchedAppProcess = cp.spawn(process.execPath, [appPath]); let output = ''; relaunchedAppProcess.stdout.on('data', data => { output += data; }); relaunchedAppProcess.stderr.on('data', data => { output += data; }); const [code] = await emittedOnce(relaunchedAppProcess, 'exit'); if (!output.includes('plaintext')) { console.log(code, output); } expect(output).to.include('plaintext'); } catch (e) { console.log(stdout); throw e; } }); }); });
closed
electron/electron
https://github.com/electron/electron
32,206
[Bug]: electron.safeStorage.isEncryptionAvailable() segfaults on Linux when called before creation of the first BrowserWindow
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Electron Version 15 and 16 ### What operating system are you using? Ubuntu ### Operating System Version Ubuntu 20.04 ### What arch are you using? x64 ### Last Known Working Electron version n/a ### Expected Behavior calling `electron.safeStorage.isEncryptionAvailable()` returns a boolean ### Actual Behavior calling `electron.safeStorage.isEncryptionAvailable()` segfaults immediately ### Testcase Gist URL https://github.com/ganthern/safe-storage-segfault ### Additional Information It also happens in a fresh openSUSE Leap 15.1.1 VM. The API should be available as soon as possible (preferrably before app ready) since it's useful for apps that run on startup without immediately opening BrowserWindows. For the record, it works as expected on MacOs and returns `false` on windows, which makes the current [documentation](https://www.electronjs.org/docs/latest/api/safe-storage#safestorageisencryptionavailable) of `isEncryptionAvailable` inaccurate.
https://github.com/electron/electron/issues/32206
https://github.com/electron/electron/pull/33913
6fea35271c67c6ad69cf026560cb221054a505a8
03e68e2efeee34715a5b37e6f7065ac8487f2485
2021-12-16T12:07:25Z
c++
2022-05-09T13:38:53Z
spec-main/fixtures/crash-cases/safe-storage/index.js
closed
electron/electron
https://github.com/electron/electron
32,206
[Bug]: electron.safeStorage.isEncryptionAvailable() segfaults on Linux when called before creation of the first BrowserWindow
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Electron Version 15 and 16 ### What operating system are you using? Ubuntu ### Operating System Version Ubuntu 20.04 ### What arch are you using? x64 ### Last Known Working Electron version n/a ### Expected Behavior calling `electron.safeStorage.isEncryptionAvailable()` returns a boolean ### Actual Behavior calling `electron.safeStorage.isEncryptionAvailable()` segfaults immediately ### Testcase Gist URL https://github.com/ganthern/safe-storage-segfault ### Additional Information It also happens in a fresh openSUSE Leap 15.1.1 VM. The API should be available as soon as possible (preferrably before app ready) since it's useful for apps that run on startup without immediately opening BrowserWindows. For the record, it works as expected on MacOs and returns `false` on windows, which makes the current [documentation](https://www.electronjs.org/docs/latest/api/safe-storage#safestorageisencryptionavailable) of `isEncryptionAvailable` inaccurate.
https://github.com/electron/electron/issues/32206
https://github.com/electron/electron/pull/33913
6fea35271c67c6ad69cf026560cb221054a505a8
03e68e2efeee34715a5b37e6f7065ac8487f2485
2021-12-16T12:07:25Z
c++
2022-05-09T13:38:53Z
docs/api/safe-storage.md
# safeStorage > Allows access to simple encryption and decryption of strings for storage on the local machine. Process: [Main](../glossary.md#main-process) This module protects data stored on disk from being accessed by other applications or users with full disk access. Note that on Mac, access to the system Keychain is required and these calls can block the current thread to collect user input. The same is true for Linux, if a password management tool is available. ## Methods The `safeStorage` module has the following methods: ### `safeStorage.isEncryptionAvailable()` Returns `boolean` - Whether encryption is available. On Linux, returns true if the secret key is available. On MacOS, returns true if Keychain is available. On Windows, returns true once the app has emitted the `ready` event. ### `safeStorage.encryptString(plainText)` * `plainText` string Returns `Buffer` - An array of bytes representing the encrypted string. This function will throw an error if encryption fails. ### `safeStorage.decryptString(encrypted)` * `encrypted` Buffer Returns `string` - the decrypted string. Decrypts the encrypted buffer obtained with `safeStorage.encryptString` back into a string. This function will throw an error if decryption fails.
closed
electron/electron
https://github.com/electron/electron
32,206
[Bug]: electron.safeStorage.isEncryptionAvailable() segfaults on Linux when called before creation of the first BrowserWindow
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Electron Version 15 and 16 ### What operating system are you using? Ubuntu ### Operating System Version Ubuntu 20.04 ### What arch are you using? x64 ### Last Known Working Electron version n/a ### Expected Behavior calling `electron.safeStorage.isEncryptionAvailable()` returns a boolean ### Actual Behavior calling `electron.safeStorage.isEncryptionAvailable()` segfaults immediately ### Testcase Gist URL https://github.com/ganthern/safe-storage-segfault ### Additional Information It also happens in a fresh openSUSE Leap 15.1.1 VM. The API should be available as soon as possible (preferrably before app ready) since it's useful for apps that run on startup without immediately opening BrowserWindows. For the record, it works as expected on MacOs and returns `false` on windows, which makes the current [documentation](https://www.electronjs.org/docs/latest/api/safe-storage#safestorageisencryptionavailable) of `isEncryptionAvailable` inaccurate.
https://github.com/electron/electron/issues/32206
https://github.com/electron/electron/pull/33913
6fea35271c67c6ad69cf026560cb221054a505a8
03e68e2efeee34715a5b37e6f7065ac8487f2485
2021-12-16T12:07:25Z
c++
2022-05-09T13:38:53Z
shell/browser/api/electron_api_safe_storage.cc
// Copyright (c) 2021 Slack Technologies, 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_safe_storage.h" #include <string> #include <vector> #include "components/os_crypt/os_crypt.h" #include "shell/browser/browser.h" #include "shell/common/gin_converters/base_converter.h" #include "shell/common/gin_converters/callback_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/node_includes.h" #include "shell/common/platform_util.h" namespace electron { namespace safestorage { static const char* kEncryptionVersionPrefixV10 = "v10"; static const char* kEncryptionVersionPrefixV11 = "v11"; #if DCHECK_IS_ON() static bool electron_crypto_ready = false; void SetElectronCryptoReady(bool ready) { electron_crypto_ready = ready; } #endif bool IsEncryptionAvailable() { return OSCrypt::IsEncryptionAvailable(); } v8::Local<v8::Value> EncryptString(v8::Isolate* isolate, const std::string& plaintext) { if (!OSCrypt::IsEncryptionAvailable()) { gin_helper::ErrorThrower(isolate).ThrowError( "Error while decrypting the ciphertext provided to " "safeStorage.decryptString. " "Encryption is not available."); return v8::Local<v8::Value>(); } std::string ciphertext; bool encrypted = OSCrypt::EncryptString(plaintext, &ciphertext); if (!encrypted) { gin_helper::ErrorThrower(isolate).ThrowError( "Error while encrypting the text provided to " "safeStorage.encryptString."); return v8::Local<v8::Value>(); } return node::Buffer::Copy(isolate, ciphertext.c_str(), ciphertext.size()) .ToLocalChecked(); } std::string DecryptString(v8::Isolate* isolate, v8::Local<v8::Value> buffer) { if (!OSCrypt::IsEncryptionAvailable()) { gin_helper::ErrorThrower(isolate).ThrowError( "Error while decrypting the ciphertext provided to " "safeStorage.decryptString. " "Decryption is not available."); return ""; } if (!node::Buffer::HasInstance(buffer)) { gin_helper::ErrorThrower(isolate).ThrowError( "Expected the first argument of decryptString() to be a buffer"); return ""; } // ensures an error is thrown in Mac or Linux on // decryption failure, rather than failing silently const char* data = node::Buffer::Data(buffer); auto size = node::Buffer::Length(buffer); std::string ciphertext(data, size); if (ciphertext.empty()) { return ""; } if (ciphertext.find(kEncryptionVersionPrefixV10) != 0 && ciphertext.find(kEncryptionVersionPrefixV11) != 0) { gin_helper::ErrorThrower(isolate).ThrowError( "Error while decrypting the ciphertext provided to " "safeStorage.decryptString. " "Ciphertext does not appear to be encrypted."); return ""; } std::string plaintext; bool decrypted = OSCrypt::DecryptString(ciphertext, &plaintext); if (!decrypted) { gin_helper::ErrorThrower(isolate).ThrowError( "Error while decrypting the ciphertext provided to " "safeStorage.decryptString."); return ""; } return plaintext; } } // namespace safestorage } // namespace electron 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.SetMethod("isEncryptionAvailable", &electron::safestorage::IsEncryptionAvailable); dict.SetMethod("encryptString", &electron::safestorage::EncryptString); dict.SetMethod("decryptString", &electron::safestorage::DecryptString); } NODE_LINKED_MODULE_CONTEXT_AWARE(electron_browser_safe_storage, Initialize)
closed
electron/electron
https://github.com/electron/electron
32,206
[Bug]: electron.safeStorage.isEncryptionAvailable() segfaults on Linux when called before creation of the first BrowserWindow
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Electron Version 15 and 16 ### What operating system are you using? Ubuntu ### Operating System Version Ubuntu 20.04 ### What arch are you using? x64 ### Last Known Working Electron version n/a ### Expected Behavior calling `electron.safeStorage.isEncryptionAvailable()` returns a boolean ### Actual Behavior calling `electron.safeStorage.isEncryptionAvailable()` segfaults immediately ### Testcase Gist URL https://github.com/ganthern/safe-storage-segfault ### Additional Information It also happens in a fresh openSUSE Leap 15.1.1 VM. The API should be available as soon as possible (preferrably before app ready) since it's useful for apps that run on startup without immediately opening BrowserWindows. For the record, it works as expected on MacOs and returns `false` on windows, which makes the current [documentation](https://www.electronjs.org/docs/latest/api/safe-storage#safestorageisencryptionavailable) of `isEncryptionAvailable` inaccurate.
https://github.com/electron/electron/issues/32206
https://github.com/electron/electron/pull/33913
6fea35271c67c6ad69cf026560cb221054a505a8
03e68e2efeee34715a5b37e6f7065ac8487f2485
2021-12-16T12:07:25Z
c++
2022-05-09T13:38:53Z
spec-main/api-safe-storage-spec.ts
import * as cp from 'child_process'; import * as path from 'path'; import { safeStorage } from 'electron/main'; import { expect } from 'chai'; import { emittedOnce } from './events-helpers'; import { ifdescribe } from './spec-helpers'; import * as fs from 'fs'; /* isEncryptionAvailable returns false in Linux when running CI due to a mocked dbus. This stops * Chrome from reaching the system's keyring or libsecret. When running the tests with config.store * set to basic-text, a nullptr is returned from chromium, defaulting the available encryption to false. * * Because all encryption methods are gated by isEncryptionAvailable, the methods will never return the correct values * when run on CI and linux. */ ifdescribe(process.platform !== 'linux')('safeStorage module', () => { after(async () => { const pathToEncryptedString = path.resolve(__dirname, 'fixtures', 'api', 'safe-storage', 'encrypted.txt'); if (fs.existsSync(pathToEncryptedString)) { await fs.unlinkSync(pathToEncryptedString); } }); describe('SafeStorage.isEncryptionAvailable()', () => { it('should return true when encryption key is available (macOS, Windows)', () => { expect(safeStorage.isEncryptionAvailable()).to.equal(true); }); }); describe('SafeStorage.encryptString()', () => { it('valid input should correctly encrypt string', () => { const plaintext = 'plaintext'; const encrypted = safeStorage.encryptString(plaintext); expect(Buffer.isBuffer(encrypted)).to.equal(true); }); it('UTF-16 characters can be encrypted', () => { const plaintext = '€ - utf symbol'; const encrypted = safeStorage.encryptString(plaintext); expect(Buffer.isBuffer(encrypted)).to.equal(true); }); }); describe('SafeStorage.decryptString()', () => { it('valid input should correctly decrypt string', () => { const encrypted = safeStorage.encryptString('plaintext'); expect(safeStorage.decryptString(encrypted)).to.equal('plaintext'); }); it('UTF-16 characters can be decrypted', () => { const plaintext = '€ - utf symbol'; const encrypted = safeStorage.encryptString(plaintext); expect(safeStorage.decryptString(encrypted)).to.equal(plaintext); }); it('unencrypted input should throw', () => { const plaintextBuffer = Buffer.from('I am unencoded!', 'utf-8'); expect(() => { safeStorage.decryptString(plaintextBuffer); }).to.throw(Error); }); it('non-buffer input should throw', () => { const notABuffer = {} as any; expect(() => { safeStorage.decryptString(notABuffer); }).to.throw(Error); }); }); describe('safeStorage persists encryption key across app relaunch', () => { it('can decrypt after closing and reopening app', async () => { const fixturesPath = path.resolve(__dirname, 'fixtures'); const encryptAppPath = path.join(fixturesPath, 'api', 'safe-storage', 'encrypt-app'); const encryptAppProcess = cp.spawn(process.execPath, [encryptAppPath]); let stdout: string = ''; encryptAppProcess.stderr.on('data', data => { stdout += data; }); encryptAppProcess.stderr.on('data', data => { stdout += data; }); try { await emittedOnce(encryptAppProcess, 'exit'); const appPath = path.join(fixturesPath, 'api', 'safe-storage', 'decrypt-app'); const relaunchedAppProcess = cp.spawn(process.execPath, [appPath]); let output = ''; relaunchedAppProcess.stdout.on('data', data => { output += data; }); relaunchedAppProcess.stderr.on('data', data => { output += data; }); const [code] = await emittedOnce(relaunchedAppProcess, 'exit'); if (!output.includes('plaintext')) { console.log(code, output); } expect(output).to.include('plaintext'); } catch (e) { console.log(stdout); throw e; } }); }); });
closed
electron/electron
https://github.com/electron/electron
32,206
[Bug]: electron.safeStorage.isEncryptionAvailable() segfaults on Linux when called before creation of the first BrowserWindow
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Electron Version 15 and 16 ### What operating system are you using? Ubuntu ### Operating System Version Ubuntu 20.04 ### What arch are you using? x64 ### Last Known Working Electron version n/a ### Expected Behavior calling `electron.safeStorage.isEncryptionAvailable()` returns a boolean ### Actual Behavior calling `electron.safeStorage.isEncryptionAvailable()` segfaults immediately ### Testcase Gist URL https://github.com/ganthern/safe-storage-segfault ### Additional Information It also happens in a fresh openSUSE Leap 15.1.1 VM. The API should be available as soon as possible (preferrably before app ready) since it's useful for apps that run on startup without immediately opening BrowserWindows. For the record, it works as expected on MacOs and returns `false` on windows, which makes the current [documentation](https://www.electronjs.org/docs/latest/api/safe-storage#safestorageisencryptionavailable) of `isEncryptionAvailable` inaccurate.
https://github.com/electron/electron/issues/32206
https://github.com/electron/electron/pull/33913
6fea35271c67c6ad69cf026560cb221054a505a8
03e68e2efeee34715a5b37e6f7065ac8487f2485
2021-12-16T12:07:25Z
c++
2022-05-09T13:38:53Z
spec-main/fixtures/crash-cases/safe-storage/index.js
closed
electron/electron
https://github.com/electron/electron
34,118
[bug, linux] crash on start `undefined symbol: gtk_native_dialog_get_type`
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 18.1.0, nightly v20-20220418 and newer ### What operating system are you using? Ubuntu ### Operating System Version repro on 16.04, no repro on 22.04, other versions unknown ### What arch are you using? x64 ### Last Known Working Electron version 18.0.3, nightly v20-20220415 and older ### Expected Behavior Electron starts. ### Actual Behavior Electron crashes on startup: <img width="1696" alt="image" src="https://user-images.githubusercontent.com/8472721/167078330-76bf7b1f-2ca2-4e1a-b244-c384948f7e0c.png"> ### Testcase Gist URL No fiddle needed, just try to run an affected version. ### Additional Information Likely caused by #33650. Can we fix the fix 😆? Since this got backported, it affects 18, 19 and 20 now. cc @deepak1556 @miniak
https://github.com/electron/electron/issues/34118
https://github.com/electron/electron/pull/34141
9483e714c46cfa134209691b29b4ab5cf9fdb2ac
00368aca37c838decd414920e3a9db6447444ea6
2022-05-06T06:28:32Z
c++
2022-05-09T20:37:50Z
shell/browser/ui/electron_gtk.sigs
GtkFileChooserNative* gtk_file_chooser_native_new(const gchar* title, GtkWindow* parent, GtkFileChooserAction action, const gchar* accept_label, const gchar* cancel_label); void gtk_native_dialog_set_modal(GtkNativeDialog* self, gboolean modal); void gtk_native_dialog_show(GtkNativeDialog* self); void gtk_native_dialog_hide(GtkNativeDialog* self); gint gtk_native_dialog_run(GtkNativeDialog* self); void gtk_native_dialog_destroy(GtkNativeDialog* self);
closed
electron/electron
https://github.com/electron/electron
34,118
[bug, linux] crash on start `undefined symbol: gtk_native_dialog_get_type`
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 18.1.0, nightly v20-20220418 and newer ### What operating system are you using? Ubuntu ### Operating System Version repro on 16.04, no repro on 22.04, other versions unknown ### What arch are you using? x64 ### Last Known Working Electron version 18.0.3, nightly v20-20220415 and older ### Expected Behavior Electron starts. ### Actual Behavior Electron crashes on startup: <img width="1696" alt="image" src="https://user-images.githubusercontent.com/8472721/167078330-76bf7b1f-2ca2-4e1a-b244-c384948f7e0c.png"> ### Testcase Gist URL No fiddle needed, just try to run an affected version. ### Additional Information Likely caused by #33650. Can we fix the fix 😆? Since this got backported, it affects 18, 19 and 20 now. cc @deepak1556 @miniak
https://github.com/electron/electron/issues/34118
https://github.com/electron/electron/pull/34141
9483e714c46cfa134209691b29b4ab5cf9fdb2ac
00368aca37c838decd414920e3a9db6447444ea6
2022-05-06T06:28:32Z
c++
2022-05-09T20:37:50Z
shell/browser/ui/electron_gtk.sigs
GtkFileChooserNative* gtk_file_chooser_native_new(const gchar* title, GtkWindow* parent, GtkFileChooserAction action, const gchar* accept_label, const gchar* cancel_label); void gtk_native_dialog_set_modal(GtkNativeDialog* self, gboolean modal); void gtk_native_dialog_show(GtkNativeDialog* self); void gtk_native_dialog_hide(GtkNativeDialog* self); gint gtk_native_dialog_run(GtkNativeDialog* self); void gtk_native_dialog_destroy(GtkNativeDialog* self);
closed
electron/electron
https://github.com/electron/electron
33,652
Symbol generation is failing for 32-bit Windows release builds for nightlies and 19-x-y
Symbol generation on 32-bit Windows release builds on nightlies and 19-x-y are failing with the following error: ``` C:/depot_tools/bootstrap-2@3_8_10_chromium_23_bin/python3/bin/python3.exe ../../electron/build/dump_syms.py ./dump_syms.exe electron.exe breakpad_symbols gen/electron/electron_app_symbols.stamp failed to get function name WriteSymbols failed. Traceback (most recent call last): File "../../electron/build/dump_syms.py", line 53, in <module> main(*sys.argv[1:]) File "../../electron/build/dump_syms.py", line 42, in main symbol_data = subprocess.check_output(args).decode(sys.stdout.encoding) File "C:\depot_tools\bootstrap-2@3_8_10_chromium_23_bin\python3\bin\lib\subprocess.py", line 415, in check_output return run(*popenargs, stdout=PIPE, timeout=timeout, check=True, File "C:\depot_tools\bootstrap-2@3_8_10_chromium_23_bin\python3\bin\lib\subprocess.py", line 516, in run raise CalledProcessError(retcode, process.args, subprocess.CalledProcessError: Command '['./dump_syms.exe', 'electron.exe']' returned non-zero exit status 1. ninja: build stopped: subcommand failed. Command exited with code 1 ``` Here's a recent nightly release build with the failure: https://ci.appveyor.com/project/electron-bot/electron-ia32-release/builds/43164264 It looks like this failure was introduced via #33454.
https://github.com/electron/electron/issues/33652
https://github.com/electron/electron/pull/34162
6063d4f8df7298b6fbc66cc71e76c04e913faaf3
c512993744145e594c9ee8d55e5c4190c943f841
2022-04-07T14:51:10Z
c++
2022-05-11T15:27:23Z
appveyor.yml
# The config expects the following environment variables to be set: # - "GN_CONFIG" Build type. One of {'testing', 'release'}. # - "GN_EXTRA_ARGS" Additional gn arguments for a build config, # e.g. 'target_cpu="x86"' to build for a 32bit platform. # https://gn.googlesource.com/gn/+/master/docs/reference.md#target_cpu # Don't forget to set up "NPM_CONFIG_ARCH" and "TARGET_ARCH" accordningly # if you pass a custom value for 'target_cpu'. # - "ELECTRON_RELEASE" Set it to '1' upload binaries on success. # - "NPM_CONFIG_ARCH" E.g. 'x86'. Is used to build native Node.js modules. # Must match 'target_cpu' passed to "GN_EXTRA_ARGS" and "TARGET_ARCH" value. # - "TARGET_ARCH" Choose from {'ia32', 'x64', 'arm', 'arm64', 'mips64el'}. # Is used in some publishing scripts, but does NOT affect the Electron binary. # Must match 'target_cpu' passed to "GN_EXTRA_ARGS" and "NPM_CONFIG_ARCH" value. # - "UPLOAD_TO_STORAGE" Set it to '1' upload a release to the Azure bucket. # Otherwise the release will be uploaded to the Github Releases. # (The value is only checked if "ELECTRON_RELEASE" is defined.) # # The publishing scripts expect access tokens to be defined as env vars, # but those are not covered here. # # AppVeyor docs on variables: # https://www.appveyor.com/docs/environment-variables/ # https://www.appveyor.com/docs/build-configuration/#secure-variables # https://www.appveyor.com/docs/build-configuration/#custom-environment-variables version: 1.0.{build} build_cloud: electron-16-core image: vs2019bt-16.16.11 environment: GIT_CACHE_PATH: C:\Users\electron\libcc_cache ELECTRON_OUT_DIR: Default ELECTRON_ENABLE_STACK_DUMPING: 1 ELECTRON_ALSO_LOG_TO_STDERR: 1 MOCHA_REPORTER: mocha-multi-reporters MOCHA_MULTI_REPORTERS: mocha-appveyor-reporter, tap GOMA_FALLBACK_ON_AUTH_FAILURE: true notifications: - provider: Webhook url: https://electron-mission-control.herokuapp.com/rest/appveyor-hook method: POST headers: x-mission-control-secret: secure: 90BLVPcqhJPG7d24v0q/RRray6W3wDQ8uVQlQjOHaBWkw1i8FoA1lsjr2C/v1dVok+tS2Pi6KxDctPUkwIb4T27u4RhvmcPzQhVpfwVJAG9oNtq+yKN7vzHfg7k/pojEzVdJpQLzeJGcSrZu7VY39Q== on_build_success: false on_build_failure: true on_build_status_changed: false build_script: - ps: >- if(($env:APPVEYOR_PULL_REQUEST_HEAD_REPO_NAME -split "/")[0] -eq ($env:APPVEYOR_REPO_NAME -split "/")[0]) { Write-warning "Skipping PR build for branch"; Exit-AppveyorBuild } else { node script/yarn.js install --frozen-lockfile $result = node script/doc-only-change.js --prNumber=$env:APPVEYOR_PULL_REQUEST_NUMBER --prBranch=$env:APPVEYOR_REPO_BRANCH Write-Output $result if ($result.ExitCode -eq 0) { Write-warning "Skipping build for doc only change"; Exit-AppveyorBuild } } - echo "Building $env:GN_CONFIG build" - git config --global core.longpaths true - cd .. - mkdir src - update_depot_tools.bat - ps: Move-Item $env:APPVEYOR_BUILD_FOLDER -Destination src\electron - ps: >- if (Test-Path 'env:RAW_GOMA_AUTH') { $env:GOMA_OAUTH2_CONFIG_FILE = "$pwd\.goma_oauth2_config" $env:RAW_GOMA_AUTH | Set-Content $env:GOMA_OAUTH2_CONFIG_FILE } - git clone https://github.com/electron/build-tools.git - cd build-tools - npm install - mkdir third_party - ps: >- node -e "require('./src/utils/goma.js').downloadAndPrepare({ gomaOneForAll: true })" - ps: $env:GN_GOMA_FILE = node -e "console.log(require('./src/utils/goma.js').gnFilePath)" - ps: $env:LOCAL_GOMA_DIR = node -e "console.log(require('./src/utils/goma.js').dir)" - cd .. - ps: .\src\electron\script\start-goma.ps1 -gomaDir $env:LOCAL_GOMA_DIR - ps: >- if (Test-Path 'env:RAW_GOMA_AUTH') { $goma_login = python $env:LOCAL_GOMA_DIR\goma_auth.py info if ($goma_login -eq 'Login as Fermi Planck') { Write-warning "Goma authentication is correct"; } else { Write-warning "WARNING!!!!!! Goma authentication is incorrect; please update Goma auth token."; $host.SetShouldExit(1) } } - ps: $env:CHROMIUM_BUILDTOOLS_PATH="$pwd\src\buildtools" - ps: >- if ($env:GN_CONFIG -ne 'release') { $env:NINJA_STATUS="[%r processes, %f/%t @ %o/s : %es] " } - >- gclient config --name "src\electron" --unmanaged %GCLIENT_EXTRA_ARGS% "https://github.com/electron/electron" - ps: >- if ($env:GN_CONFIG -eq 'release') { $env:RUN_GCLIENT_SYNC="true" } else { cd src\electron node script\generate-deps-hash.js $depshash = Get-Content .\.depshash -Raw $zipfile = "Z:\$depshash.7z" cd ..\.. if (Test-Path -Path $zipfile) { # file exists, unzip and then gclient sync 7z x -y $zipfile -mmt=30 -aoa if (-not (Test-Path -Path "src\buildtools")) { # the zip file must be corrupt - resync $env:RUN_GCLIENT_SYNC="true" if ($env:TARGET_ARCH -ne 'ia32') { # only save on x64/woa to avoid contention saving $env:SAVE_GCLIENT_SRC="true" } } else { # update angle cd src\third_party\angle git remote set-url origin https://chromium.googlesource.com/angle/angle.git git fetch cd ..\..\.. } } else { # file does not exist, gclient sync, then zip $env:RUN_GCLIENT_SYNC="true" if ($env:TARGET_ARCH -ne 'ia32') { # only save on x64/woa to avoid contention saving $env:SAVE_GCLIENT_SRC="true" } } } - if "%RUN_GCLIENT_SYNC%"=="true" ( gclient sync ) - ps: >- if ($env:SAVE_GCLIENT_SRC -eq 'true') { # archive current source for future use # only run on x64/woa to avoid contention saving $(7z a $zipfile src -xr!android_webview -xr!electron -xr'!*\.git' -xr!third_party\WebKit\LayoutTests! -xr!third_party\blink\web_tests -xr!third_party\blink\perf_tests -slp -t7z -mmt=30) if ($LASTEXITCODE -ne 0) { Write-warning "Could not save source to shared drive; continuing anyway" } # build time generation of file gen/angle/angle_commit.h depends on # third_party/angle/.git # https://chromium-review.googlesource.com/c/angle/angle/+/2074924 $(7z a $zipfile src\third_party\angle\.git) if ($LASTEXITCODE -ne 0) { Write-warning "Failed to add third_party\angle\.git; continuing anyway" } # build time generation of file dawn/common/Version_autogen.h depends on third_party/dawn/.git/HEAD # https://dawn-review.googlesource.com/c/dawn/+/83901 $(7z a $zipfile src\third_party\dawn\.git) if ($LASTEXITCODE -ne 0) { Write-warning "Failed to add third_party\dawn\.git; continuing anyway" } } - cd src - set BUILD_CONFIG_PATH=//electron/build/args/%GN_CONFIG%.gn - gn gen out/Default "--args=import(\"%BUILD_CONFIG_PATH%\") import(\"%GN_GOMA_FILE%\") %GN_EXTRA_ARGS% " - gn check out/Default //electron:electron_lib - gn check out/Default //electron:electron_app - gn check out/Default //electron/shell/common/api:mojo - if DEFINED GN_GOMA_FILE (ninja -j 300 -C out/Default electron:electron_app) else (ninja -C out/Default electron:electron_app) - if "%GN_CONFIG%"=="testing" ( python C:\depot_tools\post_build_ninja_summary.py -C out\Default ) - gn gen out/ffmpeg "--args=import(\"//electron/build/args/ffmpeg.gn\") %GN_EXTRA_ARGS%" - ninja -C out/ffmpeg electron:electron_ffmpeg_zip - ninja -C out/Default electron:electron_dist_zip - ninja -C out/Default shell_browser_ui_unittests - gn desc out/Default v8:run_mksnapshot_default args > out/Default/mksnapshot_args - ninja -C out/Default electron:electron_mksnapshot_zip - cd out\Default - 7z a mksnapshot.zip mksnapshot_args gen\v8\embedded.S - cd ..\.. - ninja -C out/Default electron:hunspell_dictionaries_zip - ninja -C out/Default electron:electron_chromedriver_zip - ninja -C out/Default third_party/electron_node:headers - python %LOCAL_GOMA_DIR%\goma_ctl.py stat - python3 electron/build/profile_toolchain.py --output-json=out/Default/windows_toolchain_profile.json - 7z a node_headers.zip out\Default\gen\node_headers # Temporarily disable symbol generation on 32-bit Windows due to failures - ps: >- if ($env:GN_CONFIG -eq 'release' -And $env:TARGET_ARCH -ne 'ia32') { # Needed for msdia140.dll on 64-bit windows $env:Path += ";$pwd\third_party\llvm-build\Release+Asserts\bin" ninja -C out/Default electron:electron_symbols } - ps: >- if ($env:GN_CONFIG -eq 'release') { if ($env:TARGET_ARCH -ne 'ia32') { python electron\script\zip-symbols.py appveyor-retry appveyor PushArtifact out/Default/symbols.zip } } else { # It's useful to have pdb files when debugging testing builds that are # built on CI. 7z a pdb.zip out\Default\*.pdb } - python electron/script/zip_manifests/check-zip-manifest.py out/Default/dist.zip electron/script/zip_manifests/dist_zip.win.%TARGET_ARCH%.manifest test_script: # Workaround for https://github.com/appveyor/ci/issues/2420 - set "PATH=%PATH%;C:\Program Files\Git\mingw64\libexec\git-core" - ps: >- if ((-Not (Test-Path Env:\TEST_WOA)) -And (-Not (Test-Path Env:\ELECTRON_RELEASE)) -And ($env:GN_CONFIG -in "testing", "release")) { $env:RUN_TESTS="true" } - ps: >- if ($env:RUN_TESTS -eq 'true') { New-Item .\out\Default\gen\node_headers\Release -Type directory Copy-Item -path .\out\Default\electron.lib -destination .\out\Default\gen\node_headers\Release\node.lib } else { echo "Skipping tests for $env:GN_CONFIG build" } - cd electron # CalculateNativeWinOcclusion is disabled due to https://bugs.chromium.org/p/chromium/issues/detail?id=1139022 - if "%RUN_TESTS%"=="true" ( echo Running main test suite & node script/yarn test -- --trace-uncaught --runners=main --enable-logging=file --log-file=%cd%\electron.log --disable-features=CalculateNativeWinOcclusion ) - if "%RUN_TESTS%"=="true" ( echo Running remote test suite & node script/yarn test -- --trace-uncaught --runners=remote --runTestFilesSeperately --enable-logging=file --log-file=%cd%\electron.log --disable-features=CalculateNativeWinOcclusion ) - if "%RUN_TESTS%"=="true" ( echo Running native test suite & node script/yarn test -- --trace-uncaught --runners=native --enable-logging=file --log-file=%cd%\electron.log --disable-features=CalculateNativeWinOcclusion ) - cd .. - if "%RUN_TESTS%"=="true" ( echo Verifying non proprietary ffmpeg & python electron\script\verify-ffmpeg.py --build-dir out\Default --source-root %cd% --ffmpeg-path out\ffmpeg ) - echo "About to verify mksnapshot" - if "%RUN_TESTS%"=="true" ( echo Verifying mksnapshot & python electron\script\verify-mksnapshot.py --build-dir out\Default --source-root %cd% ) - echo "Done verifying mksnapshot" - if "%RUN_TESTS%"=="true" ( echo Verifying chromedriver & python electron\script\verify-chromedriver.py --build-dir out\Default --source-root %cd% ) - echo "Done verifying chromedriver" deploy_script: - cd electron - ps: >- if (Test-Path Env:\ELECTRON_RELEASE) { if (Test-Path Env:\UPLOAD_TO_STORAGE) { Write-Output "Uploading Electron release distribution to azure" & python script\release\uploaders\upload.py --verbose --upload_to_storage } else { Write-Output "Uploading Electron release distribution to github releases" & python script\release\uploaders\upload.py --verbose } } elseif (Test-Path Env:\TEST_WOA) { node script/release/ci-release-build.js --job=electron-woa-testing --ci=VSTS --armTest --appveyorJobId=$env:APPVEYOR_JOB_ID $env:APPVEYOR_REPO_BRANCH } on_finish: # Uncomment this lines to enable RDP #- ps: $blockRdp = $true; iex ((new-object net.webclient).DownloadString('https://raw.githubusercontent.com/appveyor/ci/master/scripts/enable-rdp.ps1')) - cd .. - if exist out\Default\windows_toolchain_profile.json ( appveyor-retry appveyor PushArtifact out\Default\windows_toolchain_profile.json ) - if exist out\Default\dist.zip (appveyor-retry appveyor PushArtifact out\Default\dist.zip) - if exist out\Default\shell_browser_ui_unittests.exe (appveyor-retry appveyor PushArtifact out\Default\shell_browser_ui_unittests.exe) - if exist out\Default\chromedriver.zip (appveyor-retry appveyor PushArtifact out\Default\chromedriver.zip) - if exist out\ffmpeg\ffmpeg.zip (appveyor-retry appveyor PushArtifact out\ffmpeg\ffmpeg.zip) - if exist node_headers.zip (appveyor-retry appveyor PushArtifact node_headers.zip) - if exist out\Default\mksnapshot.zip (appveyor-retry appveyor PushArtifact out\Default\mksnapshot.zip) - if exist out\Default\hunspell_dictionaries.zip (appveyor-retry appveyor PushArtifact out\Default\hunspell_dictionaries.zip) - if exist out\Default\electron.lib (appveyor-retry appveyor PushArtifact out\Default\electron.lib) - ps: >- if ((Test-Path "pdb.zip") -And ($env:GN_CONFIG -ne 'release')) { appveyor-retry appveyor PushArtifact pdb.zip } - if exist electron\electron.log ( appveyor-retry appveyor PushArtifact electron\electron.log )
closed
electron/electron
https://github.com/electron/electron
33,652
Symbol generation is failing for 32-bit Windows release builds for nightlies and 19-x-y
Symbol generation on 32-bit Windows release builds on nightlies and 19-x-y are failing with the following error: ``` C:/depot_tools/bootstrap-2@3_8_10_chromium_23_bin/python3/bin/python3.exe ../../electron/build/dump_syms.py ./dump_syms.exe electron.exe breakpad_symbols gen/electron/electron_app_symbols.stamp failed to get function name WriteSymbols failed. Traceback (most recent call last): File "../../electron/build/dump_syms.py", line 53, in <module> main(*sys.argv[1:]) File "../../electron/build/dump_syms.py", line 42, in main symbol_data = subprocess.check_output(args).decode(sys.stdout.encoding) File "C:\depot_tools\bootstrap-2@3_8_10_chromium_23_bin\python3\bin\lib\subprocess.py", line 415, in check_output return run(*popenargs, stdout=PIPE, timeout=timeout, check=True, File "C:\depot_tools\bootstrap-2@3_8_10_chromium_23_bin\python3\bin\lib\subprocess.py", line 516, in run raise CalledProcessError(retcode, process.args, subprocess.CalledProcessError: Command '['./dump_syms.exe', 'electron.exe']' returned non-zero exit status 1. ninja: build stopped: subcommand failed. Command exited with code 1 ``` Here's a recent nightly release build with the failure: https://ci.appveyor.com/project/electron-bot/electron-ia32-release/builds/43164264 It looks like this failure was introduced via #33454.
https://github.com/electron/electron/issues/33652
https://github.com/electron/electron/pull/34162
6063d4f8df7298b6fbc66cc71e76c04e913faaf3
c512993744145e594c9ee8d55e5c4190c943f841
2022-04-07T14:51:10Z
c++
2022-05-11T15:27:23Z
script/release/release.js
#!/usr/bin/env node if (!process.env.CI) require('dotenv-safe').load(); const args = require('minimist')(process.argv.slice(2), { boolean: [ 'validateRelease', 'verboseNugget' ], default: { verboseNugget: false } }); const fs = require('fs'); const { execSync } = require('child_process'); const got = require('got'); const pkg = require('../../package.json'); const pkgVersion = `v${pkg.version}`; const path = require('path'); const temp = require('temp').track(); const { URL } = require('url'); const { BlobServiceClient } = require('@azure/storage-blob'); const { Octokit } = require('@octokit/rest'); require('colors'); const pass = '✓'.green; const fail = '✗'.red; const { ELECTRON_DIR } = require('../lib/utils'); const getUrlHash = require('./get-url-hash'); const octokit = new Octokit({ auth: process.env.ELECTRON_GITHUB_TOKEN }); const targetRepo = pkgVersion.indexOf('nightly') > 0 ? 'nightlies' : 'electron'; let failureCount = 0; async function getDraftRelease (version, skipValidation) { const releaseInfo = await octokit.repos.listReleases({ owner: 'electron', repo: targetRepo }); const versionToCheck = version || pkgVersion; const drafts = releaseInfo.data.filter(release => { return release.tag_name === versionToCheck && release.draft === true; }); const draft = drafts[0]; if (!skipValidation) { failureCount = 0; check(drafts.length === 1, 'one draft exists', true); if (versionToCheck.indexOf('beta') > -1) { check(draft.prerelease, 'draft is a prerelease'); } check(draft.body.length > 50 && !draft.body.includes('(placeholder)'), 'draft has release notes'); check((failureCount === 0), 'Draft release looks good to go.', true); } return draft; } async function validateReleaseAssets (release, validatingRelease) { const requiredAssets = assetsForVersion(release.tag_name, validatingRelease).sort(); const extantAssets = release.assets.map(asset => asset.name).sort(); const downloadUrls = release.assets.map(asset => ({ url: asset.browser_download_url, file: asset.name })).sort((a, b) => a.file.localeCompare(b.file)); failureCount = 0; requiredAssets.forEach(asset => { check(extantAssets.includes(asset), asset); }); check((failureCount === 0), 'All required GitHub assets exist for release', true); if (!validatingRelease || !release.draft) { if (release.draft) { await verifyDraftGitHubReleaseAssets(release); } else { await verifyShasumsForRemoteFiles(downloadUrls) .catch(err => { console.log(`${fail} error verifyingShasums`, err); }); } const azRemoteFiles = azRemoteFilesForVersion(release.tag_name); await verifyShasumsForRemoteFiles(azRemoteFiles, true); } } function check (condition, statement, exitIfFail = false) { if (condition) { console.log(`${pass} ${statement}`); } else { failureCount++; console.log(`${fail} ${statement}`); if (exitIfFail) process.exit(1); } } function assetsForVersion (version, validatingRelease) { const patterns = [ `chromedriver-${version}-darwin-x64.zip`, `chromedriver-${version}-darwin-arm64.zip`, `chromedriver-${version}-linux-arm64.zip`, `chromedriver-${version}-linux-armv7l.zip`, `chromedriver-${version}-linux-x64.zip`, `chromedriver-${version}-mas-x64.zip`, `chromedriver-${version}-mas-arm64.zip`, `chromedriver-${version}-win32-ia32.zip`, `chromedriver-${version}-win32-x64.zip`, `chromedriver-${version}-win32-arm64.zip`, `electron-${version}-darwin-x64-dsym.zip`, `electron-${version}-darwin-x64-dsym-snapshot.zip`, `electron-${version}-darwin-x64-symbols.zip`, `electron-${version}-darwin-x64.zip`, `electron-${version}-darwin-arm64-dsym.zip`, `electron-${version}-darwin-arm64-dsym-snapshot.zip`, `electron-${version}-darwin-arm64-symbols.zip`, `electron-${version}-darwin-arm64.zip`, `electron-${version}-linux-arm64-symbols.zip`, `electron-${version}-linux-arm64.zip`, `electron-${version}-linux-armv7l-symbols.zip`, `electron-${version}-linux-armv7l.zip`, `electron-${version}-linux-x64-debug.zip`, `electron-${version}-linux-x64-symbols.zip`, `electron-${version}-linux-x64.zip`, `electron-${version}-mas-x64-dsym.zip`, `electron-${version}-mas-x64-dsym-snapshot.zip`, `electron-${version}-mas-x64-symbols.zip`, `electron-${version}-mas-x64.zip`, `electron-${version}-mas-arm64-dsym.zip`, `electron-${version}-mas-arm64-dsym-snapshot.zip`, `electron-${version}-mas-arm64-symbols.zip`, `electron-${version}-mas-arm64.zip`, // TODO(jkleinsc) Symbol generation on 32-bit Windows is temporarily disabled due to failures // `electron-${version}-win32-ia32-pdb.zip`, // `electron-${version}-win32-ia32-symbols.zip`, `electron-${version}-win32-ia32.zip`, `electron-${version}-win32-x64-pdb.zip`, `electron-${version}-win32-x64-symbols.zip`, `electron-${version}-win32-x64.zip`, `electron-${version}-win32-arm64-pdb.zip`, `electron-${version}-win32-arm64-symbols.zip`, `electron-${version}-win32-arm64.zip`, 'electron-api.json', 'electron.d.ts', 'hunspell_dictionaries.zip', 'libcxx_headers.zip', 'libcxxabi_headers.zip', `libcxx-objects-${version}-linux-arm64.zip`, `libcxx-objects-${version}-linux-armv7l.zip`, `libcxx-objects-${version}-linux-x64.zip`, `ffmpeg-${version}-darwin-x64.zip`, `ffmpeg-${version}-darwin-arm64.zip`, `ffmpeg-${version}-linux-arm64.zip`, `ffmpeg-${version}-linux-armv7l.zip`, `ffmpeg-${version}-linux-x64.zip`, `ffmpeg-${version}-mas-x64.zip`, `ffmpeg-${version}-mas-arm64.zip`, `ffmpeg-${version}-win32-ia32.zip`, `ffmpeg-${version}-win32-x64.zip`, `ffmpeg-${version}-win32-arm64.zip`, `mksnapshot-${version}-darwin-x64.zip`, `mksnapshot-${version}-darwin-arm64.zip`, `mksnapshot-${version}-linux-arm64-x64.zip`, `mksnapshot-${version}-linux-armv7l-x64.zip`, `mksnapshot-${version}-linux-x64.zip`, `mksnapshot-${version}-mas-x64.zip`, `mksnapshot-${version}-mas-arm64.zip`, `mksnapshot-${version}-win32-ia32.zip`, `mksnapshot-${version}-win32-x64.zip`, `mksnapshot-${version}-win32-arm64-x64.zip`, `electron-${version}-win32-ia32-toolchain-profile.zip`, `electron-${version}-win32-x64-toolchain-profile.zip`, `electron-${version}-win32-arm64-toolchain-profile.zip` ]; if (!validatingRelease) { patterns.push('SHASUMS256.txt'); } return patterns; } const cloudStoreFilePaths = (version) => [ `iojs-${version}-headers.tar.gz`, `iojs-${version}.tar.gz`, `node-${version}.tar.gz`, 'node.lib', 'x64/node.lib', 'win-x64/iojs.lib', 'win-x86/iojs.lib', 'win-arm64/iojs.lib', 'win-x64/node.lib', 'win-x86/node.lib', 'win-arm64/node.lib', 'arm64/node.lib', 'SHASUMS.txt', 'SHASUMS256.txt' ]; function azRemoteFilesForVersion (version) { const azCDN = 'https://artifacts.electronjs.org/headers/'; const versionPrefix = `${azCDN}dist/${version}/`; return cloudStoreFilePaths(version).map((filePath) => ({ file: filePath, url: `${versionPrefix}${filePath}` })); } function runScript (scriptName, scriptArgs, cwd) { const scriptCommand = `${scriptName} ${scriptArgs.join(' ')}`; const scriptOptions = { encoding: 'UTF-8' }; if (cwd) scriptOptions.cwd = cwd; try { return execSync(scriptCommand, scriptOptions); } catch (err) { console.log(`${fail} Error running ${scriptName}`, err); process.exit(1); } } function uploadNodeShasums () { console.log('Uploading Node SHASUMS file to artifacts.electronjs.org.'); const scriptPath = path.join(ELECTRON_DIR, 'script', 'release', 'uploaders', 'upload-node-checksums.py'); runScript(scriptPath, ['-v', pkgVersion]); console.log(`${pass} Done uploading Node SHASUMS file to artifacts.electronjs.org.`); } function uploadIndexJson () { console.log('Uploading index.json to artifacts.electronjs.org.'); const scriptPath = path.join(ELECTRON_DIR, 'script', 'release', 'uploaders', 'upload-index-json.py'); runScript(scriptPath, [pkgVersion]); console.log(`${pass} Done uploading index.json to artifacts.electronjs.org.`); } async function mergeShasums (pkgVersion) { // Download individual checksum files for Electron zip files from artifact storage, // concatenate them, and upload to GitHub. const connectionString = process.env.ELECTRON_ARTIFACTS_BLOB_STORAGE; if (!connectionString) { throw new Error('Please set the $ELECTRON_ARTIFACTS_BLOB_STORAGE environment variable'); } const blobServiceClient = BlobServiceClient.fromConnectionString(connectionString); const containerClient = blobServiceClient.getContainerClient('checksums-scratchpad'); const blobsIter = containerClient.listBlobsFlat({ prefix: `${pkgVersion}/` }); const shasums = []; for await (const blob of blobsIter) { if (blob.name.endsWith('.sha256sum')) { const blobClient = containerClient.getBlockBlobClient(blob.name); const response = await blobClient.downloadToBuffer(); shasums.push(response.toString('ascii').trim()); } } return shasums.join('\n'); } async function createReleaseShasums (release) { const fileName = 'SHASUMS256.txt'; const existingAssets = release.assets.filter(asset => asset.name === fileName); if (existingAssets.length > 0) { console.log(`${fileName} already exists on GitHub; deleting before creating new file.`); await octokit.repos.deleteReleaseAsset({ owner: 'electron', repo: targetRepo, asset_id: existingAssets[0].id }).catch(err => { console.log(`${fail} Error deleting ${fileName} on GitHub:`, err); }); } console.log(`Creating and uploading the release ${fileName}.`); const checksums = await mergeShasums(pkgVersion); console.log(`${pass} Generated release SHASUMS.`); const filePath = await saveShaSumFile(checksums, fileName); console.log(`${pass} Created ${fileName} file.`); await uploadShasumFile(filePath, fileName, release.id); console.log(`${pass} Successfully uploaded ${fileName} to GitHub.`); } async function uploadShasumFile (filePath, fileName, releaseId) { const uploadUrl = `https://uploads.github.com/repos/electron/${targetRepo}/releases/${releaseId}/assets{?name,label}`; return octokit.repos.uploadReleaseAsset({ url: uploadUrl, headers: { 'content-type': 'text/plain', 'content-length': fs.statSync(filePath).size }, data: fs.createReadStream(filePath), name: fileName }).catch(err => { console.log(`${fail} Error uploading ${filePath} to GitHub:`, err); process.exit(1); }); } function saveShaSumFile (checksums, fileName) { return new Promise((resolve, reject) => { temp.open(fileName, (err, info) => { if (err) { console.log(`${fail} Could not create ${fileName} file`); process.exit(1); } else { fs.writeFileSync(info.fd, checksums); fs.close(info.fd, (err) => { if (err) { console.log(`${fail} Could close ${fileName} file`); process.exit(1); } resolve(info.path); }); } }); }); } async function publishRelease (release) { return octokit.repos.updateRelease({ owner: 'electron', repo: targetRepo, release_id: release.id, tag_name: release.tag_name, draft: false }).catch(err => { console.log(`${fail} Error publishing release:`, err); process.exit(1); }); } async function makeRelease (releaseToValidate) { if (releaseToValidate) { if (releaseToValidate === true) { releaseToValidate = pkgVersion; } else { console.log('Release to validate !=== true'); } console.log(`Validating release ${releaseToValidate}`); const release = await getDraftRelease(releaseToValidate); await validateReleaseAssets(release, true); } else { let draftRelease = await getDraftRelease(); uploadNodeShasums(); uploadIndexJson(); await createReleaseShasums(draftRelease); // Fetch latest version of release before verifying draftRelease = await getDraftRelease(pkgVersion, true); await validateReleaseAssets(draftRelease); await publishRelease(draftRelease); console.log(`${pass} SUCCESS!!! Release has been published. Please run ` + '"npm run publish-to-npm" to publish release to npm.'); } } async function makeTempDir () { return new Promise((resolve, reject) => { temp.mkdir('electron-publish', (err, dirPath) => { if (err) { reject(err); } else { resolve(dirPath); } }); }); } const SHASUM_256_FILENAME = 'SHASUMS256.txt'; const SHASUM_1_FILENAME = 'SHASUMS.txt'; async function verifyDraftGitHubReleaseAssets (release) { console.log('Fetching authenticated GitHub artifact URLs to verify shasums'); const remoteFilesToHash = await Promise.all(release.assets.map(async asset => { const requestOptions = octokit.repos.getReleaseAsset.endpoint({ owner: 'electron', repo: targetRepo, asset_id: asset.id, headers: { Accept: 'application/octet-stream' } }); const { url, headers } = requestOptions; headers.authorization = `token ${process.env.ELECTRON_GITHUB_TOKEN}`; const response = await got(url, { followRedirect: false, method: 'HEAD', headers }); return { url: response.headers.location, file: asset.name }; })).catch(err => { console.log(`${fail} Error downloading files from GitHub`, err); process.exit(1); }); await verifyShasumsForRemoteFiles(remoteFilesToHash); } async function getShaSumMappingFromUrl (shaSumFileUrl, fileNamePrefix) { const response = await got(shaSumFileUrl); const raw = response.body; return raw.split('\n').map(line => line.trim()).filter(Boolean).reduce((map, line) => { const [sha, file] = line.replace(' ', ' ').split(' '); map[file.slice(fileNamePrefix.length)] = sha; return map; }, {}); } async function validateFileHashesAgainstShaSumMapping (remoteFilesWithHashes, mapping) { for (const remoteFileWithHash of remoteFilesWithHashes) { check(remoteFileWithHash.hash === mapping[remoteFileWithHash.file], `Release asset ${remoteFileWithHash.file} should have hash of ${mapping[remoteFileWithHash.file]} but found ${remoteFileWithHash.hash}`, true); } } async function verifyShasumsForRemoteFiles (remoteFilesToHash, filesAreNodeJSArtifacts = false) { console.log(`Generating SHAs for ${remoteFilesToHash.length} files to verify shasums`); // Only used for node.js artifact uploads const shaSum1File = remoteFilesToHash.find(({ file }) => file === SHASUM_1_FILENAME); // Used for both node.js artifact uploads and normal electron artifacts const shaSum256File = remoteFilesToHash.find(({ file }) => file === SHASUM_256_FILENAME); remoteFilesToHash = remoteFilesToHash.filter(({ file }) => file !== SHASUM_1_FILENAME && file !== SHASUM_256_FILENAME); const remoteFilesWithHashes = await Promise.all(remoteFilesToHash.map(async (file) => { return { hash: await getUrlHash(file.url, 'sha256'), ...file }; })); await validateFileHashesAgainstShaSumMapping(remoteFilesWithHashes, await getShaSumMappingFromUrl(shaSum256File.url, filesAreNodeJSArtifacts ? '' : '*')); if (filesAreNodeJSArtifacts) { const remoteFilesWithSha1Hashes = await Promise.all(remoteFilesToHash.map(async (file) => { return { hash: await getUrlHash(file.url, 'sha1'), ...file }; })); await validateFileHashesAgainstShaSumMapping(remoteFilesWithSha1Hashes, await getShaSumMappingFromUrl(shaSum1File.url, filesAreNodeJSArtifacts ? '' : '*')); } } makeRelease(args.validateRelease) .catch((err) => { console.error('Error occurred while making release:', err); process.exit(1); });
closed
electron/electron
https://github.com/electron/electron
33,652
Symbol generation is failing for 32-bit Windows release builds for nightlies and 19-x-y
Symbol generation on 32-bit Windows release builds on nightlies and 19-x-y are failing with the following error: ``` C:/depot_tools/bootstrap-2@3_8_10_chromium_23_bin/python3/bin/python3.exe ../../electron/build/dump_syms.py ./dump_syms.exe electron.exe breakpad_symbols gen/electron/electron_app_symbols.stamp failed to get function name WriteSymbols failed. Traceback (most recent call last): File "../../electron/build/dump_syms.py", line 53, in <module> main(*sys.argv[1:]) File "../../electron/build/dump_syms.py", line 42, in main symbol_data = subprocess.check_output(args).decode(sys.stdout.encoding) File "C:\depot_tools\bootstrap-2@3_8_10_chromium_23_bin\python3\bin\lib\subprocess.py", line 415, in check_output return run(*popenargs, stdout=PIPE, timeout=timeout, check=True, File "C:\depot_tools\bootstrap-2@3_8_10_chromium_23_bin\python3\bin\lib\subprocess.py", line 516, in run raise CalledProcessError(retcode, process.args, subprocess.CalledProcessError: Command '['./dump_syms.exe', 'electron.exe']' returned non-zero exit status 1. ninja: build stopped: subcommand failed. Command exited with code 1 ``` Here's a recent nightly release build with the failure: https://ci.appveyor.com/project/electron-bot/electron-ia32-release/builds/43164264 It looks like this failure was introduced via #33454.
https://github.com/electron/electron/issues/33652
https://github.com/electron/electron/pull/34162
6063d4f8df7298b6fbc66cc71e76c04e913faaf3
c512993744145e594c9ee8d55e5c4190c943f841
2022-04-07T14:51:10Z
c++
2022-05-11T15:27:23Z
script/release/uploaders/upload.py
#!/usr/bin/env python3 from __future__ import print_function import argparse import datetime import hashlib import json import mmap import os import shutil import subprocess from struct import Struct import sys sys.path.append( os.path.abspath(os.path.dirname(os.path.abspath(__file__)) + "/../..")) from zipfile import ZipFile from lib.config import PLATFORM, get_target_arch, \ get_zip_name, enable_verbose_mode, get_platform_key from lib.util import get_electron_branding, execute, get_electron_version, \ store_artifact, get_electron_exec, get_out_dir, \ SRC_DIR, ELECTRON_DIR, TS_NODE ELECTRON_VERSION = get_electron_version() PROJECT_NAME = get_electron_branding()['project_name'] PRODUCT_NAME = get_electron_branding()['product_name'] OUT_DIR = get_out_dir() DIST_NAME = get_zip_name(PROJECT_NAME, ELECTRON_VERSION) SYMBOLS_NAME = get_zip_name(PROJECT_NAME, ELECTRON_VERSION, 'symbols') DSYM_NAME = get_zip_name(PROJECT_NAME, ELECTRON_VERSION, 'dsym') DSYM_SNAPSHOT_NAME = get_zip_name(PROJECT_NAME, ELECTRON_VERSION, 'dsym-snapshot') PDB_NAME = get_zip_name(PROJECT_NAME, ELECTRON_VERSION, 'pdb') DEBUG_NAME = get_zip_name(PROJECT_NAME, ELECTRON_VERSION, 'debug') TOOLCHAIN_PROFILE_NAME = get_zip_name(PROJECT_NAME, ELECTRON_VERSION, 'toolchain-profile') CXX_OBJECTS_NAME = get_zip_name(PROJECT_NAME, ELECTRON_VERSION, 'libcxx_objects') def main(): args = parse_args() if args.verbose: enable_verbose_mode() if args.upload_to_storage: utcnow = datetime.datetime.utcnow() args.upload_timestamp = utcnow.strftime('%Y%m%d') build_version = get_electron_build_version() if not ELECTRON_VERSION.startswith(build_version): error = 'Tag name ({0}) should match build version ({1})\n'.format( ELECTRON_VERSION, build_version) sys.stderr.write(error) sys.stderr.flush() return 1 tag_exists = False release = get_release(args.version) if not release['draft']: tag_exists = True if not args.upload_to_storage: assert release['exists'], \ 'Release does not exist; cannot upload to GitHub!' assert tag_exists == args.overwrite, \ 'You have to pass --overwrite to overwrite a published release' # Upload Electron files. # Rename dist.zip to get_zip_name('electron', version, suffix='') electron_zip = os.path.join(OUT_DIR, DIST_NAME) shutil.copy2(os.path.join(OUT_DIR, 'dist.zip'), electron_zip) upload_electron(release, electron_zip, args) if get_target_arch() != 'mips64el': if (get_target_arch() != 'ia32' or PLATFORM != 'win32'): symbols_zip = os.path.join(OUT_DIR, SYMBOLS_NAME) shutil.copy2(os.path.join(OUT_DIR, 'symbols.zip'), symbols_zip) upload_electron(release, symbols_zip, args) if PLATFORM == 'darwin': if get_platform_key() == 'darwin' and get_target_arch() == 'x64': api_path = os.path.join(ELECTRON_DIR, 'electron-api.json') upload_electron(release, api_path, args) ts_defs_path = os.path.join(ELECTRON_DIR, 'electron.d.ts') upload_electron(release, ts_defs_path, args) dsym_zip = os.path.join(OUT_DIR, DSYM_NAME) shutil.copy2(os.path.join(OUT_DIR, 'dsym.zip'), dsym_zip) upload_electron(release, dsym_zip, args) dsym_snaphot_zip = os.path.join(OUT_DIR, DSYM_SNAPSHOT_NAME) shutil.copy2(os.path.join(OUT_DIR, 'dsym-snapshot.zip'), dsym_snaphot_zip) upload_electron(release, dsym_snaphot_zip, args) elif PLATFORM == 'win32': if get_target_arch() != 'ia32': pdb_zip = os.path.join(OUT_DIR, PDB_NAME) shutil.copy2(os.path.join(OUT_DIR, 'pdb.zip'), pdb_zip) upload_electron(release, pdb_zip, args) elif PLATFORM == 'linux': debug_zip = os.path.join(OUT_DIR, DEBUG_NAME) shutil.copy2(os.path.join(OUT_DIR, 'debug.zip'), debug_zip) upload_electron(release, debug_zip, args) # Upload libcxx_objects.zip for linux only libcxx_objects = get_zip_name('libcxx-objects', ELECTRON_VERSION) libcxx_objects_zip = os.path.join(OUT_DIR, libcxx_objects) shutil.copy2(os.path.join(OUT_DIR, 'libcxx_objects.zip'), libcxx_objects_zip) upload_electron(release, libcxx_objects_zip, args) # Upload headers.zip and abi_headers.zip as non-platform specific if get_target_arch() == "x64": cxx_headers_zip = os.path.join(OUT_DIR, 'libcxx_headers.zip') upload_electron(release, cxx_headers_zip, args) abi_headers_zip = os.path.join(OUT_DIR, 'libcxxabi_headers.zip') upload_electron(release, abi_headers_zip, args) # Upload free version of ffmpeg. ffmpeg = get_zip_name('ffmpeg', ELECTRON_VERSION) ffmpeg_zip = os.path.join(OUT_DIR, ffmpeg) ffmpeg_build_path = os.path.join(SRC_DIR, 'out', 'ffmpeg', 'ffmpeg.zip') shutil.copy2(ffmpeg_build_path, ffmpeg_zip) upload_electron(release, ffmpeg_zip, args) chromedriver = get_zip_name('chromedriver', ELECTRON_VERSION) chromedriver_zip = os.path.join(OUT_DIR, chromedriver) shutil.copy2(os.path.join(OUT_DIR, 'chromedriver.zip'), chromedriver_zip) upload_electron(release, chromedriver_zip, args) mksnapshot = get_zip_name('mksnapshot', ELECTRON_VERSION) mksnapshot_zip = os.path.join(OUT_DIR, mksnapshot) if get_target_arch().startswith('arm') and PLATFORM != 'darwin': # Upload the x64 binary for arm/arm64 mksnapshot mksnapshot = get_zip_name('mksnapshot', ELECTRON_VERSION, 'x64') mksnapshot_zip = os.path.join(OUT_DIR, mksnapshot) shutil.copy2(os.path.join(OUT_DIR, 'mksnapshot.zip'), mksnapshot_zip) upload_electron(release, mksnapshot_zip, args) if PLATFORM == 'linux' and get_target_arch() == 'x64': # Upload the hunspell dictionaries only from the linux x64 build hunspell_dictionaries_zip = os.path.join( OUT_DIR, 'hunspell_dictionaries.zip') upload_electron(release, hunspell_dictionaries_zip, args) if not tag_exists and not args.upload_to_storage: # Upload symbols to symbol server. run_python_upload_script('upload-symbols.py') if PLATFORM == 'win32': run_python_upload_script('upload-node-headers.py', '-v', args.version) if PLATFORM == 'win32': toolchain_profile_zip = os.path.join(OUT_DIR, TOOLCHAIN_PROFILE_NAME) with ZipFile(toolchain_profile_zip, 'w') as myzip: myzip.write( os.path.join(OUT_DIR, 'windows_toolchain_profile.json'), 'toolchain_profile.json') upload_electron(release, toolchain_profile_zip, args) return 0 def parse_args(): parser = argparse.ArgumentParser(description='upload distribution file') parser.add_argument('-v', '--version', help='Specify the version', default=ELECTRON_VERSION) parser.add_argument('-o', '--overwrite', help='Overwrite a published release', action='store_true') parser.add_argument('-p', '--publish-release', help='Publish the release', action='store_true') parser.add_argument('-s', '--upload_to_storage', help='Upload assets to azure bucket', dest='upload_to_storage', action='store_true', default=False, required=False) parser.add_argument('--verbose', action='store_true', help='Mooooorreee logs') return parser.parse_args() def run_python_upload_script(script, *args): script_path = os.path.join( ELECTRON_DIR, 'script', 'release', 'uploaders', script) print(execute([sys.executable, script_path] + list(args))) def get_electron_build_version(): if get_target_arch().startswith('arm') or 'CI' in os.environ: # In CI we just build as told. return ELECTRON_VERSION electron = get_electron_exec() return subprocess.check_output([electron, '--version']).strip() class NonZipFileError(ValueError): """Raised when a given file does not appear to be a zip""" def zero_zip_date_time(fname): """ Wrap strip-zip zero_zip_date_time within a file opening operation """ try: with open(fname, 'r+b') as f: _zero_zip_date_time(f) except Exception: # pylint: disable=W0707 raise NonZipFileError(fname) def _zero_zip_date_time(zip_): def purify_extra_data(mm, offset, length, compressed_size=0): extra_header_struct = Struct("<HH") # 0. id # 1. length STRIPZIP_OPTION_HEADER = 0xFFFF EXTENDED_TIME_DATA = 0x5455 # Some sort of extended time data, see # ftp://ftp.info-zip.org/pub/infozip/src/zip30.zip ./proginfo/extrafld.txt # fallthrough UNIX_EXTRA_DATA = 0x7875 # Unix extra data; UID / GID stuff, see # ftp://ftp.info-zip.org/pub/infozip/src/zip30.zip ./proginfo/extrafld.txt ZIP64_EXTRA_HEADER = 0x0001 zip64_extra_struct = Struct("<HHQQ") # ZIP64. # When a ZIP64 extra field is present this 8byte length # will override the 4byte length defined in canonical zips. # This is in the form: # - 0x0001 (header_id) # - 0x0010 [16] (header_length) # - ... (8byte uncompressed_length) # - ... (8byte compressed_length) mlen = offset + length while offset < mlen: values = list(extra_header_struct.unpack_from(mm, offset)) _, header_length = values extra_struct = Struct("<HH" + "B" * header_length) values = list(extra_struct.unpack_from(mm, offset)) header_id, header_length = values[:2] if header_id in (EXTENDED_TIME_DATA, UNIX_EXTRA_DATA): values[0] = STRIPZIP_OPTION_HEADER for i in range(2, len(values)): values[i] = 0xff extra_struct.pack_into(mm, offset, *values) if header_id == ZIP64_EXTRA_HEADER: assert header_length == 16 values = list(zip64_extra_struct.unpack_from(mm, offset)) header_id, header_length, _, compressed_size = values offset += extra_header_struct.size + header_length return compressed_size FILE_HEADER_SIGNATURE = 0x04034b50 CENDIR_HEADER_SIGNATURE = 0x02014b50 archive_size = os.fstat(zip_.fileno()).st_size signature_struct = Struct("<L") local_file_header_struct = Struct("<LHHHHHLLLHH") # 0. L signature # 1. H version_needed # 2. H gp_bits # 3. H compression_method # 4. H last_mod_time # 5. H last_mod_date # 6. L crc32 # 7. L compressed_size # 8. L uncompressed_size # 9. H name_length # 10. H extra_field_length central_directory_header_struct = Struct("<LHHHHHHLLLHHHHHLL") # 0. L signature # 1. H version_made_by # 2. H version_needed # 3. H gp_bits # 4. H compression_method # 5. H last_mod_time # 6. H last_mod_date # 7. L crc32 # 8. L compressed_size # 9. L uncompressed_size # 10. H file_name_length # 11. H extra_field_length # 12. H file_comment_length # 13. H disk_number_start # 14. H internal_attr # 15. L external_attr # 16. L rel_offset_local_header offset = 0 mm = mmap.mmap(zip_.fileno(), 0) while offset < archive_size: if signature_struct.unpack_from(mm, offset) != (FILE_HEADER_SIGNATURE,): break values = list(local_file_header_struct.unpack_from(mm, offset)) compressed_size, _, name_length, extra_field_length = values[7:11] # reset last_mod_time values[4] = 0 # reset last_mod_date values[5] = 0x21 local_file_header_struct.pack_into(mm, offset, *values) offset += local_file_header_struct.size + name_length if extra_field_length != 0: compressed_size = purify_extra_data(mm, offset, extra_field_length, compressed_size) offset += compressed_size + extra_field_length while offset < archive_size: if signature_struct.unpack_from(mm, offset) != (CENDIR_HEADER_SIGNATURE,): break values = list(central_directory_header_struct.unpack_from(mm, offset)) file_name_length, extra_field_length, file_comment_length = values[10:13] # reset last_mod_time values[5] = 0 # reset last_mod_date values[6] = 0x21 central_directory_header_struct.pack_into(mm, offset, *values) offset += central_directory_header_struct.size offset += file_name_length + extra_field_length + file_comment_length if extra_field_length != 0: purify_extra_data(mm, offset - extra_field_length, extra_field_length) if offset == 0: raise NonZipFileError(zip_.name) def upload_electron(release, file_path, args): filename = os.path.basename(file_path) # Strip zip non determinism before upload, in-place operation try: zero_zip_date_time(file_path) except NonZipFileError: pass # if upload_to_storage is set, skip github upload. # todo (vertedinde): migrate this variable to upload_to_storage if args.upload_to_storage: key_prefix = 'release-builds/{0}_{1}'.format(args.version, args.upload_timestamp) store_artifact(os.path.dirname(file_path), key_prefix, [file_path]) upload_sha256_checksum(args.version, file_path, key_prefix) return # Upload the file. upload_io_to_github(release, filename, file_path, args.version) # Upload the checksum file. upload_sha256_checksum(args.version, file_path) def upload_io_to_github(release, filename, filepath, version): print('Uploading %s to Github' % \ (filename)) script_path = os.path.join( ELECTRON_DIR, 'script', 'release', 'uploaders', 'upload-to-github.ts') execute([TS_NODE, script_path, filepath, filename, str(release['id']), version]) def upload_sha256_checksum(version, file_path, key_prefix=None): checksum_path = '{}.sha256sum'.format(file_path) if key_prefix is None: key_prefix = 'checksums-scratchpad/{0}'.format(version) sha256 = hashlib.sha256() with open(file_path, 'rb') as f: sha256.update(f.read()) filename = os.path.basename(file_path) with open(checksum_path, 'w') as checksum: checksum.write('{} *{}'.format(sha256.hexdigest(), filename)) store_artifact(os.path.dirname(checksum_path), key_prefix, [checksum_path]) def get_release(version): script_path = os.path.join( ELECTRON_DIR, 'script', 'release', 'find-github-release.js') release_info = execute(['node', script_path, version]) release = json.loads(release_info) return release if __name__ == '__main__': sys.exit(main())
closed
electron/electron
https://github.com/electron/electron
33,652
Symbol generation is failing for 32-bit Windows release builds for nightlies and 19-x-y
Symbol generation on 32-bit Windows release builds on nightlies and 19-x-y are failing with the following error: ``` C:/depot_tools/bootstrap-2@3_8_10_chromium_23_bin/python3/bin/python3.exe ../../electron/build/dump_syms.py ./dump_syms.exe electron.exe breakpad_symbols gen/electron/electron_app_symbols.stamp failed to get function name WriteSymbols failed. Traceback (most recent call last): File "../../electron/build/dump_syms.py", line 53, in <module> main(*sys.argv[1:]) File "../../electron/build/dump_syms.py", line 42, in main symbol_data = subprocess.check_output(args).decode(sys.stdout.encoding) File "C:\depot_tools\bootstrap-2@3_8_10_chromium_23_bin\python3\bin\lib\subprocess.py", line 415, in check_output return run(*popenargs, stdout=PIPE, timeout=timeout, check=True, File "C:\depot_tools\bootstrap-2@3_8_10_chromium_23_bin\python3\bin\lib\subprocess.py", line 516, in run raise CalledProcessError(retcode, process.args, subprocess.CalledProcessError: Command '['./dump_syms.exe', 'electron.exe']' returned non-zero exit status 1. ninja: build stopped: subcommand failed. Command exited with code 1 ``` Here's a recent nightly release build with the failure: https://ci.appveyor.com/project/electron-bot/electron-ia32-release/builds/43164264 It looks like this failure was introduced via #33454.
https://github.com/electron/electron/issues/33652
https://github.com/electron/electron/pull/34162
6063d4f8df7298b6fbc66cc71e76c04e913faaf3
c512993744145e594c9ee8d55e5c4190c943f841
2022-04-07T14:51:10Z
c++
2022-05-11T15:27:23Z
appveyor.yml
# The config expects the following environment variables to be set: # - "GN_CONFIG" Build type. One of {'testing', 'release'}. # - "GN_EXTRA_ARGS" Additional gn arguments for a build config, # e.g. 'target_cpu="x86"' to build for a 32bit platform. # https://gn.googlesource.com/gn/+/master/docs/reference.md#target_cpu # Don't forget to set up "NPM_CONFIG_ARCH" and "TARGET_ARCH" accordningly # if you pass a custom value for 'target_cpu'. # - "ELECTRON_RELEASE" Set it to '1' upload binaries on success. # - "NPM_CONFIG_ARCH" E.g. 'x86'. Is used to build native Node.js modules. # Must match 'target_cpu' passed to "GN_EXTRA_ARGS" and "TARGET_ARCH" value. # - "TARGET_ARCH" Choose from {'ia32', 'x64', 'arm', 'arm64', 'mips64el'}. # Is used in some publishing scripts, but does NOT affect the Electron binary. # Must match 'target_cpu' passed to "GN_EXTRA_ARGS" and "NPM_CONFIG_ARCH" value. # - "UPLOAD_TO_STORAGE" Set it to '1' upload a release to the Azure bucket. # Otherwise the release will be uploaded to the Github Releases. # (The value is only checked if "ELECTRON_RELEASE" is defined.) # # The publishing scripts expect access tokens to be defined as env vars, # but those are not covered here. # # AppVeyor docs on variables: # https://www.appveyor.com/docs/environment-variables/ # https://www.appveyor.com/docs/build-configuration/#secure-variables # https://www.appveyor.com/docs/build-configuration/#custom-environment-variables version: 1.0.{build} build_cloud: electron-16-core image: vs2019bt-16.16.11 environment: GIT_CACHE_PATH: C:\Users\electron\libcc_cache ELECTRON_OUT_DIR: Default ELECTRON_ENABLE_STACK_DUMPING: 1 ELECTRON_ALSO_LOG_TO_STDERR: 1 MOCHA_REPORTER: mocha-multi-reporters MOCHA_MULTI_REPORTERS: mocha-appveyor-reporter, tap GOMA_FALLBACK_ON_AUTH_FAILURE: true notifications: - provider: Webhook url: https://electron-mission-control.herokuapp.com/rest/appveyor-hook method: POST headers: x-mission-control-secret: secure: 90BLVPcqhJPG7d24v0q/RRray6W3wDQ8uVQlQjOHaBWkw1i8FoA1lsjr2C/v1dVok+tS2Pi6KxDctPUkwIb4T27u4RhvmcPzQhVpfwVJAG9oNtq+yKN7vzHfg7k/pojEzVdJpQLzeJGcSrZu7VY39Q== on_build_success: false on_build_failure: true on_build_status_changed: false build_script: - ps: >- if(($env:APPVEYOR_PULL_REQUEST_HEAD_REPO_NAME -split "/")[0] -eq ($env:APPVEYOR_REPO_NAME -split "/")[0]) { Write-warning "Skipping PR build for branch"; Exit-AppveyorBuild } else { node script/yarn.js install --frozen-lockfile $result = node script/doc-only-change.js --prNumber=$env:APPVEYOR_PULL_REQUEST_NUMBER --prBranch=$env:APPVEYOR_REPO_BRANCH Write-Output $result if ($result.ExitCode -eq 0) { Write-warning "Skipping build for doc only change"; Exit-AppveyorBuild } } - echo "Building $env:GN_CONFIG build" - git config --global core.longpaths true - cd .. - mkdir src - update_depot_tools.bat - ps: Move-Item $env:APPVEYOR_BUILD_FOLDER -Destination src\electron - ps: >- if (Test-Path 'env:RAW_GOMA_AUTH') { $env:GOMA_OAUTH2_CONFIG_FILE = "$pwd\.goma_oauth2_config" $env:RAW_GOMA_AUTH | Set-Content $env:GOMA_OAUTH2_CONFIG_FILE } - git clone https://github.com/electron/build-tools.git - cd build-tools - npm install - mkdir third_party - ps: >- node -e "require('./src/utils/goma.js').downloadAndPrepare({ gomaOneForAll: true })" - ps: $env:GN_GOMA_FILE = node -e "console.log(require('./src/utils/goma.js').gnFilePath)" - ps: $env:LOCAL_GOMA_DIR = node -e "console.log(require('./src/utils/goma.js').dir)" - cd .. - ps: .\src\electron\script\start-goma.ps1 -gomaDir $env:LOCAL_GOMA_DIR - ps: >- if (Test-Path 'env:RAW_GOMA_AUTH') { $goma_login = python $env:LOCAL_GOMA_DIR\goma_auth.py info if ($goma_login -eq 'Login as Fermi Planck') { Write-warning "Goma authentication is correct"; } else { Write-warning "WARNING!!!!!! Goma authentication is incorrect; please update Goma auth token."; $host.SetShouldExit(1) } } - ps: $env:CHROMIUM_BUILDTOOLS_PATH="$pwd\src\buildtools" - ps: >- if ($env:GN_CONFIG -ne 'release') { $env:NINJA_STATUS="[%r processes, %f/%t @ %o/s : %es] " } - >- gclient config --name "src\electron" --unmanaged %GCLIENT_EXTRA_ARGS% "https://github.com/electron/electron" - ps: >- if ($env:GN_CONFIG -eq 'release') { $env:RUN_GCLIENT_SYNC="true" } else { cd src\electron node script\generate-deps-hash.js $depshash = Get-Content .\.depshash -Raw $zipfile = "Z:\$depshash.7z" cd ..\.. if (Test-Path -Path $zipfile) { # file exists, unzip and then gclient sync 7z x -y $zipfile -mmt=30 -aoa if (-not (Test-Path -Path "src\buildtools")) { # the zip file must be corrupt - resync $env:RUN_GCLIENT_SYNC="true" if ($env:TARGET_ARCH -ne 'ia32') { # only save on x64/woa to avoid contention saving $env:SAVE_GCLIENT_SRC="true" } } else { # update angle cd src\third_party\angle git remote set-url origin https://chromium.googlesource.com/angle/angle.git git fetch cd ..\..\.. } } else { # file does not exist, gclient sync, then zip $env:RUN_GCLIENT_SYNC="true" if ($env:TARGET_ARCH -ne 'ia32') { # only save on x64/woa to avoid contention saving $env:SAVE_GCLIENT_SRC="true" } } } - if "%RUN_GCLIENT_SYNC%"=="true" ( gclient sync ) - ps: >- if ($env:SAVE_GCLIENT_SRC -eq 'true') { # archive current source for future use # only run on x64/woa to avoid contention saving $(7z a $zipfile src -xr!android_webview -xr!electron -xr'!*\.git' -xr!third_party\WebKit\LayoutTests! -xr!third_party\blink\web_tests -xr!third_party\blink\perf_tests -slp -t7z -mmt=30) if ($LASTEXITCODE -ne 0) { Write-warning "Could not save source to shared drive; continuing anyway" } # build time generation of file gen/angle/angle_commit.h depends on # third_party/angle/.git # https://chromium-review.googlesource.com/c/angle/angle/+/2074924 $(7z a $zipfile src\third_party\angle\.git) if ($LASTEXITCODE -ne 0) { Write-warning "Failed to add third_party\angle\.git; continuing anyway" } # build time generation of file dawn/common/Version_autogen.h depends on third_party/dawn/.git/HEAD # https://dawn-review.googlesource.com/c/dawn/+/83901 $(7z a $zipfile src\third_party\dawn\.git) if ($LASTEXITCODE -ne 0) { Write-warning "Failed to add third_party\dawn\.git; continuing anyway" } } - cd src - set BUILD_CONFIG_PATH=//electron/build/args/%GN_CONFIG%.gn - gn gen out/Default "--args=import(\"%BUILD_CONFIG_PATH%\") import(\"%GN_GOMA_FILE%\") %GN_EXTRA_ARGS% " - gn check out/Default //electron:electron_lib - gn check out/Default //electron:electron_app - gn check out/Default //electron/shell/common/api:mojo - if DEFINED GN_GOMA_FILE (ninja -j 300 -C out/Default electron:electron_app) else (ninja -C out/Default electron:electron_app) - if "%GN_CONFIG%"=="testing" ( python C:\depot_tools\post_build_ninja_summary.py -C out\Default ) - gn gen out/ffmpeg "--args=import(\"//electron/build/args/ffmpeg.gn\") %GN_EXTRA_ARGS%" - ninja -C out/ffmpeg electron:electron_ffmpeg_zip - ninja -C out/Default electron:electron_dist_zip - ninja -C out/Default shell_browser_ui_unittests - gn desc out/Default v8:run_mksnapshot_default args > out/Default/mksnapshot_args - ninja -C out/Default electron:electron_mksnapshot_zip - cd out\Default - 7z a mksnapshot.zip mksnapshot_args gen\v8\embedded.S - cd ..\.. - ninja -C out/Default electron:hunspell_dictionaries_zip - ninja -C out/Default electron:electron_chromedriver_zip - ninja -C out/Default third_party/electron_node:headers - python %LOCAL_GOMA_DIR%\goma_ctl.py stat - python3 electron/build/profile_toolchain.py --output-json=out/Default/windows_toolchain_profile.json - 7z a node_headers.zip out\Default\gen\node_headers # Temporarily disable symbol generation on 32-bit Windows due to failures - ps: >- if ($env:GN_CONFIG -eq 'release' -And $env:TARGET_ARCH -ne 'ia32') { # Needed for msdia140.dll on 64-bit windows $env:Path += ";$pwd\third_party\llvm-build\Release+Asserts\bin" ninja -C out/Default electron:electron_symbols } - ps: >- if ($env:GN_CONFIG -eq 'release') { if ($env:TARGET_ARCH -ne 'ia32') { python electron\script\zip-symbols.py appveyor-retry appveyor PushArtifact out/Default/symbols.zip } } else { # It's useful to have pdb files when debugging testing builds that are # built on CI. 7z a pdb.zip out\Default\*.pdb } - python electron/script/zip_manifests/check-zip-manifest.py out/Default/dist.zip electron/script/zip_manifests/dist_zip.win.%TARGET_ARCH%.manifest test_script: # Workaround for https://github.com/appveyor/ci/issues/2420 - set "PATH=%PATH%;C:\Program Files\Git\mingw64\libexec\git-core" - ps: >- if ((-Not (Test-Path Env:\TEST_WOA)) -And (-Not (Test-Path Env:\ELECTRON_RELEASE)) -And ($env:GN_CONFIG -in "testing", "release")) { $env:RUN_TESTS="true" } - ps: >- if ($env:RUN_TESTS -eq 'true') { New-Item .\out\Default\gen\node_headers\Release -Type directory Copy-Item -path .\out\Default\electron.lib -destination .\out\Default\gen\node_headers\Release\node.lib } else { echo "Skipping tests for $env:GN_CONFIG build" } - cd electron # CalculateNativeWinOcclusion is disabled due to https://bugs.chromium.org/p/chromium/issues/detail?id=1139022 - if "%RUN_TESTS%"=="true" ( echo Running main test suite & node script/yarn test -- --trace-uncaught --runners=main --enable-logging=file --log-file=%cd%\electron.log --disable-features=CalculateNativeWinOcclusion ) - if "%RUN_TESTS%"=="true" ( echo Running remote test suite & node script/yarn test -- --trace-uncaught --runners=remote --runTestFilesSeperately --enable-logging=file --log-file=%cd%\electron.log --disable-features=CalculateNativeWinOcclusion ) - if "%RUN_TESTS%"=="true" ( echo Running native test suite & node script/yarn test -- --trace-uncaught --runners=native --enable-logging=file --log-file=%cd%\electron.log --disable-features=CalculateNativeWinOcclusion ) - cd .. - if "%RUN_TESTS%"=="true" ( echo Verifying non proprietary ffmpeg & python electron\script\verify-ffmpeg.py --build-dir out\Default --source-root %cd% --ffmpeg-path out\ffmpeg ) - echo "About to verify mksnapshot" - if "%RUN_TESTS%"=="true" ( echo Verifying mksnapshot & python electron\script\verify-mksnapshot.py --build-dir out\Default --source-root %cd% ) - echo "Done verifying mksnapshot" - if "%RUN_TESTS%"=="true" ( echo Verifying chromedriver & python electron\script\verify-chromedriver.py --build-dir out\Default --source-root %cd% ) - echo "Done verifying chromedriver" deploy_script: - cd electron - ps: >- if (Test-Path Env:\ELECTRON_RELEASE) { if (Test-Path Env:\UPLOAD_TO_STORAGE) { Write-Output "Uploading Electron release distribution to azure" & python script\release\uploaders\upload.py --verbose --upload_to_storage } else { Write-Output "Uploading Electron release distribution to github releases" & python script\release\uploaders\upload.py --verbose } } elseif (Test-Path Env:\TEST_WOA) { node script/release/ci-release-build.js --job=electron-woa-testing --ci=VSTS --armTest --appveyorJobId=$env:APPVEYOR_JOB_ID $env:APPVEYOR_REPO_BRANCH } on_finish: # Uncomment this lines to enable RDP #- ps: $blockRdp = $true; iex ((new-object net.webclient).DownloadString('https://raw.githubusercontent.com/appveyor/ci/master/scripts/enable-rdp.ps1')) - cd .. - if exist out\Default\windows_toolchain_profile.json ( appveyor-retry appveyor PushArtifact out\Default\windows_toolchain_profile.json ) - if exist out\Default\dist.zip (appveyor-retry appveyor PushArtifact out\Default\dist.zip) - if exist out\Default\shell_browser_ui_unittests.exe (appveyor-retry appveyor PushArtifact out\Default\shell_browser_ui_unittests.exe) - if exist out\Default\chromedriver.zip (appveyor-retry appveyor PushArtifact out\Default\chromedriver.zip) - if exist out\ffmpeg\ffmpeg.zip (appveyor-retry appveyor PushArtifact out\ffmpeg\ffmpeg.zip) - if exist node_headers.zip (appveyor-retry appveyor PushArtifact node_headers.zip) - if exist out\Default\mksnapshot.zip (appveyor-retry appveyor PushArtifact out\Default\mksnapshot.zip) - if exist out\Default\hunspell_dictionaries.zip (appveyor-retry appveyor PushArtifact out\Default\hunspell_dictionaries.zip) - if exist out\Default\electron.lib (appveyor-retry appveyor PushArtifact out\Default\electron.lib) - ps: >- if ((Test-Path "pdb.zip") -And ($env:GN_CONFIG -ne 'release')) { appveyor-retry appveyor PushArtifact pdb.zip } - if exist electron\electron.log ( appveyor-retry appveyor PushArtifact electron\electron.log )
closed
electron/electron
https://github.com/electron/electron
33,652
Symbol generation is failing for 32-bit Windows release builds for nightlies and 19-x-y
Symbol generation on 32-bit Windows release builds on nightlies and 19-x-y are failing with the following error: ``` C:/depot_tools/bootstrap-2@3_8_10_chromium_23_bin/python3/bin/python3.exe ../../electron/build/dump_syms.py ./dump_syms.exe electron.exe breakpad_symbols gen/electron/electron_app_symbols.stamp failed to get function name WriteSymbols failed. Traceback (most recent call last): File "../../electron/build/dump_syms.py", line 53, in <module> main(*sys.argv[1:]) File "../../electron/build/dump_syms.py", line 42, in main symbol_data = subprocess.check_output(args).decode(sys.stdout.encoding) File "C:\depot_tools\bootstrap-2@3_8_10_chromium_23_bin\python3\bin\lib\subprocess.py", line 415, in check_output return run(*popenargs, stdout=PIPE, timeout=timeout, check=True, File "C:\depot_tools\bootstrap-2@3_8_10_chromium_23_bin\python3\bin\lib\subprocess.py", line 516, in run raise CalledProcessError(retcode, process.args, subprocess.CalledProcessError: Command '['./dump_syms.exe', 'electron.exe']' returned non-zero exit status 1. ninja: build stopped: subcommand failed. Command exited with code 1 ``` Here's a recent nightly release build with the failure: https://ci.appveyor.com/project/electron-bot/electron-ia32-release/builds/43164264 It looks like this failure was introduced via #33454.
https://github.com/electron/electron/issues/33652
https://github.com/electron/electron/pull/34162
6063d4f8df7298b6fbc66cc71e76c04e913faaf3
c512993744145e594c9ee8d55e5c4190c943f841
2022-04-07T14:51:10Z
c++
2022-05-11T15:27:23Z
script/release/release.js
#!/usr/bin/env node if (!process.env.CI) require('dotenv-safe').load(); const args = require('minimist')(process.argv.slice(2), { boolean: [ 'validateRelease', 'verboseNugget' ], default: { verboseNugget: false } }); const fs = require('fs'); const { execSync } = require('child_process'); const got = require('got'); const pkg = require('../../package.json'); const pkgVersion = `v${pkg.version}`; const path = require('path'); const temp = require('temp').track(); const { URL } = require('url'); const { BlobServiceClient } = require('@azure/storage-blob'); const { Octokit } = require('@octokit/rest'); require('colors'); const pass = '✓'.green; const fail = '✗'.red; const { ELECTRON_DIR } = require('../lib/utils'); const getUrlHash = require('./get-url-hash'); const octokit = new Octokit({ auth: process.env.ELECTRON_GITHUB_TOKEN }); const targetRepo = pkgVersion.indexOf('nightly') > 0 ? 'nightlies' : 'electron'; let failureCount = 0; async function getDraftRelease (version, skipValidation) { const releaseInfo = await octokit.repos.listReleases({ owner: 'electron', repo: targetRepo }); const versionToCheck = version || pkgVersion; const drafts = releaseInfo.data.filter(release => { return release.tag_name === versionToCheck && release.draft === true; }); const draft = drafts[0]; if (!skipValidation) { failureCount = 0; check(drafts.length === 1, 'one draft exists', true); if (versionToCheck.indexOf('beta') > -1) { check(draft.prerelease, 'draft is a prerelease'); } check(draft.body.length > 50 && !draft.body.includes('(placeholder)'), 'draft has release notes'); check((failureCount === 0), 'Draft release looks good to go.', true); } return draft; } async function validateReleaseAssets (release, validatingRelease) { const requiredAssets = assetsForVersion(release.tag_name, validatingRelease).sort(); const extantAssets = release.assets.map(asset => asset.name).sort(); const downloadUrls = release.assets.map(asset => ({ url: asset.browser_download_url, file: asset.name })).sort((a, b) => a.file.localeCompare(b.file)); failureCount = 0; requiredAssets.forEach(asset => { check(extantAssets.includes(asset), asset); }); check((failureCount === 0), 'All required GitHub assets exist for release', true); if (!validatingRelease || !release.draft) { if (release.draft) { await verifyDraftGitHubReleaseAssets(release); } else { await verifyShasumsForRemoteFiles(downloadUrls) .catch(err => { console.log(`${fail} error verifyingShasums`, err); }); } const azRemoteFiles = azRemoteFilesForVersion(release.tag_name); await verifyShasumsForRemoteFiles(azRemoteFiles, true); } } function check (condition, statement, exitIfFail = false) { if (condition) { console.log(`${pass} ${statement}`); } else { failureCount++; console.log(`${fail} ${statement}`); if (exitIfFail) process.exit(1); } } function assetsForVersion (version, validatingRelease) { const patterns = [ `chromedriver-${version}-darwin-x64.zip`, `chromedriver-${version}-darwin-arm64.zip`, `chromedriver-${version}-linux-arm64.zip`, `chromedriver-${version}-linux-armv7l.zip`, `chromedriver-${version}-linux-x64.zip`, `chromedriver-${version}-mas-x64.zip`, `chromedriver-${version}-mas-arm64.zip`, `chromedriver-${version}-win32-ia32.zip`, `chromedriver-${version}-win32-x64.zip`, `chromedriver-${version}-win32-arm64.zip`, `electron-${version}-darwin-x64-dsym.zip`, `electron-${version}-darwin-x64-dsym-snapshot.zip`, `electron-${version}-darwin-x64-symbols.zip`, `electron-${version}-darwin-x64.zip`, `electron-${version}-darwin-arm64-dsym.zip`, `electron-${version}-darwin-arm64-dsym-snapshot.zip`, `electron-${version}-darwin-arm64-symbols.zip`, `electron-${version}-darwin-arm64.zip`, `electron-${version}-linux-arm64-symbols.zip`, `electron-${version}-linux-arm64.zip`, `electron-${version}-linux-armv7l-symbols.zip`, `electron-${version}-linux-armv7l.zip`, `electron-${version}-linux-x64-debug.zip`, `electron-${version}-linux-x64-symbols.zip`, `electron-${version}-linux-x64.zip`, `electron-${version}-mas-x64-dsym.zip`, `electron-${version}-mas-x64-dsym-snapshot.zip`, `electron-${version}-mas-x64-symbols.zip`, `electron-${version}-mas-x64.zip`, `electron-${version}-mas-arm64-dsym.zip`, `electron-${version}-mas-arm64-dsym-snapshot.zip`, `electron-${version}-mas-arm64-symbols.zip`, `electron-${version}-mas-arm64.zip`, // TODO(jkleinsc) Symbol generation on 32-bit Windows is temporarily disabled due to failures // `electron-${version}-win32-ia32-pdb.zip`, // `electron-${version}-win32-ia32-symbols.zip`, `electron-${version}-win32-ia32.zip`, `electron-${version}-win32-x64-pdb.zip`, `electron-${version}-win32-x64-symbols.zip`, `electron-${version}-win32-x64.zip`, `electron-${version}-win32-arm64-pdb.zip`, `electron-${version}-win32-arm64-symbols.zip`, `electron-${version}-win32-arm64.zip`, 'electron-api.json', 'electron.d.ts', 'hunspell_dictionaries.zip', 'libcxx_headers.zip', 'libcxxabi_headers.zip', `libcxx-objects-${version}-linux-arm64.zip`, `libcxx-objects-${version}-linux-armv7l.zip`, `libcxx-objects-${version}-linux-x64.zip`, `ffmpeg-${version}-darwin-x64.zip`, `ffmpeg-${version}-darwin-arm64.zip`, `ffmpeg-${version}-linux-arm64.zip`, `ffmpeg-${version}-linux-armv7l.zip`, `ffmpeg-${version}-linux-x64.zip`, `ffmpeg-${version}-mas-x64.zip`, `ffmpeg-${version}-mas-arm64.zip`, `ffmpeg-${version}-win32-ia32.zip`, `ffmpeg-${version}-win32-x64.zip`, `ffmpeg-${version}-win32-arm64.zip`, `mksnapshot-${version}-darwin-x64.zip`, `mksnapshot-${version}-darwin-arm64.zip`, `mksnapshot-${version}-linux-arm64-x64.zip`, `mksnapshot-${version}-linux-armv7l-x64.zip`, `mksnapshot-${version}-linux-x64.zip`, `mksnapshot-${version}-mas-x64.zip`, `mksnapshot-${version}-mas-arm64.zip`, `mksnapshot-${version}-win32-ia32.zip`, `mksnapshot-${version}-win32-x64.zip`, `mksnapshot-${version}-win32-arm64-x64.zip`, `electron-${version}-win32-ia32-toolchain-profile.zip`, `electron-${version}-win32-x64-toolchain-profile.zip`, `electron-${version}-win32-arm64-toolchain-profile.zip` ]; if (!validatingRelease) { patterns.push('SHASUMS256.txt'); } return patterns; } const cloudStoreFilePaths = (version) => [ `iojs-${version}-headers.tar.gz`, `iojs-${version}.tar.gz`, `node-${version}.tar.gz`, 'node.lib', 'x64/node.lib', 'win-x64/iojs.lib', 'win-x86/iojs.lib', 'win-arm64/iojs.lib', 'win-x64/node.lib', 'win-x86/node.lib', 'win-arm64/node.lib', 'arm64/node.lib', 'SHASUMS.txt', 'SHASUMS256.txt' ]; function azRemoteFilesForVersion (version) { const azCDN = 'https://artifacts.electronjs.org/headers/'; const versionPrefix = `${azCDN}dist/${version}/`; return cloudStoreFilePaths(version).map((filePath) => ({ file: filePath, url: `${versionPrefix}${filePath}` })); } function runScript (scriptName, scriptArgs, cwd) { const scriptCommand = `${scriptName} ${scriptArgs.join(' ')}`; const scriptOptions = { encoding: 'UTF-8' }; if (cwd) scriptOptions.cwd = cwd; try { return execSync(scriptCommand, scriptOptions); } catch (err) { console.log(`${fail} Error running ${scriptName}`, err); process.exit(1); } } function uploadNodeShasums () { console.log('Uploading Node SHASUMS file to artifacts.electronjs.org.'); const scriptPath = path.join(ELECTRON_DIR, 'script', 'release', 'uploaders', 'upload-node-checksums.py'); runScript(scriptPath, ['-v', pkgVersion]); console.log(`${pass} Done uploading Node SHASUMS file to artifacts.electronjs.org.`); } function uploadIndexJson () { console.log('Uploading index.json to artifacts.electronjs.org.'); const scriptPath = path.join(ELECTRON_DIR, 'script', 'release', 'uploaders', 'upload-index-json.py'); runScript(scriptPath, [pkgVersion]); console.log(`${pass} Done uploading index.json to artifacts.electronjs.org.`); } async function mergeShasums (pkgVersion) { // Download individual checksum files for Electron zip files from artifact storage, // concatenate them, and upload to GitHub. const connectionString = process.env.ELECTRON_ARTIFACTS_BLOB_STORAGE; if (!connectionString) { throw new Error('Please set the $ELECTRON_ARTIFACTS_BLOB_STORAGE environment variable'); } const blobServiceClient = BlobServiceClient.fromConnectionString(connectionString); const containerClient = blobServiceClient.getContainerClient('checksums-scratchpad'); const blobsIter = containerClient.listBlobsFlat({ prefix: `${pkgVersion}/` }); const shasums = []; for await (const blob of blobsIter) { if (blob.name.endsWith('.sha256sum')) { const blobClient = containerClient.getBlockBlobClient(blob.name); const response = await blobClient.downloadToBuffer(); shasums.push(response.toString('ascii').trim()); } } return shasums.join('\n'); } async function createReleaseShasums (release) { const fileName = 'SHASUMS256.txt'; const existingAssets = release.assets.filter(asset => asset.name === fileName); if (existingAssets.length > 0) { console.log(`${fileName} already exists on GitHub; deleting before creating new file.`); await octokit.repos.deleteReleaseAsset({ owner: 'electron', repo: targetRepo, asset_id: existingAssets[0].id }).catch(err => { console.log(`${fail} Error deleting ${fileName} on GitHub:`, err); }); } console.log(`Creating and uploading the release ${fileName}.`); const checksums = await mergeShasums(pkgVersion); console.log(`${pass} Generated release SHASUMS.`); const filePath = await saveShaSumFile(checksums, fileName); console.log(`${pass} Created ${fileName} file.`); await uploadShasumFile(filePath, fileName, release.id); console.log(`${pass} Successfully uploaded ${fileName} to GitHub.`); } async function uploadShasumFile (filePath, fileName, releaseId) { const uploadUrl = `https://uploads.github.com/repos/electron/${targetRepo}/releases/${releaseId}/assets{?name,label}`; return octokit.repos.uploadReleaseAsset({ url: uploadUrl, headers: { 'content-type': 'text/plain', 'content-length': fs.statSync(filePath).size }, data: fs.createReadStream(filePath), name: fileName }).catch(err => { console.log(`${fail} Error uploading ${filePath} to GitHub:`, err); process.exit(1); }); } function saveShaSumFile (checksums, fileName) { return new Promise((resolve, reject) => { temp.open(fileName, (err, info) => { if (err) { console.log(`${fail} Could not create ${fileName} file`); process.exit(1); } else { fs.writeFileSync(info.fd, checksums); fs.close(info.fd, (err) => { if (err) { console.log(`${fail} Could close ${fileName} file`); process.exit(1); } resolve(info.path); }); } }); }); } async function publishRelease (release) { return octokit.repos.updateRelease({ owner: 'electron', repo: targetRepo, release_id: release.id, tag_name: release.tag_name, draft: false }).catch(err => { console.log(`${fail} Error publishing release:`, err); process.exit(1); }); } async function makeRelease (releaseToValidate) { if (releaseToValidate) { if (releaseToValidate === true) { releaseToValidate = pkgVersion; } else { console.log('Release to validate !=== true'); } console.log(`Validating release ${releaseToValidate}`); const release = await getDraftRelease(releaseToValidate); await validateReleaseAssets(release, true); } else { let draftRelease = await getDraftRelease(); uploadNodeShasums(); uploadIndexJson(); await createReleaseShasums(draftRelease); // Fetch latest version of release before verifying draftRelease = await getDraftRelease(pkgVersion, true); await validateReleaseAssets(draftRelease); await publishRelease(draftRelease); console.log(`${pass} SUCCESS!!! Release has been published. Please run ` + '"npm run publish-to-npm" to publish release to npm.'); } } async function makeTempDir () { return new Promise((resolve, reject) => { temp.mkdir('electron-publish', (err, dirPath) => { if (err) { reject(err); } else { resolve(dirPath); } }); }); } const SHASUM_256_FILENAME = 'SHASUMS256.txt'; const SHASUM_1_FILENAME = 'SHASUMS.txt'; async function verifyDraftGitHubReleaseAssets (release) { console.log('Fetching authenticated GitHub artifact URLs to verify shasums'); const remoteFilesToHash = await Promise.all(release.assets.map(async asset => { const requestOptions = octokit.repos.getReleaseAsset.endpoint({ owner: 'electron', repo: targetRepo, asset_id: asset.id, headers: { Accept: 'application/octet-stream' } }); const { url, headers } = requestOptions; headers.authorization = `token ${process.env.ELECTRON_GITHUB_TOKEN}`; const response = await got(url, { followRedirect: false, method: 'HEAD', headers }); return { url: response.headers.location, file: asset.name }; })).catch(err => { console.log(`${fail} Error downloading files from GitHub`, err); process.exit(1); }); await verifyShasumsForRemoteFiles(remoteFilesToHash); } async function getShaSumMappingFromUrl (shaSumFileUrl, fileNamePrefix) { const response = await got(shaSumFileUrl); const raw = response.body; return raw.split('\n').map(line => line.trim()).filter(Boolean).reduce((map, line) => { const [sha, file] = line.replace(' ', ' ').split(' '); map[file.slice(fileNamePrefix.length)] = sha; return map; }, {}); } async function validateFileHashesAgainstShaSumMapping (remoteFilesWithHashes, mapping) { for (const remoteFileWithHash of remoteFilesWithHashes) { check(remoteFileWithHash.hash === mapping[remoteFileWithHash.file], `Release asset ${remoteFileWithHash.file} should have hash of ${mapping[remoteFileWithHash.file]} but found ${remoteFileWithHash.hash}`, true); } } async function verifyShasumsForRemoteFiles (remoteFilesToHash, filesAreNodeJSArtifacts = false) { console.log(`Generating SHAs for ${remoteFilesToHash.length} files to verify shasums`); // Only used for node.js artifact uploads const shaSum1File = remoteFilesToHash.find(({ file }) => file === SHASUM_1_FILENAME); // Used for both node.js artifact uploads and normal electron artifacts const shaSum256File = remoteFilesToHash.find(({ file }) => file === SHASUM_256_FILENAME); remoteFilesToHash = remoteFilesToHash.filter(({ file }) => file !== SHASUM_1_FILENAME && file !== SHASUM_256_FILENAME); const remoteFilesWithHashes = await Promise.all(remoteFilesToHash.map(async (file) => { return { hash: await getUrlHash(file.url, 'sha256'), ...file }; })); await validateFileHashesAgainstShaSumMapping(remoteFilesWithHashes, await getShaSumMappingFromUrl(shaSum256File.url, filesAreNodeJSArtifacts ? '' : '*')); if (filesAreNodeJSArtifacts) { const remoteFilesWithSha1Hashes = await Promise.all(remoteFilesToHash.map(async (file) => { return { hash: await getUrlHash(file.url, 'sha1'), ...file }; })); await validateFileHashesAgainstShaSumMapping(remoteFilesWithSha1Hashes, await getShaSumMappingFromUrl(shaSum1File.url, filesAreNodeJSArtifacts ? '' : '*')); } } makeRelease(args.validateRelease) .catch((err) => { console.error('Error occurred while making release:', err); process.exit(1); });
closed
electron/electron
https://github.com/electron/electron
33,652
Symbol generation is failing for 32-bit Windows release builds for nightlies and 19-x-y
Symbol generation on 32-bit Windows release builds on nightlies and 19-x-y are failing with the following error: ``` C:/depot_tools/bootstrap-2@3_8_10_chromium_23_bin/python3/bin/python3.exe ../../electron/build/dump_syms.py ./dump_syms.exe electron.exe breakpad_symbols gen/electron/electron_app_symbols.stamp failed to get function name WriteSymbols failed. Traceback (most recent call last): File "../../electron/build/dump_syms.py", line 53, in <module> main(*sys.argv[1:]) File "../../electron/build/dump_syms.py", line 42, in main symbol_data = subprocess.check_output(args).decode(sys.stdout.encoding) File "C:\depot_tools\bootstrap-2@3_8_10_chromium_23_bin\python3\bin\lib\subprocess.py", line 415, in check_output return run(*popenargs, stdout=PIPE, timeout=timeout, check=True, File "C:\depot_tools\bootstrap-2@3_8_10_chromium_23_bin\python3\bin\lib\subprocess.py", line 516, in run raise CalledProcessError(retcode, process.args, subprocess.CalledProcessError: Command '['./dump_syms.exe', 'electron.exe']' returned non-zero exit status 1. ninja: build stopped: subcommand failed. Command exited with code 1 ``` Here's a recent nightly release build with the failure: https://ci.appveyor.com/project/electron-bot/electron-ia32-release/builds/43164264 It looks like this failure was introduced via #33454.
https://github.com/electron/electron/issues/33652
https://github.com/electron/electron/pull/34162
6063d4f8df7298b6fbc66cc71e76c04e913faaf3
c512993744145e594c9ee8d55e5c4190c943f841
2022-04-07T14:51:10Z
c++
2022-05-11T15:27:23Z
script/release/uploaders/upload.py
#!/usr/bin/env python3 from __future__ import print_function import argparse import datetime import hashlib import json import mmap import os import shutil import subprocess from struct import Struct import sys sys.path.append( os.path.abspath(os.path.dirname(os.path.abspath(__file__)) + "/../..")) from zipfile import ZipFile from lib.config import PLATFORM, get_target_arch, \ get_zip_name, enable_verbose_mode, get_platform_key from lib.util import get_electron_branding, execute, get_electron_version, \ store_artifact, get_electron_exec, get_out_dir, \ SRC_DIR, ELECTRON_DIR, TS_NODE ELECTRON_VERSION = get_electron_version() PROJECT_NAME = get_electron_branding()['project_name'] PRODUCT_NAME = get_electron_branding()['product_name'] OUT_DIR = get_out_dir() DIST_NAME = get_zip_name(PROJECT_NAME, ELECTRON_VERSION) SYMBOLS_NAME = get_zip_name(PROJECT_NAME, ELECTRON_VERSION, 'symbols') DSYM_NAME = get_zip_name(PROJECT_NAME, ELECTRON_VERSION, 'dsym') DSYM_SNAPSHOT_NAME = get_zip_name(PROJECT_NAME, ELECTRON_VERSION, 'dsym-snapshot') PDB_NAME = get_zip_name(PROJECT_NAME, ELECTRON_VERSION, 'pdb') DEBUG_NAME = get_zip_name(PROJECT_NAME, ELECTRON_VERSION, 'debug') TOOLCHAIN_PROFILE_NAME = get_zip_name(PROJECT_NAME, ELECTRON_VERSION, 'toolchain-profile') CXX_OBJECTS_NAME = get_zip_name(PROJECT_NAME, ELECTRON_VERSION, 'libcxx_objects') def main(): args = parse_args() if args.verbose: enable_verbose_mode() if args.upload_to_storage: utcnow = datetime.datetime.utcnow() args.upload_timestamp = utcnow.strftime('%Y%m%d') build_version = get_electron_build_version() if not ELECTRON_VERSION.startswith(build_version): error = 'Tag name ({0}) should match build version ({1})\n'.format( ELECTRON_VERSION, build_version) sys.stderr.write(error) sys.stderr.flush() return 1 tag_exists = False release = get_release(args.version) if not release['draft']: tag_exists = True if not args.upload_to_storage: assert release['exists'], \ 'Release does not exist; cannot upload to GitHub!' assert tag_exists == args.overwrite, \ 'You have to pass --overwrite to overwrite a published release' # Upload Electron files. # Rename dist.zip to get_zip_name('electron', version, suffix='') electron_zip = os.path.join(OUT_DIR, DIST_NAME) shutil.copy2(os.path.join(OUT_DIR, 'dist.zip'), electron_zip) upload_electron(release, electron_zip, args) if get_target_arch() != 'mips64el': if (get_target_arch() != 'ia32' or PLATFORM != 'win32'): symbols_zip = os.path.join(OUT_DIR, SYMBOLS_NAME) shutil.copy2(os.path.join(OUT_DIR, 'symbols.zip'), symbols_zip) upload_electron(release, symbols_zip, args) if PLATFORM == 'darwin': if get_platform_key() == 'darwin' and get_target_arch() == 'x64': api_path = os.path.join(ELECTRON_DIR, 'electron-api.json') upload_electron(release, api_path, args) ts_defs_path = os.path.join(ELECTRON_DIR, 'electron.d.ts') upload_electron(release, ts_defs_path, args) dsym_zip = os.path.join(OUT_DIR, DSYM_NAME) shutil.copy2(os.path.join(OUT_DIR, 'dsym.zip'), dsym_zip) upload_electron(release, dsym_zip, args) dsym_snaphot_zip = os.path.join(OUT_DIR, DSYM_SNAPSHOT_NAME) shutil.copy2(os.path.join(OUT_DIR, 'dsym-snapshot.zip'), dsym_snaphot_zip) upload_electron(release, dsym_snaphot_zip, args) elif PLATFORM == 'win32': if get_target_arch() != 'ia32': pdb_zip = os.path.join(OUT_DIR, PDB_NAME) shutil.copy2(os.path.join(OUT_DIR, 'pdb.zip'), pdb_zip) upload_electron(release, pdb_zip, args) elif PLATFORM == 'linux': debug_zip = os.path.join(OUT_DIR, DEBUG_NAME) shutil.copy2(os.path.join(OUT_DIR, 'debug.zip'), debug_zip) upload_electron(release, debug_zip, args) # Upload libcxx_objects.zip for linux only libcxx_objects = get_zip_name('libcxx-objects', ELECTRON_VERSION) libcxx_objects_zip = os.path.join(OUT_DIR, libcxx_objects) shutil.copy2(os.path.join(OUT_DIR, 'libcxx_objects.zip'), libcxx_objects_zip) upload_electron(release, libcxx_objects_zip, args) # Upload headers.zip and abi_headers.zip as non-platform specific if get_target_arch() == "x64": cxx_headers_zip = os.path.join(OUT_DIR, 'libcxx_headers.zip') upload_electron(release, cxx_headers_zip, args) abi_headers_zip = os.path.join(OUT_DIR, 'libcxxabi_headers.zip') upload_electron(release, abi_headers_zip, args) # Upload free version of ffmpeg. ffmpeg = get_zip_name('ffmpeg', ELECTRON_VERSION) ffmpeg_zip = os.path.join(OUT_DIR, ffmpeg) ffmpeg_build_path = os.path.join(SRC_DIR, 'out', 'ffmpeg', 'ffmpeg.zip') shutil.copy2(ffmpeg_build_path, ffmpeg_zip) upload_electron(release, ffmpeg_zip, args) chromedriver = get_zip_name('chromedriver', ELECTRON_VERSION) chromedriver_zip = os.path.join(OUT_DIR, chromedriver) shutil.copy2(os.path.join(OUT_DIR, 'chromedriver.zip'), chromedriver_zip) upload_electron(release, chromedriver_zip, args) mksnapshot = get_zip_name('mksnapshot', ELECTRON_VERSION) mksnapshot_zip = os.path.join(OUT_DIR, mksnapshot) if get_target_arch().startswith('arm') and PLATFORM != 'darwin': # Upload the x64 binary for arm/arm64 mksnapshot mksnapshot = get_zip_name('mksnapshot', ELECTRON_VERSION, 'x64') mksnapshot_zip = os.path.join(OUT_DIR, mksnapshot) shutil.copy2(os.path.join(OUT_DIR, 'mksnapshot.zip'), mksnapshot_zip) upload_electron(release, mksnapshot_zip, args) if PLATFORM == 'linux' and get_target_arch() == 'x64': # Upload the hunspell dictionaries only from the linux x64 build hunspell_dictionaries_zip = os.path.join( OUT_DIR, 'hunspell_dictionaries.zip') upload_electron(release, hunspell_dictionaries_zip, args) if not tag_exists and not args.upload_to_storage: # Upload symbols to symbol server. run_python_upload_script('upload-symbols.py') if PLATFORM == 'win32': run_python_upload_script('upload-node-headers.py', '-v', args.version) if PLATFORM == 'win32': toolchain_profile_zip = os.path.join(OUT_DIR, TOOLCHAIN_PROFILE_NAME) with ZipFile(toolchain_profile_zip, 'w') as myzip: myzip.write( os.path.join(OUT_DIR, 'windows_toolchain_profile.json'), 'toolchain_profile.json') upload_electron(release, toolchain_profile_zip, args) return 0 def parse_args(): parser = argparse.ArgumentParser(description='upload distribution file') parser.add_argument('-v', '--version', help='Specify the version', default=ELECTRON_VERSION) parser.add_argument('-o', '--overwrite', help='Overwrite a published release', action='store_true') parser.add_argument('-p', '--publish-release', help='Publish the release', action='store_true') parser.add_argument('-s', '--upload_to_storage', help='Upload assets to azure bucket', dest='upload_to_storage', action='store_true', default=False, required=False) parser.add_argument('--verbose', action='store_true', help='Mooooorreee logs') return parser.parse_args() def run_python_upload_script(script, *args): script_path = os.path.join( ELECTRON_DIR, 'script', 'release', 'uploaders', script) print(execute([sys.executable, script_path] + list(args))) def get_electron_build_version(): if get_target_arch().startswith('arm') or 'CI' in os.environ: # In CI we just build as told. return ELECTRON_VERSION electron = get_electron_exec() return subprocess.check_output([electron, '--version']).strip() class NonZipFileError(ValueError): """Raised when a given file does not appear to be a zip""" def zero_zip_date_time(fname): """ Wrap strip-zip zero_zip_date_time within a file opening operation """ try: with open(fname, 'r+b') as f: _zero_zip_date_time(f) except Exception: # pylint: disable=W0707 raise NonZipFileError(fname) def _zero_zip_date_time(zip_): def purify_extra_data(mm, offset, length, compressed_size=0): extra_header_struct = Struct("<HH") # 0. id # 1. length STRIPZIP_OPTION_HEADER = 0xFFFF EXTENDED_TIME_DATA = 0x5455 # Some sort of extended time data, see # ftp://ftp.info-zip.org/pub/infozip/src/zip30.zip ./proginfo/extrafld.txt # fallthrough UNIX_EXTRA_DATA = 0x7875 # Unix extra data; UID / GID stuff, see # ftp://ftp.info-zip.org/pub/infozip/src/zip30.zip ./proginfo/extrafld.txt ZIP64_EXTRA_HEADER = 0x0001 zip64_extra_struct = Struct("<HHQQ") # ZIP64. # When a ZIP64 extra field is present this 8byte length # will override the 4byte length defined in canonical zips. # This is in the form: # - 0x0001 (header_id) # - 0x0010 [16] (header_length) # - ... (8byte uncompressed_length) # - ... (8byte compressed_length) mlen = offset + length while offset < mlen: values = list(extra_header_struct.unpack_from(mm, offset)) _, header_length = values extra_struct = Struct("<HH" + "B" * header_length) values = list(extra_struct.unpack_from(mm, offset)) header_id, header_length = values[:2] if header_id in (EXTENDED_TIME_DATA, UNIX_EXTRA_DATA): values[0] = STRIPZIP_OPTION_HEADER for i in range(2, len(values)): values[i] = 0xff extra_struct.pack_into(mm, offset, *values) if header_id == ZIP64_EXTRA_HEADER: assert header_length == 16 values = list(zip64_extra_struct.unpack_from(mm, offset)) header_id, header_length, _, compressed_size = values offset += extra_header_struct.size + header_length return compressed_size FILE_HEADER_SIGNATURE = 0x04034b50 CENDIR_HEADER_SIGNATURE = 0x02014b50 archive_size = os.fstat(zip_.fileno()).st_size signature_struct = Struct("<L") local_file_header_struct = Struct("<LHHHHHLLLHH") # 0. L signature # 1. H version_needed # 2. H gp_bits # 3. H compression_method # 4. H last_mod_time # 5. H last_mod_date # 6. L crc32 # 7. L compressed_size # 8. L uncompressed_size # 9. H name_length # 10. H extra_field_length central_directory_header_struct = Struct("<LHHHHHHLLLHHHHHLL") # 0. L signature # 1. H version_made_by # 2. H version_needed # 3. H gp_bits # 4. H compression_method # 5. H last_mod_time # 6. H last_mod_date # 7. L crc32 # 8. L compressed_size # 9. L uncompressed_size # 10. H file_name_length # 11. H extra_field_length # 12. H file_comment_length # 13. H disk_number_start # 14. H internal_attr # 15. L external_attr # 16. L rel_offset_local_header offset = 0 mm = mmap.mmap(zip_.fileno(), 0) while offset < archive_size: if signature_struct.unpack_from(mm, offset) != (FILE_HEADER_SIGNATURE,): break values = list(local_file_header_struct.unpack_from(mm, offset)) compressed_size, _, name_length, extra_field_length = values[7:11] # reset last_mod_time values[4] = 0 # reset last_mod_date values[5] = 0x21 local_file_header_struct.pack_into(mm, offset, *values) offset += local_file_header_struct.size + name_length if extra_field_length != 0: compressed_size = purify_extra_data(mm, offset, extra_field_length, compressed_size) offset += compressed_size + extra_field_length while offset < archive_size: if signature_struct.unpack_from(mm, offset) != (CENDIR_HEADER_SIGNATURE,): break values = list(central_directory_header_struct.unpack_from(mm, offset)) file_name_length, extra_field_length, file_comment_length = values[10:13] # reset last_mod_time values[5] = 0 # reset last_mod_date values[6] = 0x21 central_directory_header_struct.pack_into(mm, offset, *values) offset += central_directory_header_struct.size offset += file_name_length + extra_field_length + file_comment_length if extra_field_length != 0: purify_extra_data(mm, offset - extra_field_length, extra_field_length) if offset == 0: raise NonZipFileError(zip_.name) def upload_electron(release, file_path, args): filename = os.path.basename(file_path) # Strip zip non determinism before upload, in-place operation try: zero_zip_date_time(file_path) except NonZipFileError: pass # if upload_to_storage is set, skip github upload. # todo (vertedinde): migrate this variable to upload_to_storage if args.upload_to_storage: key_prefix = 'release-builds/{0}_{1}'.format(args.version, args.upload_timestamp) store_artifact(os.path.dirname(file_path), key_prefix, [file_path]) upload_sha256_checksum(args.version, file_path, key_prefix) return # Upload the file. upload_io_to_github(release, filename, file_path, args.version) # Upload the checksum file. upload_sha256_checksum(args.version, file_path) def upload_io_to_github(release, filename, filepath, version): print('Uploading %s to Github' % \ (filename)) script_path = os.path.join( ELECTRON_DIR, 'script', 'release', 'uploaders', 'upload-to-github.ts') execute([TS_NODE, script_path, filepath, filename, str(release['id']), version]) def upload_sha256_checksum(version, file_path, key_prefix=None): checksum_path = '{}.sha256sum'.format(file_path) if key_prefix is None: key_prefix = 'checksums-scratchpad/{0}'.format(version) sha256 = hashlib.sha256() with open(file_path, 'rb') as f: sha256.update(f.read()) filename = os.path.basename(file_path) with open(checksum_path, 'w') as checksum: checksum.write('{} *{}'.format(sha256.hexdigest(), filename)) store_artifact(os.path.dirname(checksum_path), key_prefix, [checksum_path]) def get_release(version): script_path = os.path.join( ELECTRON_DIR, 'script', 'release', 'find-github-release.js') release_info = execute(['node', script_path, version]) release = json.loads(release_info) return release if __name__ == '__main__': sys.exit(main())
closed
electron/electron
https://github.com/electron/electron
34,152
[Bug]: Non-default window dispositions fail to load initial URL
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 18.2.1 ### What operating system are you using? - Windows - macOS ### Operating System Version - Windows 10 21H2 - macOS 12.3.1 ### What arch are you using? x64 ### Last Known Working Electron version 17.4.3 ### Expected Behavior `Shift+LeftClick` (new-window) or `Ctrl+Shift+LeftClick` (foreground-tab) on links should open and load them in a new window. ### Actual Behavior `Shift+LeftClick` or `Ctrl+Shift+LeftClick` on links opens a new window and never loads. ### Testcase Gist URL https://gist.github.com/samuelmaddock/d8e8c64c5143df9b3493592c75fa33b8 ### Additional Information Bug initially introduced in v18.0.0-alpha.1
https://github.com/electron/electron/issues/34152
https://github.com/electron/electron/pull/34159
6f8a36f4047ba6300f93d4470193d6b54afabacf
dd6ce91f5766c9eea0ffca23e42ef8766851e0a2
2022-05-09T21:13:02Z
c++
2022-05-11T18:34:33Z
lib/browser/guest-window-manager.ts
/** * Create and minimally track guest windows at the direction of the renderer * (via window.open). Here, "guest" roughly means "child" — it's not necessarily * emblematic of its process status; both in-process (same-origin) and * out-of-process (cross-origin) are created here. "Embedder" roughly means * "parent." */ import { BrowserWindow } from 'electron/main'; import type { BrowserWindowConstructorOptions, Referrer, WebContents, LoadURLOptions } from 'electron/main'; import { parseFeatures } from '@electron/internal/browser/parse-features-string'; type PostData = LoadURLOptions['postData'] export type WindowOpenArgs = { url: string, frameName: string, features: string, } const frameNamesToWindow = new Map<string, BrowserWindow>(); const registerFrameNameToGuestWindow = (name: string, win: BrowserWindow) => frameNamesToWindow.set(name, win); const unregisterFrameName = (name: string) => frameNamesToWindow.delete(name); const getGuestWindowByFrameName = (name: string) => frameNamesToWindow.get(name); /** * `openGuestWindow` is called to create and setup event handling for the new * window. * * Until its removal in 12.0.0, the `new-window` event is fired, allowing the * user to preventDefault() on the passed event (which ends up calling * DestroyWebContents). */ export function openGuestWindow ({ event, embedder, guest, referrer, disposition, postData, overrideBrowserWindowOptions, windowOpenArgs, outlivesOpener }: { event: { sender: WebContents, defaultPrevented: boolean }, embedder: WebContents, guest?: WebContents, referrer: Referrer, disposition: string, postData?: PostData, overrideBrowserWindowOptions?: BrowserWindowConstructorOptions, windowOpenArgs: WindowOpenArgs, outlivesOpener: boolean, }): BrowserWindow | undefined { const { url, frameName, features } = windowOpenArgs; const { options: browserWindowOptions } = makeBrowserWindowOptions({ embedder, features, overrideOptions: overrideBrowserWindowOptions }); const didCancelEvent = emitDeprecatedNewWindowEvent({ event, embedder, guest, browserWindowOptions, windowOpenArgs, disposition, postData, referrer }); if (didCancelEvent) return; // To spec, subsequent window.open calls with the same frame name (`target` in // spec parlance) will reuse the previous window. // https://html.spec.whatwg.org/multipage/window-object.html#apis-for-creating-and-navigating-browsing-contexts-by-name const existingWindow = getGuestWindowByFrameName(frameName); if (existingWindow) { if (existingWindow.isDestroyed() || existingWindow.webContents.isDestroyed()) { // FIXME(t57ser): The webContents is destroyed for some reason, unregister the frame name unregisterFrameName(frameName); } else { existingWindow.loadURL(url); return existingWindow; } } const window = new BrowserWindow({ webContents: guest, ...browserWindowOptions }); handleWindowLifecycleEvents({ embedder, frameName, guest: window, outlivesOpener }); embedder.emit('did-create-window', window, { url, frameName, options: browserWindowOptions, disposition, referrer, postData }); return window; } /** * Manage the relationship between embedder window and guest window. When the * guest is destroyed, notify the embedder. When the embedder is destroyed, so * too is the guest destroyed; this is Electron convention and isn't based in * browser behavior. */ const handleWindowLifecycleEvents = function ({ embedder, guest, frameName, outlivesOpener }: { embedder: WebContents, guest: BrowserWindow, frameName: string, outlivesOpener: boolean }) { const closedByEmbedder = function () { guest.removeListener('closed', closedByUser); guest.destroy(); }; const closedByUser = function () { // Embedder might have been closed if (!embedder.isDestroyed() && !outlivesOpener) { embedder.removeListener('current-render-view-deleted' as any, closedByEmbedder); } }; if (!outlivesOpener) { embedder.once('current-render-view-deleted' as any, closedByEmbedder); } guest.once('closed', closedByUser); if (frameName) { registerFrameNameToGuestWindow(frameName, guest); guest.once('closed', function () { unregisterFrameName(frameName); }); } }; /** * Deprecated in favor of `webContents.setWindowOpenHandler` and * `did-create-window` in 11.0.0. Will be removed in 12.0.0. */ function emitDeprecatedNewWindowEvent ({ event, embedder, guest, windowOpenArgs, browserWindowOptions, disposition, referrer, postData }: { event: { sender: WebContents, defaultPrevented: boolean, newGuest?: BrowserWindow }, embedder: WebContents, guest?: WebContents, windowOpenArgs: WindowOpenArgs, browserWindowOptions: BrowserWindowConstructorOptions, disposition: string, referrer: Referrer, postData?: PostData, }): boolean { const { url, frameName } = windowOpenArgs; const isWebViewWithPopupsDisabled = embedder.getType() === 'webview' && embedder.getLastWebPreferences()!.disablePopups; const postBody = postData ? { data: postData, ...parseContentTypeFormat(postData) } : null; embedder.emit( 'new-window', event, url, frameName, disposition, { ...browserWindowOptions, webContents: guest }, [], // additionalFeatures referrer, postBody ); const { newGuest } = event; if (isWebViewWithPopupsDisabled) return true; if (event.defaultPrevented) { if (newGuest) { if (guest === newGuest.webContents) { // The webContents is not changed, so set defaultPrevented to false to // stop the callers of this event from destroying the webContents. event.defaultPrevented = false; } handleWindowLifecycleEvents({ embedder: event.sender, guest: newGuest, frameName, outlivesOpener: false }); } return true; } return false; } // Security options that child windows will always inherit from parent windows const securityWebPreferences: { [key: string]: boolean } = { contextIsolation: true, javascript: false, nodeIntegration: false, sandbox: true, webviewTag: false, nodeIntegrationInSubFrames: false, enableWebSQL: false }; function makeBrowserWindowOptions ({ embedder, features, overrideOptions }: { embedder: WebContents, features: string, overrideOptions?: BrowserWindowConstructorOptions, }) { const { options: parsedOptions, webPreferences: parsedWebPreferences } = parseFeatures(features); return { options: { show: true, width: 800, height: 600, ...parsedOptions, ...overrideOptions, // Note that for normal code path an existing WebContents created by // Chromium will be used, with web preferences parsed in the // |-will-add-new-contents| event. // The |webPreferences| here is only used by the |new-window| event. webPreferences: makeWebPreferences({ embedder, insecureParsedWebPreferences: parsedWebPreferences, secureOverrideWebPreferences: overrideOptions && overrideOptions.webPreferences }) } as Electron.BrowserViewConstructorOptions }; } export function makeWebPreferences ({ embedder, secureOverrideWebPreferences = {}, insecureParsedWebPreferences: parsedWebPreferences = {} }: { embedder: WebContents, insecureParsedWebPreferences?: ReturnType<typeof parseFeatures>['webPreferences'], // Note that override preferences are considered elevated, and should only be // sourced from the main process, as they override security defaults. If you // have unvetted prefs, use parsedWebPreferences. secureOverrideWebPreferences?: BrowserWindowConstructorOptions['webPreferences'], }) { const parentWebPreferences = embedder.getLastWebPreferences()!; const securityWebPreferencesFromParent = (Object.keys(securityWebPreferences).reduce((map, key) => { if (securityWebPreferences[key] === parentWebPreferences[key as keyof Electron.WebPreferences]) { (map as any)[key] = parentWebPreferences[key as keyof Electron.WebPreferences]; } return map; }, {} as Electron.WebPreferences)); return { ...parsedWebPreferences, // Note that order is key here, we want to disallow the renderer's // ability to change important security options but allow main (via // setWindowOpenHandler) to change them. ...securityWebPreferencesFromParent, ...secureOverrideWebPreferences }; } const MULTIPART_CONTENT_TYPE = 'multipart/form-data'; const URL_ENCODED_CONTENT_TYPE = 'application/x-www-form-urlencoded'; // Figure out appropriate headers for post data. export const parseContentTypeFormat = function (postData: Exclude<PostData, undefined>) { if (postData.length) { if (postData[0].type === 'rawData') { // For multipart forms, the first element will start with the boundary // notice, which looks something like `------WebKitFormBoundary12345678` // Note, this regex would fail when submitting a urlencoded form with an // input attribute of name="--theKey", but, uhh, don't do that? const postDataFront = postData[0].bytes.toString(); const boundary = /^--.*[^-\r\n]/.exec(postDataFront); if (boundary) { return { boundary: boundary[0].substr(2), contentType: MULTIPART_CONTENT_TYPE }; } } } // Either the form submission didn't contain any inputs (the postData array // was empty), or we couldn't find the boundary and thus we can assume this is // a key=value style form. return { contentType: URL_ENCODED_CONTENT_TYPE }; };
closed
electron/electron
https://github.com/electron/electron
34,152
[Bug]: Non-default window dispositions fail to load initial URL
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 18.2.1 ### What operating system are you using? - Windows - macOS ### Operating System Version - Windows 10 21H2 - macOS 12.3.1 ### What arch are you using? x64 ### Last Known Working Electron version 17.4.3 ### Expected Behavior `Shift+LeftClick` (new-window) or `Ctrl+Shift+LeftClick` (foreground-tab) on links should open and load them in a new window. ### Actual Behavior `Shift+LeftClick` or `Ctrl+Shift+LeftClick` on links opens a new window and never loads. ### Testcase Gist URL https://gist.github.com/samuelmaddock/d8e8c64c5143df9b3493592c75fa33b8 ### Additional Information Bug initially introduced in v18.0.0-alpha.1
https://github.com/electron/electron/issues/34152
https://github.com/electron/electron/pull/34159
6f8a36f4047ba6300f93d4470193d6b54afabacf
dd6ce91f5766c9eea0ffca23e42ef8766851e0a2
2022-05-09T21:13:02Z
c++
2022-05-11T18:34:33Z
spec-main/api-browser-window-spec.ts
import { expect } from 'chai'; import * as childProcess from 'child_process'; import * as path from 'path'; import * as fs from 'fs'; import * as os from 'os'; import * as qs from 'querystring'; import * as http from 'http'; import * as semver from 'semver'; import { AddressInfo } from 'net'; import { app, BrowserWindow, BrowserView, dialog, ipcMain, OnBeforeSendHeadersListenerDetails, protocol, screen, webContents, session, WebContents, BrowserWindowConstructorOptions } from 'electron/main'; import { emittedOnce, emittedUntil, emittedNTimes } from './events-helpers'; import { ifit, ifdescribe, defer, delay } from './spec-helpers'; import { closeWindow, closeAllWindows } from './window-helpers'; import { areColorsSimilar, captureScreen, CHROMA_COLOR_HEX, getPixelColor } from './screen-helpers'; const features = process._linkedBinding('electron_common_features'); const fixtures = path.resolve(__dirname, '..', 'spec', 'fixtures'); const mainFixtures = path.resolve(__dirname, 'fixtures'); // Is the display's scale factor possibly causing rounding of pixel coordinate // values? const isScaleFactorRounding = () => { const { scaleFactor } = screen.getPrimaryDisplay(); // Return true if scale factor is non-integer value if (Math.round(scaleFactor) !== scaleFactor) return true; // Return true if scale factor is odd number above 2 return scaleFactor > 2 && scaleFactor % 2 === 1; }; const expectBoundsEqual = (actual: any, expected: any) => { if (!isScaleFactorRounding()) { expect(expected).to.deep.equal(actual); } else if (Array.isArray(actual)) { expect(actual[0]).to.be.closeTo(expected[0], 1); expect(actual[1]).to.be.closeTo(expected[1], 1); } else { expect(actual.x).to.be.closeTo(expected.x, 1); expect(actual.y).to.be.closeTo(expected.y, 1); expect(actual.width).to.be.closeTo(expected.width, 1); expect(actual.height).to.be.closeTo(expected.height, 1); } }; const isBeforeUnload = (event: Event, level: number, message: string) => { return (message === 'beforeunload'); }; describe('BrowserWindow module', () => { describe('BrowserWindow constructor', () => { it('allows passing void 0 as the webContents', async () => { expect(() => { const w = new BrowserWindow({ show: false, // apparently void 0 had different behaviour from undefined in the // issue that this test is supposed to catch. webContents: void 0 // eslint-disable-line no-void } as any); w.destroy(); }).not.to.throw(); }); ifit(process.platform === 'linux')('does not crash when setting large window icons', async () => { const appPath = path.join(__dirname, 'spec-main', 'fixtures', 'apps', 'xwindow-icon'); const appProcess = childProcess.spawn(process.execPath, [appPath]); await new Promise((resolve) => { appProcess.once('exit', resolve); }); }); it('does not crash or throw when passed an invalid icon', async () => { expect(() => { const w = new BrowserWindow({ icon: undefined } as any); w.destroy(); }).not.to.throw(); }); }); describe('garbage collection', () => { const v8Util = process._linkedBinding('electron_common_v8_util'); afterEach(closeAllWindows); it('window does not get garbage collected when opened', async () => { const w = new BrowserWindow({ show: false }); // Keep a weak reference to the window. // eslint-disable-next-line no-undef const wr = new WeakRef(w); await delay(); // Do garbage collection, since |w| is not referenced in this closure // it would be gone after next call if there is no other reference. v8Util.requestGarbageCollectionForTesting(); await delay(); expect(wr.deref()).to.not.be.undefined(); }); }); describe('BrowserWindow.close()', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('should work if called when a messageBox is showing', async () => { const closed = emittedOnce(w, 'closed'); dialog.showMessageBox(w, { message: 'Hello Error' }); w.close(); await closed; }); it('closes window without rounded corners', async () => { await closeWindow(w); w = new BrowserWindow({ show: false, frame: false, roundedCorners: false }); const closed = emittedOnce(w, 'closed'); w.close(); await closed; }); it('should not crash if called after webContents is destroyed', () => { w.webContents.destroy(); w.webContents.on('destroyed', () => w.close()); }); it('should emit unload handler', async () => { await w.loadFile(path.join(fixtures, 'api', 'unload.html')); const closed = emittedOnce(w, 'closed'); w.close(); await closed; const test = path.join(fixtures, 'api', 'unload'); const content = fs.readFileSync(test); fs.unlinkSync(test); expect(String(content)).to.equal('unload'); }); it('should emit beforeunload handler', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); await emittedOnce(w.webContents, 'before-unload-fired'); }); it('should not crash when keyboard event is sent before closing', async () => { await w.loadURL('data:text/html,pls no crash'); const closed = emittedOnce(w, 'closed'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' }); w.close(); await closed; }); describe('when invoked synchronously inside navigation observer', () => { let server: http.Server = null as unknown as http.Server; let url: string = null as unknown as string; before((done) => { server = http.createServer((request, response) => { switch (request.url) { case '/net-error': response.destroy(); break; case '/301': response.statusCode = 301; response.setHeader('Location', '/200'); response.end(); break; case '/200': response.statusCode = 200; response.end('hello'); break; case '/title': response.statusCode = 200; response.end('<title>Hello</title>'); break; default: throw new Error(`unsupported endpoint: ${request.url}`); } }).listen(0, '127.0.0.1', () => { url = 'http://127.0.0.1:' + (server.address() as AddressInfo).port; done(); }); }); after(() => { server.close(); }); const events = [ { name: 'did-start-loading', path: '/200' }, { name: 'dom-ready', path: '/200' }, { name: 'page-title-updated', path: '/title' }, { name: 'did-stop-loading', path: '/200' }, { name: 'did-finish-load', path: '/200' }, { name: 'did-frame-finish-load', path: '/200' }, { name: 'did-fail-load', path: '/net-error' } ]; for (const { name, path } of events) { it(`should not crash when closed during ${name}`, async () => { const w = new BrowserWindow({ show: false }); w.webContents.once((name as any), () => { w.close(); }); const destroyed = emittedOnce(w.webContents, 'destroyed'); w.webContents.loadURL(url + path); await destroyed; }); } }); }); describe('window.close()', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('should emit unload event', async () => { w.loadFile(path.join(fixtures, 'api', 'close.html')); await emittedOnce(w, 'closed'); const test = path.join(fixtures, 'api', 'close'); const content = fs.readFileSync(test).toString(); fs.unlinkSync(test); expect(content).to.equal('close'); }); it('should emit beforeunload event', async function () { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.webContents.executeJavaScript('window.close()', true); await emittedOnce(w.webContents, 'before-unload-fired'); }); }); describe('BrowserWindow.destroy()', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('prevents users to access methods of webContents', async () => { const contents = w.webContents; w.destroy(); await new Promise(setImmediate); expect(() => { contents.getProcessId(); }).to.throw('Object has been destroyed'); }); it('should not crash when destroying windows with pending events', () => { const focusListener = () => { }; app.on('browser-window-focus', focusListener); const windowCount = 3; const windowOptions = { show: false, width: 400, height: 400, webPreferences: { backgroundThrottling: false } }; const windows = Array.from(Array(windowCount)).map(() => new BrowserWindow(windowOptions)); windows.forEach(win => win.show()); windows.forEach(win => win.focus()); windows.forEach(win => win.destroy()); app.removeListener('browser-window-focus', focusListener); }); }); describe('BrowserWindow.loadURL(url)', () => { let w = null as unknown as BrowserWindow; const scheme = 'other'; const srcPath = path.join(fixtures, 'api', 'loaded-from-dataurl.js'); before(() => { protocol.registerFileProtocol(scheme, (request, callback) => { callback(srcPath); }); }); after(() => { protocol.unregisterProtocol(scheme); }); beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); let server = null as unknown as http.Server; let url = null as unknown as string; let postData = null as any; before((done) => { const filePath = path.join(fixtures, 'pages', 'a.html'); const fileStats = fs.statSync(filePath); postData = [ { type: 'rawData', bytes: Buffer.from('username=test&file=') }, { type: 'file', filePath: filePath, offset: 0, length: fileStats.size, modificationTime: fileStats.mtime.getTime() / 1000 } ]; server = http.createServer((req, res) => { function respond () { if (req.method === 'POST') { let body = ''; req.on('data', (data) => { if (data) body += data; }); req.on('end', () => { const parsedData = qs.parse(body); fs.readFile(filePath, (err, data) => { if (err) return; if (parsedData.username === 'test' && parsedData.file === data.toString()) { res.end(); } }); }); } else if (req.url === '/302') { res.setHeader('Location', '/200'); res.statusCode = 302; res.end(); } else { res.end(); } } setTimeout(respond, req.url && req.url.includes('slow') ? 200 : 0); }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; done(); }); }); after(() => { server.close(); }); it('should emit did-start-loading event', async () => { const didStartLoading = emittedOnce(w.webContents, 'did-start-loading'); w.loadURL('about:blank'); await didStartLoading; }); it('should emit ready-to-show event', async () => { const readyToShow = emittedOnce(w, 'ready-to-show'); w.loadURL('about:blank'); await readyToShow; }); // TODO(deepak1556): The error code now seems to be `ERR_FAILED`, verify what // changed and adjust the test. it.skip('should emit did-fail-load event for files that do not exist', async () => { const didFailLoad = emittedOnce(w.webContents, 'did-fail-load'); w.loadURL('file://a.txt'); const [, code, desc,, isMainFrame] = await didFailLoad; expect(code).to.equal(-6); expect(desc).to.equal('ERR_FILE_NOT_FOUND'); expect(isMainFrame).to.equal(true); }); it('should emit did-fail-load event for invalid URL', async () => { const didFailLoad = emittedOnce(w.webContents, 'did-fail-load'); w.loadURL('http://example:port'); const [, code, desc,, isMainFrame] = await didFailLoad; expect(desc).to.equal('ERR_INVALID_URL'); expect(code).to.equal(-300); expect(isMainFrame).to.equal(true); }); it('should set `mainFrame = false` on did-fail-load events in iframes', async () => { const didFailLoad = emittedOnce(w.webContents, 'did-fail-load'); w.loadFile(path.join(fixtures, 'api', 'did-fail-load-iframe.html')); const [,,,, isMainFrame] = await didFailLoad; expect(isMainFrame).to.equal(false); }); it('does not crash in did-fail-provisional-load handler', (done) => { w.webContents.once('did-fail-provisional-load', () => { w.loadURL('http://127.0.0.1:11111'); done(); }); w.loadURL('http://127.0.0.1:11111'); }); it('should emit did-fail-load event for URL exceeding character limit', async () => { const data = Buffer.alloc(2 * 1024 * 1024).toString('base64'); const didFailLoad = emittedOnce(w.webContents, 'did-fail-load'); w.loadURL(`data:image/png;base64,${data}`); const [, code, desc,, isMainFrame] = await didFailLoad; expect(desc).to.equal('ERR_INVALID_URL'); expect(code).to.equal(-300); expect(isMainFrame).to.equal(true); }); it('should return a promise', () => { const p = w.loadURL('about:blank'); expect(p).to.have.property('then'); }); it('should return a promise that resolves', async () => { await expect(w.loadURL('about:blank')).to.eventually.be.fulfilled(); }); it('should return a promise that rejects on a load failure', async () => { const data = Buffer.alloc(2 * 1024 * 1024).toString('base64'); const p = w.loadURL(`data:image/png;base64,${data}`); await expect(p).to.eventually.be.rejected; }); it('should return a promise that resolves even if pushState occurs during navigation', async () => { const p = w.loadURL('data:text/html,<script>window.history.pushState({}, "/foo")</script>'); await expect(p).to.eventually.be.fulfilled; }); describe('POST navigations', () => { afterEach(() => { w.webContents.session.webRequest.onBeforeSendHeaders(null); }); it('supports specifying POST data', async () => { await w.loadURL(url, { postData }); }); it('sets the content type header on URL encoded forms', async () => { await w.loadURL(url); const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => { w.webContents.session.webRequest.onBeforeSendHeaders((details) => { resolve(details); }); }); w.webContents.executeJavaScript(` form = document.createElement('form') document.body.appendChild(form) form.method = 'POST' form.submit() `); const details = await requestDetails; expect(details.requestHeaders['Content-Type']).to.equal('application/x-www-form-urlencoded'); }); it('sets the content type header on multi part forms', async () => { await w.loadURL(url); const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => { w.webContents.session.webRequest.onBeforeSendHeaders((details) => { resolve(details); }); }); w.webContents.executeJavaScript(` form = document.createElement('form') document.body.appendChild(form) form.method = 'POST' form.enctype = 'multipart/form-data' file = document.createElement('input') file.type = 'file' file.name = 'file' form.appendChild(file) form.submit() `); const details = await requestDetails; expect(details.requestHeaders['Content-Type'].startsWith('multipart/form-data; boundary=----WebKitFormBoundary')).to.equal(true); }); }); it('should support base url for data urls', async () => { await w.loadURL('data:text/html,<script src="loaded-from-dataurl.js"></script>', { baseURLForDataURL: `other://${path.join(fixtures, 'api')}${path.sep}` }); expect(await w.webContents.executeJavaScript('window.ping')).to.equal('pong'); }); }); for (const sandbox of [false, true]) { describe(`navigation events${sandbox ? ' with sandbox' : ''}`, () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: false, sandbox } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('will-navigate event', () => { let server = null as unknown as http.Server; let url = null as unknown as string; before((done) => { server = http.createServer((req, res) => { if (req.url === '/navigate-top') { res.end('<a target=_top href="/">navigate _top</a>'); } else { res.end(''); } }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/`; done(); }); }); after(() => { server.close(); }); it('allows the window to be closed from the event listener', (done) => { w.webContents.once('will-navigate', () => { w.close(); done(); }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('can be prevented', (done) => { let willNavigate = false; w.webContents.once('will-navigate', (e) => { willNavigate = true; e.preventDefault(); }); w.webContents.on('did-stop-loading', () => { if (willNavigate) { // i.e. it shouldn't have had '?navigated' appended to it. try { expect(w.webContents.getURL().endsWith('will-navigate.html')).to.be.true(); done(); } catch (e) { done(e); } } }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('is triggered when navigating from file: to http:', async () => { await w.loadFile(path.join(fixtures, 'api', 'blank.html')); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-navigate', (e, url) => { e.preventDefault(); resolve(url); }); }); expect(navigatedTo).to.equal(url); expect(w.webContents.getURL()).to.match(/^file:/); }); it('is triggered when navigating from about:blank to http:', async () => { await w.loadURL('about:blank'); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-navigate', (e, url) => { e.preventDefault(); resolve(url); }); }); expect(navigatedTo).to.equal(url); expect(w.webContents.getURL()).to.equal('about:blank'); }); it('is triggered when a cross-origin iframe navigates _top', async () => { await w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-top"></iframe>`); await delay(1000); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const iframeTarget = targets.targetInfos.find((t: any) => t.type === 'iframe'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: iframeTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); let willNavigateEmitted = false; w.webContents.on('will-navigate', () => { willNavigateEmitted = true; }); await emittedOnce(w.webContents, 'did-navigate'); expect(willNavigateEmitted).to.be.true(); }); }); describe('will-redirect event', () => { let server = null as unknown as http.Server; let url = null as unknown as string; before((done) => { server = http.createServer((req, res) => { if (req.url === '/302') { res.setHeader('Location', '/200'); res.statusCode = 302; res.end(); } else if (req.url === '/navigate-302') { res.end(`<html><body><script>window.location='${url}/302'</script></body></html>`); } else { res.end(); } }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; done(); }); }); after(() => { server.close(); }); it('is emitted on redirects', async () => { const willRedirect = emittedOnce(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await willRedirect; }); it('is emitted after will-navigate on redirects', async () => { let navigateCalled = false; w.webContents.on('will-navigate', () => { navigateCalled = true; }); const willRedirect = emittedOnce(w.webContents, 'will-redirect'); w.loadURL(`${url}/navigate-302`); await willRedirect; expect(navigateCalled).to.equal(true, 'should have called will-navigate first'); }); it('is emitted before did-stop-loading on redirects', async () => { let stopCalled = false; w.webContents.on('did-stop-loading', () => { stopCalled = true; }); const willRedirect = emittedOnce(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await willRedirect; expect(stopCalled).to.equal(false, 'should not have called did-stop-loading first'); }); it('allows the window to be closed from the event listener', (done) => { w.webContents.once('will-redirect', () => { w.close(); done(); }); w.loadURL(`${url}/302`); }); it('can be prevented', (done) => { w.webContents.once('will-redirect', (event) => { event.preventDefault(); }); w.webContents.on('will-navigate', (e, u) => { expect(u).to.equal(`${url}/302`); }); w.webContents.on('did-stop-loading', () => { try { expect(w.webContents.getURL()).to.equal( `${url}/navigate-302`, 'url should not have changed after navigation event' ); done(); } catch (e) { done(e); } }); w.webContents.on('will-redirect', (e, u) => { try { expect(u).to.equal(`${url}/200`); } catch (e) { done(e); } }); w.loadURL(`${url}/navigate-302`); }); }); }); } describe('focus and visibility', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.show()', () => { it('should focus on window', async () => { await emittedOnce(w, 'focus', () => w.show()); expect(w.isFocused()).to.equal(true); }); it('should make the window visible', async () => { await emittedOnce(w, 'focus', () => w.show()); expect(w.isVisible()).to.equal(true); }); it('emits when window is shown', async () => { const show = emittedOnce(w, 'show'); w.show(); await show; expect(w.isVisible()).to.equal(true); }); }); describe('BrowserWindow.hide()', () => { it('should defocus on window', () => { w.hide(); expect(w.isFocused()).to.equal(false); }); it('should make the window not visible', () => { w.show(); w.hide(); expect(w.isVisible()).to.equal(false); }); it('emits when window is hidden', async () => { const shown = emittedOnce(w, 'show'); w.show(); await shown; const hidden = emittedOnce(w, 'hide'); w.hide(); await hidden; expect(w.isVisible()).to.equal(false); }); }); describe('BrowserWindow.showInactive()', () => { it('should not focus on window', () => { w.showInactive(); expect(w.isFocused()).to.equal(false); }); // TODO(dsanders11): Enable for Linux once CI plays nice with these kinds of tests ifit(process.platform !== 'linux')('should not restore maximized windows', async () => { const maximize = emittedOnce(w, 'maximize'); const shown = emittedOnce(w, 'show'); w.maximize(); // TODO(dsanders11): The maximize event isn't firing on macOS for a window initially hidden if (process.platform !== 'darwin') { await maximize; } else { await delay(1000); } w.showInactive(); await shown; expect(w.isMaximized()).to.equal(true); }); }); describe('BrowserWindow.focus()', () => { it('does not make the window become visible', () => { expect(w.isVisible()).to.equal(false); w.focus(); expect(w.isVisible()).to.equal(false); }); ifit(process.platform !== 'win32')('focuses a blurred window', async () => { { const isBlurred = emittedOnce(w, 'blur'); const isShown = emittedOnce(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 = emittedOnce(w3, 'focus'); const isShown1 = emittedOnce(w1, 'show'); const isShown2 = emittedOnce(w2, 'show'); const isShown3 = emittedOnce(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 = emittedOnce(w1, 'closed'); const isClosed2 = emittedOnce(w2, 'closed'); const isClosed3 = emittedOnce(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 = emittedOnce(w, 'focus'); const isShown = emittedOnce(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 = emittedOnce(w3, 'focus'); const isShown1 = emittedOnce(w1, 'show'); const isShown2 = emittedOnce(w2, 'show'); const isShown3 = emittedOnce(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 = emittedOnce(w1, 'closed'); const isClosed2 = emittedOnce(w2, 'closed'); const isClosed3 = emittedOnce(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 () => { await emittedOnce(w, 'focus', () => w.show()); w.webContents.openDevTools({ mode: 'undocked' }); await emittedOnce(w.webContents, 'devtools-focused'); expect(BrowserWindow.getFocusedWindow()).to.equal(w); }); }); describe('BrowserWindow.moveTop()', () => { it('should not steal focus', async () => { const posDelta = 50; const wShownInactive = emittedOnce(w, 'show'); w.showInactive(); await wShownInactive; expect(w.isFocused()).to.equal(false); const otherWindow = new BrowserWindow({ show: false, title: 'otherWindow' }); const otherWindowShown = emittedOnce(otherWindow, 'show'); const otherWindowFocused = emittedOnce(otherWindow, 'focus'); otherWindow.show(); await otherWindowShown; await otherWindowFocused; expect(otherWindow.isFocused()).to.equal(true); w.moveTop(); const wPos = w.getPosition(); const wMoving = emittedOnce(w, 'move'); w.setPosition(wPos[0] + posDelta, wPos[1] + posDelta); await wMoving; expect(w.isFocused()).to.equal(false); expect(otherWindow.isFocused()).to.equal(true); const wFocused = emittedOnce(w, 'focus'); const otherWindowBlurred = emittedOnce(otherWindow, 'blur'); w.focus(); await wFocused; await otherWindowBlurred; expect(w.isFocused()).to.equal(true); otherWindow.moveTop(); const otherWindowPos = otherWindow.getPosition(); const otherWindowMoving = emittedOnce(otherWindow, 'move'); otherWindow.setPosition(otherWindowPos[0] + posDelta, otherWindowPos[1] + posDelta); await otherWindowMoving; expect(otherWindow.isFocused()).to.equal(false); expect(w.isFocused()).to.equal(true); await closeWindow(otherWindow, { assertNotWindows: false }); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1); }); }); ifdescribe(features.isDesktopCapturerEnabled())('BrowserWindow.moveAbove(mediaSourceId)', () => { it('should throw an exception if wrong formatting', async () => { const fakeSourceIds = [ 'none', 'screen:0', 'window:fake', 'window:1234', 'foobar:1:2' ]; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Invalid media source id/); }); }); it('should throw an exception if wrong type', async () => { const fakeSourceIds = [null as any, 123 as any]; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Error processing argument at index 0 */); }); }); it('should throw an exception if invalid window', async () => { // It is very unlikely that these window id exist. const fakeSourceIds = ['window:99999999:0', 'window:123456:1', 'window:123456:9']; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Invalid media source id/); }); }); it('should not throw an exception', async () => { const w2 = new BrowserWindow({ show: false, title: 'window2' }); const w2Shown = emittedOnce(w2, 'show'); w2.show(); await w2Shown; expect(() => { w.moveAbove(w2.getMediaSourceId()); }).to.not.throw(); await closeWindow(w2, { assertNotWindows: false }); }); }); describe('BrowserWindow.setFocusable()', () => { it('can set unfocusable window to focusable', async () => { const w2 = new BrowserWindow({ focusable: false }); const w2Focused = emittedOnce(w2, 'focus'); w2.setFocusable(true); w2.focus(); await w2Focused; await closeWindow(w2, { assertNotWindows: false }); }); }); describe('BrowserWindow.isFocusable()', () => { it('correctly returns whether a window is focusable', async () => { const w2 = new BrowserWindow({ focusable: false }); expect(w2.isFocusable()).to.be.false(); w2.setFocusable(true); expect(w2.isFocusable()).to.be.true(); await closeWindow(w2, { assertNotWindows: false }); }); }); }); describe('sizing', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, width: 400, height: 400 }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.setBounds(bounds[, animate])', () => { it('sets the window bounds with full bounds', () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds); expectBoundsEqual(w.getBounds(), fullBounds); }); it('sets the window bounds with partial bounds', () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds); const boundsUpdate = { width: 200 }; w.setBounds(boundsUpdate as any); const expectedBounds = Object.assign(fullBounds, boundsUpdate); expectBoundsEqual(w.getBounds(), expectedBounds); }); ifit(process.platform === 'darwin')('on macOS', () => { it('emits \'resized\' event after animating', async () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds, true); await expect(emittedOnce(w, 'resized')).to.eventually.be.fulfilled(); }); }); }); describe('BrowserWindow.setSize(width, height)', () => { it('sets the window size', async () => { const size = [300, 400]; const resized = emittedOnce(w, 'resize'); w.setSize(size[0], size[1]); await resized; expectBoundsEqual(w.getSize(), size); }); ifit(process.platform === 'darwin')('on macOS', () => { it('emits \'resized\' event after animating', async () => { const size = [300, 400]; w.setSize(size[0], size[1], true); await expect(emittedOnce(w, 'resized')).to.eventually.be.fulfilled(); }); }); }); describe('BrowserWindow.setMinimum/MaximumSize(width, height)', () => { it('sets the maximum and minimum size of the window', () => { expect(w.getMinimumSize()).to.deep.equal([0, 0]); expect(w.getMaximumSize()).to.deep.equal([0, 0]); w.setMinimumSize(100, 100); expectBoundsEqual(w.getMinimumSize(), [100, 100]); expectBoundsEqual(w.getMaximumSize(), [0, 0]); w.setMaximumSize(900, 600); expectBoundsEqual(w.getMinimumSize(), [100, 100]); expectBoundsEqual(w.getMaximumSize(), [900, 600]); }); }); describe('BrowserWindow.setAspectRatio(ratio)', () => { it('resets the behaviour when passing in 0', async () => { const size = [300, 400]; w.setAspectRatio(1 / 2); w.setAspectRatio(0); const resize = emittedOnce(w, 'resize'); w.setSize(size[0], size[1]); await resize; expectBoundsEqual(w.getSize(), size); }); it('doesn\'t change bounds when maximum size is set', () => { w.setMenu(null); w.setMaximumSize(400, 400); // Without https://github.com/electron/electron/pull/29101 // following call would shrink the window to 384x361. // There would be also DCHECK in resize_utils.cc on // debug build. w.setAspectRatio(1.0); expectBoundsEqual(w.getSize(), [400, 400]); }); }); describe('BrowserWindow.setPosition(x, y)', () => { it('sets the window position', async () => { const pos = [10, 10]; const move = emittedOnce(w, 'move'); w.setPosition(pos[0], pos[1]); await move; expect(w.getPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setContentSize(width, height)', () => { it('sets the content size', async () => { // NB. The CI server has a very small screen. Attempting to size the window // larger than the screen will limit the window's size to the screen and // cause the test to fail. const size = [456, 567]; w.setContentSize(size[0], size[1]); await new Promise(setImmediate); const after = w.getContentSize(); expect(after).to.deep.equal(size); }); it('works for a frameless window', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 400, height: 400 }); const size = [456, 567]; w.setContentSize(size[0], size[1]); await new Promise(setImmediate); const after = w.getContentSize(); expect(after).to.deep.equal(size); }); }); describe('BrowserWindow.setContentBounds(bounds)', () => { it('sets the content size and position', async () => { const bounds = { x: 10, y: 10, width: 250, height: 250 }; const resize = emittedOnce(w, 'resize'); w.setContentBounds(bounds); await resize; await delay(); expectBoundsEqual(w.getContentBounds(), bounds); }); it('works for a frameless window', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300 }); const bounds = { x: 10, y: 10, width: 250, height: 250 }; const resize = emittedOnce(w, 'resize'); w.setContentBounds(bounds); await resize; await delay(); expectBoundsEqual(w.getContentBounds(), bounds); }); }); describe('BrowserWindow.getBackgroundColor()', () => { it('returns default value if no backgroundColor is set', () => { w.destroy(); w = new BrowserWindow({}); expect(w.getBackgroundColor()).to.equal('#FFFFFF'); }); it('returns correct value if backgroundColor is set', () => { const backgroundColor = '#BBAAFF'; w.destroy(); w = new BrowserWindow({ backgroundColor: backgroundColor }); expect(w.getBackgroundColor()).to.equal(backgroundColor); }); it('returns correct value from setBackgroundColor()', () => { const backgroundColor = '#AABBFF'; w.destroy(); w = new BrowserWindow({}); w.setBackgroundColor(backgroundColor); expect(w.getBackgroundColor()).to.equal(backgroundColor); }); 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 = emittedOnce(w, 'resize'); w.setSize(size[0], size[1]); await resize; expectBoundsEqual(w.getNormalBounds(), w.getBounds()); }); it('checks normal bounds after move', async () => { const pos = [10, 10]; const move = emittedOnce(w, 'move'); w.setPosition(pos[0], pos[1]); await move; expectBoundsEqual(w.getNormalBounds(), w.getBounds()); }); }); ifdescribe(process.platform !== 'linux')('Maximized state', () => { it('checks normal bounds when maximized', async () => { const bounds = w.getBounds(); const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('checks normal bounds when unmaximized', async () => { const bounds = w.getBounds(); w.once('maximize', () => { w.unmaximize(); }); const unmaximize = emittedOnce(w, 'unmaximize'); w.show(); w.maximize(); await unmaximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('does not change size for a frameless window with min size', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300, minWidth: 300, minHeight: 300 }); const bounds = w.getBounds(); w.once('maximize', () => { w.unmaximize(); }); const unmaximize = emittedOnce(w, 'unmaximize'); w.show(); w.maximize(); await unmaximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('correctly checks transparent window maximization state', async () => { w.destroy(); w = new BrowserWindow({ show: false, width: 300, height: 300, transparent: true }); const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; expect(w.isMaximized()).to.equal(true); const unmaximize = emittedOnce(w, 'unmaximize'); w.unmaximize(); await unmaximize; expect(w.isMaximized()).to.equal(false); }); it('returns the correct value for windows with an aspect ratio', async () => { w.destroy(); w = new BrowserWindow({ show: false, fullscreenable: false }); w.setAspectRatio(16 / 11); const maximize = emittedOnce(w, 'resize'); w.show(); w.maximize(); await maximize; expect(w.isMaximized()).to.equal(true); w.resizable = false; expect(w.isMaximized()).to.equal(true); }); }); ifdescribe(process.platform !== 'linux')('Minimized state', () => { it('checks normal bounds when minimized', async () => { const bounds = w.getBounds(); const minimize = emittedOnce(w, 'minimize'); w.show(); w.minimize(); await minimize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('checks normal bounds when restored', async () => { const bounds = w.getBounds(); w.once('minimize', () => { w.restore(); }); const restore = emittedOnce(w, 'restore'); w.show(); w.minimize(); await restore; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('does not change size for a frameless window with min size', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300, minWidth: 300, minHeight: 300 }); const bounds = w.getBounds(); w.once('minimize', () => { w.restore(); }); const restore = emittedOnce(w, 'restore'); w.show(); w.minimize(); await restore; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); ifdescribe(process.platform === 'win32')('Fullscreen state', () => { it('with properties', () => { it('can be set with the fullscreen constructor option', () => { w = new BrowserWindow({ fullscreen: true }); expect(w.fullScreen).to.be.true(); }); it('can be changed', () => { w.fullScreen = false; expect(w.fullScreen).to.be.false(); w.fullScreen = true; expect(w.fullScreen).to.be.true(); }); it('checks normal bounds when fullscreen\'ed', async () => { const bounds = w.getBounds(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.show(); w.fullScreen = true; await enterFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('checks normal bounds when unfullscreen\'ed', async () => { const bounds = w.getBounds(); w.once('enter-full-screen', () => { w.fullScreen = false; }); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.show(); w.fullScreen = true; await leaveFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); it('with functions', () => { it('can be set with the fullscreen constructor option', () => { w = new BrowserWindow({ fullscreen: true }); expect(w.isFullScreen()).to.be.true(); }); it('can be changed', () => { w.setFullScreen(false); expect(w.isFullScreen()).to.be.false(); w.setFullScreen(true); expect(w.isFullScreen()).to.be.true(); }); it('checks normal bounds when fullscreen\'ed', async () => { const bounds = w.getBounds(); w.show(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('checks normal bounds when unfullscreen\'ed', async () => { const bounds = w.getBounds(); w.show(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); }); }); }); ifdescribe(process.platform === 'darwin')('tabbed windows', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.selectPreviousTab()', () => { it('does not throw', () => { expect(() => { w.selectPreviousTab(); }).to.not.throw(); }); }); describe('BrowserWindow.selectNextTab()', () => { it('does not throw', () => { expect(() => { w.selectNextTab(); }).to.not.throw(); }); }); describe('BrowserWindow.mergeAllWindows()', () => { it('does not throw', () => { expect(() => { w.mergeAllWindows(); }).to.not.throw(); }); }); describe('BrowserWindow.moveTabToNewWindow()', () => { it('does not throw', () => { expect(() => { w.moveTabToNewWindow(); }).to.not.throw(); }); }); describe('BrowserWindow.toggleTabBar()', () => { it('does not throw', () => { expect(() => { w.toggleTabBar(); }).to.not.throw(); }); }); describe('BrowserWindow.addTabbedWindow()', () => { it('does not throw', async () => { const tabbedWindow = new BrowserWindow({}); expect(() => { w.addTabbedWindow(tabbedWindow); }).to.not.throw(); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(2); // w + tabbedWindow await closeWindow(tabbedWindow, { assertNotWindows: false }); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1); // w }); it('throws when called on itself', () => { expect(() => { w.addTabbedWindow(w); }).to.throw('AddTabbedWindow cannot be called by a window on itself.'); }); }); }); describe('autoHideMenuBar state', () => { afterEach(closeAllWindows); it('for properties', () => { it('can be set with autoHideMenuBar constructor option', () => { const w = new BrowserWindow({ show: false, autoHideMenuBar: true }); expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); w.autoHideMenuBar = true; expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); w.autoHideMenuBar = false; expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); }); }); it('for functions', () => { it('can be set with autoHideMenuBar constructor option', () => { const w = new BrowserWindow({ show: false, autoHideMenuBar: true }); expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar'); w.setAutoHideMenuBar(true); expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar'); w.setAutoHideMenuBar(false); expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar'); }); }); }); describe('BrowserWindow.capturePage(rect)', () => { afterEach(closeAllWindows); it('returns a Promise with a Buffer', async () => { const w = new BrowserWindow({ show: false }); const image = await w.capturePage({ x: 0, y: 0, width: 100, height: 100 }); expect(image.isEmpty()).to.equal(true); }); it('resolves after the window is hidden', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixtures, 'pages', 'a.html')); await emittedOnce(w, 'ready-to-show'); w.show(); const visibleImage = await w.capturePage(); expect(visibleImage.isEmpty()).to.equal(false); w.hide(); const hiddenImage = await w.capturePage(); const isEmpty = process.platform !== 'darwin'; expect(hiddenImage.isEmpty()).to.equal(isEmpty); }); it('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 emittedOnce(w, 'ready-to-show'); w.webContents.incrementCapturerCount(); 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 emittedOnce(w, 'ready-to-show'); w.show(); const image = await w.capturePage(); const imgBuffer = image.toPNG(); // Check the 25th byte in the PNG. // Values can be 0,2,3,4, or 6. We want 6, which is RGB + Alpha expect(imgBuffer[25]).to.equal(6); }); it('should increase the capturer count', () => { const w = new BrowserWindow({ show: false }); w.webContents.incrementCapturerCount(); expect(w.webContents.isBeingCaptured()).to.be.true(); w.webContents.decrementCapturerCount(); expect(w.webContents.isBeingCaptured()).to.be.false(); }); }); describe('BrowserWindow.setProgressBar(progress)', () => { let w = null as unknown as BrowserWindow; before(() => { w = new BrowserWindow({ show: false }); }); after(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('sets the progress', () => { expect(() => { if (process.platform === 'darwin') { app.dock.setIcon(path.join(fixtures, 'assets', 'logo.png')); } w.setProgressBar(0.5); if (process.platform === 'darwin') { app.dock.setIcon(null as any); } w.setProgressBar(-1); }).to.not.throw(); }); it('sets the progress using "paused" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'paused' }); }).to.not.throw(); }); it('sets the progress using "error" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'error' }); }).to.not.throw(); }); it('sets the progress using "normal" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'normal' }); }).to.not.throw(); }); }); describe('BrowserWindow.setAlwaysOnTop(flag, level)', () => { let w = null as unknown as BrowserWindow; afterEach(closeAllWindows); beforeEach(() => { w = new BrowserWindow({ show: true }); }); it('sets the window as always on top', () => { expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); w.setAlwaysOnTop(false); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); }); ifit(process.platform === 'darwin')('resets the windows level on minimize', () => { expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); w.minimize(); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.restore(); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); }); it('causes the right value to be emitted on `always-on-top-changed`', async () => { const alwaysOnTopChanged = emittedOnce(w, 'always-on-top-changed'); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true); const [, alwaysOnTop] = await alwaysOnTopChanged; expect(alwaysOnTop).to.be.true('is not alwaysOnTop'); }); ifit(process.platform === 'darwin')('honors the alwaysOnTop level of a child window', () => { w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ parent: w }); c.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.false(); expect(c.isAlwaysOnTop()).to.be.true('child is not always on top'); expect((c as any)._getAlwaysOnTopLevel()).to.equal('screen-saver'); }); }); describe('preconnect feature', () => { let w = null as unknown as BrowserWindow; let server = null as unknown as http.Server; let url = null as unknown as string; let connections = 0; beforeEach(async () => { connections = 0; server = http.createServer((req, res) => { if (req.url === '/link') { res.setHeader('Content-type', 'text/html'); res.end('<head><link rel="preconnect" href="//example.com" /></head><body>foo</body>'); return; } res.end(); }); server.on('connection', () => { connections++; }); await new Promise<void>(resolve => server.listen(0, '127.0.0.1', () => resolve())); url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; }); afterEach(async () => { server.close(); await closeWindow(w); w = null as unknown as BrowserWindow; server = null as unknown as http.Server; }); it('calling preconnect() connects to the server', async () => { w = new BrowserWindow({ show: false }); w.webContents.on('did-start-navigation', (event, url) => { w.webContents.session.preconnect({ url, numSockets: 4 }); }); await w.loadURL(url); expect(connections).to.equal(4); }); it('does not preconnect unless requested', async () => { w = new BrowserWindow({ show: false }); await w.loadURL(url); expect(connections).to.equal(1); }); it('parses <link rel=preconnect>', async () => { w = new BrowserWindow({ show: true }); const p = emittedOnce(w.webContents.session, 'preconnect'); w.loadURL(url + '/link'); const [, preconnectUrl, allowCredentials] = await p; expect(preconnectUrl).to.equal('http://example.com/'); expect(allowCredentials).to.be.true('allowCredentials'); }); }); describe('BrowserWindow.setAutoHideCursor(autoHide)', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); ifit(process.platform === 'darwin')('on macOS', () => { it('allows changing cursor auto-hiding', () => { expect(() => { w.setAutoHideCursor(false); w.setAutoHideCursor(true); }).to.not.throw(); }); }); ifit(process.platform !== 'darwin')('on non-macOS platforms', () => { it('is not available', () => { expect(w.setAutoHideCursor).to.be.undefined('setAutoHideCursor function'); }); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setWindowButtonVisibility()', () => { afterEach(closeAllWindows); it('does not throw', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setWindowButtonVisibility(true); w.setWindowButtonVisibility(false); }).to.not.throw(); }); it('changes window button visibility for normal window', () => { const w = new BrowserWindow({ show: false }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); it('changes window button visibility for frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); }); it('changes window button visibility for hiddenInset window', () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hiddenInset' }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); // Buttons of customButtonsOnHover are always hidden unless hovered. it('does not change window button visibility for customButtonsOnHover window', () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'customButtonsOnHover' }); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setVibrancy(type)', () => { let appProcess: childProcess.ChildProcessWithoutNullStreams | undefined; afterEach(() => { if (appProcess && !appProcess.killed) { appProcess.kill(); appProcess = undefined; } closeAllWindows(); }); it('allows setting, changing, and removing the vibrancy', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setVibrancy('light'); w.setVibrancy('dark'); w.setVibrancy(null); w.setVibrancy('ultra-dark'); w.setVibrancy('' as any); }).to.not.throw(); }); it('does not crash if vibrancy is set to an invalid value', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setVibrancy('i-am-not-a-valid-vibrancy-type' as any); }).to.not.throw(); }); it('Allows setting a transparent window via CSS', async () => { const appPath = path.join(__dirname, 'fixtures', 'apps', 'background-color-transparent'); appProcess = childProcess.spawn(process.execPath, [appPath]); const [code] = await emittedOnce(appProcess, 'exit'); expect(code).to.equal(0); }); }); ifdescribe(process.platform === 'darwin')('trafficLightPosition', () => { const pos = { x: 10, y: 10 }; afterEach(closeAllWindows); describe('BrowserWindow.getTrafficLightPosition(pos)', () => { it('gets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); expect(w.getTrafficLightPosition()).to.deep.equal(pos); }); it('gets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); expect(w.getTrafficLightPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setTrafficLightPosition(pos)', () => { it('sets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setTrafficLightPosition(newPos); expect(w.getTrafficLightPosition()).to.deep.equal(newPos); }); it('sets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setTrafficLightPosition(newPos); expect(w.getTrafficLightPosition()).to.deep.equal(newPos); }); }); }); ifdescribe(process.platform === 'win32')('BrowserWindow.setAppDetails(options)', () => { afterEach(closeAllWindows); it('supports setting the app details', () => { const w = new BrowserWindow({ show: false }); const iconPath = path.join(fixtures, 'assets', 'icon.ico'); expect(() => { w.setAppDetails({ appId: 'my.app.id' }); w.setAppDetails({ appIconPath: iconPath, appIconIndex: 0 }); w.setAppDetails({ appIconPath: iconPath }); w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name' }); w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2' }); w.setAppDetails({ relaunchDisplayName: 'My app name' }); w.setAppDetails({ appId: 'my.app.id', appIconPath: iconPath, appIconIndex: 0, relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name' }); w.setAppDetails({}); }).to.not.throw(); expect(() => { (w.setAppDetails as any)(); }).to.throw('Insufficient number of arguments.'); }); }); describe('BrowserWindow.fromId(id)', () => { afterEach(closeAllWindows); it('returns the window with id', () => { const w = new BrowserWindow({ show: false }); expect(BrowserWindow.fromId(w.id)!.id).to.equal(w.id); }); }); describe('BrowserWindow.fromWebContents(webContents)', () => { afterEach(closeAllWindows); it('returns the window with the webContents', () => { const w = new BrowserWindow({ show: false }); const found = BrowserWindow.fromWebContents(w.webContents); expect(found!.id).to.equal(w.id); }); it('returns null for webContents without a BrowserWindow', () => { const contents = (webContents as any).create({}); try { expect(BrowserWindow.fromWebContents(contents)).to.be.null('BrowserWindow.fromWebContents(contents)'); } finally { contents.destroy(); } }); it('returns the correct window for a BrowserView webcontents', async () => { const w = new BrowserWindow({ show: false }); const bv = new BrowserView(); w.setBrowserView(bv); defer(() => { w.removeBrowserView(bv); (bv.webContents as any).destroy(); }); await bv.webContents.loadURL('about:blank'); expect(BrowserWindow.fromWebContents(bv.webContents)!.id).to.equal(w.id); }); it('returns the correct window for a WebView webcontents', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } }); w.loadURL('data:text/html,<webview src="data:text/html,hi"></webview>'); // NOTE(nornagon): Waiting for 'did-attach-webview' is a workaround for // https://github.com/electron/electron/issues/25413, and is not integral // to the test. const p = emittedOnce(w.webContents, 'did-attach-webview'); const [, webviewContents] = await emittedOnce(app, 'web-contents-created'); expect(BrowserWindow.fromWebContents(webviewContents)!.id).to.equal(w.id); await p; }); 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((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 as any).destroy(); }); expect(BrowserWindow.fromBrowserView(bv)!.id).to.equal(w.id); }); it('returns the window when there are multiple BrowserViews', () => { const w = new BrowserWindow({ show: false }); const bv1 = new BrowserView(); w.addBrowserView(bv1); const bv2 = new BrowserView(); w.addBrowserView(bv2); defer(() => { w.removeBrowserView(bv1); w.removeBrowserView(bv2); (bv1.webContents as any).destroy(); (bv2.webContents as any).destroy(); }); expect(BrowserWindow.fromBrowserView(bv1)!.id).to.equal(w.id); expect(BrowserWindow.fromBrowserView(bv2)!.id).to.equal(w.id); }); it('returns undefined if not attached', () => { const bv = new BrowserView(); defer(() => { (bv.webContents as any).destroy(); }); expect(BrowserWindow.fromBrowserView(bv)).to.be.null('BrowserWindow associated with bv'); }); }); describe('BrowserWindow.setOpacity(opacity)', () => { afterEach(closeAllWindows); ifdescribe(process.platform !== 'linux')(('Windows and Mac'), () => { it('make window with initial opacity', () => { const w = new BrowserWindow({ show: false, opacity: 0.5 }); expect(w.getOpacity()).to.equal(0.5); }); it('allows setting the opacity', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setOpacity(0.0); expect(w.getOpacity()).to.equal(0.0); w.setOpacity(0.5); expect(w.getOpacity()).to.equal(0.5); w.setOpacity(1.0); expect(w.getOpacity()).to.equal(1.0); }).to.not.throw(); }); it('clamps opacity to [0.0...1.0]', () => { const w = new BrowserWindow({ show: false, opacity: 0.5 }); w.setOpacity(100); expect(w.getOpacity()).to.equal(1.0); w.setOpacity(-100); expect(w.getOpacity()).to.equal(0.0); }); }); ifdescribe(process.platform === 'linux')(('Linux'), () => { it('sets 1 regardless of parameter', () => { const w = new BrowserWindow({ show: false }); w.setOpacity(0); expect(w.getOpacity()).to.equal(1.0); w.setOpacity(0.5); expect(w.getOpacity()).to.equal(1.0); }); }); }); describe('BrowserWindow.setShape(rects)', () => { afterEach(closeAllWindows); it('allows setting shape', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setShape([]); w.setShape([{ x: 0, y: 0, width: 100, height: 100 }]); w.setShape([{ x: 0, y: 0, width: 100, height: 100 }, { x: 0, y: 200, width: 1000, height: 100 }]); w.setShape([]); }).to.not.throw(); }); }); describe('"useContentSize" option', () => { afterEach(closeAllWindows); it('make window created with content size when used', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, useContentSize: true }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); it('make window created with window size when not used', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400 }); const size = w.getSize(); expect(size).to.deep.equal([400, 400]); }); it('works for a frameless window', () => { const w = new BrowserWindow({ show: false, frame: false, width: 400, height: 400, useContentSize: true }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); const size = w.getSize(); expect(size).to.deep.equal([400, 400]); }); }); ifdescribe(process.platform === 'win32' || (process.platform === 'darwin' && semver.gte(os.release(), '14.0.0')))('"titleBarStyle" option', () => { const testWindowsOverlay = async (style: any) => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: style, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: true }); const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); if (process.platform === 'darwin') { await w.loadFile(overlayHTML); } else { const overlayReady = emittedOnce(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const overlayRect = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(overlayRect.y).to.equal(0); if (process.platform === 'darwin') { expect(overlayRect.x).to.be.greaterThan(0); } else { expect(overlayRect.x).to.equal(0); } expect(overlayRect.width).to.be.greaterThan(0); expect(overlayRect.height).to.be.greaterThan(0); const cssOverlayRect = await w.webContents.executeJavaScript('getCssOverlayProperties();'); expect(cssOverlayRect).to.deep.equal(overlayRect); const geometryChange = emittedOnce(ipcMain, 'geometrychange'); w.setBounds({ width: 800 }); const [, newOverlayRect] = await geometryChange; expect(newOverlayRect.width).to.equal(overlayRect.width + 400); }; afterEach(closeAllWindows); afterEach(() => { ipcMain.removeAllListeners('geometrychange'); }); it('creates browser window with hidden title bar', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden' }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); ifit(process.platform === 'darwin')('creates browser window with hidden inset title bar', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hiddenInset' }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); it('sets Window Control Overlay with hidden title bar', async () => { await testWindowsOverlay('hidden'); }); ifit(process.platform === 'darwin')('sets Window Control Overlay with hidden inset title bar', async () => { await testWindowsOverlay('hiddenInset'); }); }); ifdescribe(process.platform === 'win32' || (process.platform === 'darwin' && semver.gte(os.release(), '14.0.0')))('"titleBarOverlay" option', () => { const testWindowsOverlayHeight = async (size: any) => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden', webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { height: size } }); const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); if (process.platform === 'darwin') { await w.loadFile(overlayHTML); } else { const overlayReady = emittedOnce(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const overlayRectPreMax = await w.webContents.executeJavaScript('getJSOverlayProperties()'); await w.maximize(); const max = await w.isMaximized(); expect(max).to.equal(true); const overlayRectPostMax = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(overlayRectPreMax.y).to.equal(0); if (process.platform === 'darwin') { expect(overlayRectPreMax.x).to.be.greaterThan(0); } else { expect(overlayRectPreMax.x).to.equal(0); } expect(overlayRectPreMax.width).to.be.greaterThan(0); expect(overlayRectPreMax.height).to.equal(size); // Confirm that maximization only affected the height of the buttons and not the title bar expect(overlayRectPostMax.height).to.equal(size); }; afterEach(closeAllWindows); afterEach(() => { ipcMain.removeAllListeners('geometrychange'); }); it('sets Window Control Overlay with title bar height of 40', async () => { await testWindowsOverlayHeight(40); }); }); ifdescribe(process.platform === 'darwin')('"enableLargerThanScreen" option', () => { afterEach(closeAllWindows); it('can move the window out of screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); w.setPosition(-10, 50); const after = w.getPosition(); expect(after).to.deep.equal([-10, 50]); }); it('cannot move the window behind menu bar', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[1]).to.be.at.least(0); }); it('can move the window behind menu bar if it has no frame', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true, frame: false }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[0]).to.be.equal(-10); expect(after[1]).to.be.equal(-10); }); it('without it, cannot move the window out of screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: false }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[1]).to.be.at.least(0); }); it('can set the window larger than screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); const size = screen.getPrimaryDisplay().size; size.width += 100; size.height += 100; w.setSize(size.width, size.height); expectBoundsEqual(w.getSize(), [size.width, size.height]); }); it('without it, cannot set the window larger than screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: false }); const size = screen.getPrimaryDisplay().size; size.width += 100; size.height += 100; w.setSize(size.width, size.height); expect(w.getSize()[1]).to.at.most(screen.getPrimaryDisplay().size.height); }); }); ifdescribe(process.platform === 'darwin')('"zoomToPageWidth" option', () => { afterEach(closeAllWindows); it('sets the window width to the page width when used', () => { const w = new BrowserWindow({ show: false, width: 500, height: 400, zoomToPageWidth: true }); w.maximize(); expect(w.getSize()[0]).to.equal(500); }); }); describe('"tabbingIdentifier" option', () => { afterEach(closeAllWindows); it('can be set on a window', () => { expect(() => { /* eslint-disable no-new */ new BrowserWindow({ tabbingIdentifier: 'group1' }); new BrowserWindow({ tabbingIdentifier: 'group2', frame: false }); /* eslint-enable no-new */ }).not.to.throw(); }); }); describe('"webPreferences" option', () => { afterEach(() => { ipcMain.removeAllListeners('answer'); }); afterEach(closeAllWindows); describe('"preload" option', () => { const doesNotLeakSpec = (name: string, webPrefs: { nodeIntegration: boolean, sandbox: boolean, contextIsolation: boolean }) => { it(name, async () => { const w = new BrowserWindow({ webPreferences: { ...webPrefs, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'no-leak.html')); const [, result] = await emittedOnce(ipcMain, 'leak-result'); expect(result).to.have.property('require', 'undefined'); expect(result).to.have.property('exports', 'undefined'); expect(result).to.have.property('windowExports', 'undefined'); expect(result).to.have.property('windowPreload', 'undefined'); expect(result).to.have.property('windowRequire', 'undefined'); }); }; doesNotLeakSpec('does not leak require', { nodeIntegration: false, sandbox: false, contextIsolation: false }); doesNotLeakSpec('does not leak require when sandbox is enabled', { nodeIntegration: false, sandbox: true, contextIsolation: false }); doesNotLeakSpec('does not leak require when context isolation is enabled', { nodeIntegration: false, sandbox: false, contextIsolation: true }); doesNotLeakSpec('does not leak require when context isolation and sandbox are enabled', { nodeIntegration: false, sandbox: true, contextIsolation: true }); it('does not leak any node globals on the window object with nodeIntegration is disabled', async () => { let w = new BrowserWindow({ webPreferences: { contextIsolation: false, nodeIntegration: false, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'globals.html')); const [, notIsolated] = await emittedOnce(ipcMain, 'leak-result'); expect(notIsolated).to.have.property('globals'); w.destroy(); w = new BrowserWindow({ webPreferences: { contextIsolation: true, nodeIntegration: false, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'globals.html')); const [, isolated] = await emittedOnce(ipcMain, 'leak-result'); expect(isolated).to.have.property('globals'); const notIsolatedGlobals = new Set(notIsolated.globals); for (const isolatedGlobal of isolated.globals) { notIsolatedGlobals.delete(isolatedGlobal); } expect([...notIsolatedGlobals]).to.deep.equal([], 'non-isoalted renderer should have no additional globals'); }); it('loads the script before other scripts in window', async () => { const preload = path.join(fixtures, 'module', 'set-global.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false, preload } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test).to.eql('preload'); }); it('has synchronous access to all eventual window APIs', async () => { const preload = path.join(fixtures, 'module', 'access-blink-apis.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false, preload } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test).to.be.an('object'); expect(test.atPreload).to.be.an('array'); expect(test.atLoad).to.be.an('array'); expect(test.atPreload).to.deep.equal(test.atLoad, 'should have access to the same window APIs'); }); }); describe('session preload scripts', function () { const preloads = [ path.join(fixtures, 'module', 'set-global-preload-1.js'), path.join(fixtures, 'module', 'set-global-preload-2.js'), path.relative(process.cwd(), path.join(fixtures, 'module', 'set-global-preload-3.js')) ]; const defaultSession = session.defaultSession; beforeEach(() => { expect(defaultSession.getPreloads()).to.deep.equal([]); defaultSession.setPreloads(preloads); }); afterEach(() => { defaultSession.setPreloads([]); }); it('can set multiple session preload script', () => { expect(defaultSession.getPreloads()).to.deep.equal(preloads); }); const generateSpecs = (description: string, sandbox: boolean) => { describe(description, () => { it('loads the script before other scripts in window including normal preloads', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox, preload: path.join(fixtures, 'module', 'get-global-preload.js'), contextIsolation: false } }); w.loadURL('about:blank'); const [, preload1, preload2, preload3] = await emittedOnce(ipcMain, 'vars'); expect(preload1).to.equal('preload-1'); expect(preload2).to.equal('preload-1-2'); expect(preload3).to.be.undefined('preload 3'); }); }); }; generateSpecs('without sandbox', false); generateSpecs('with sandbox', true); }); describe('"additionalArguments" option', () => { it('adds extra args to process.argv in the renderer process', async () => { const preload = path.join(fixtures, 'module', 'check-arguments.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, preload, additionalArguments: ['--my-magic-arg'] } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, argv] = await emittedOnce(ipcMain, 'answer'); expect(argv).to.include('--my-magic-arg'); }); it('adds extra value args to process.argv in the renderer process', async () => { const preload = path.join(fixtures, 'module', 'check-arguments.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, preload, additionalArguments: ['--my-magic-arg=foo'] } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, argv] = await emittedOnce(ipcMain, 'answer'); expect(argv).to.include('--my-magic-arg=foo'); }); }); describe('"node-integration" option', () => { it('disables node integration by default', async () => { const preload = path.join(fixtures, 'module', 'send-later.js'); const w = new BrowserWindow({ show: false, webPreferences: { preload, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, typeofProcess, typeofBuffer] = await emittedOnce(ipcMain, 'answer'); expect(typeofProcess).to.equal('undefined'); expect(typeofBuffer).to.equal('undefined'); }); }); describe('"sandbox" option', () => { const preload = path.join(path.resolve(__dirname, 'fixtures'), 'module', 'preload-sandbox.js'); let server: http.Server = null as unknown as http.Server; let serverUrl: string = null as unknown as string; before((done) => { server = http.createServer((request, response) => { switch (request.url) { case '/cross-site': response.end(`<html><body><h1>${request.url}</h1></body></html>`); break; default: throw new Error(`unsupported endpoint: ${request.url}`); } }).listen(0, '127.0.0.1', () => { serverUrl = 'http://127.0.0.1:' + (server.address() as AddressInfo).port; done(); }); }); after(() => { server.close(); }); it('exposes ipcRenderer to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test).to.equal('preload'); }); it('exposes ipcRenderer to preload script (path has special chars)', async () => { const preloadSpecialChars = path.join(fixtures, 'module', 'preload-sandboxæø åü.js'); const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload: preloadSpecialChars, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test).to.equal('preload'); }); it('exposes "loaded" event to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload } }); w.loadURL('about:blank'); await emittedOnce(ipcMain, 'process-loaded'); }); it('exposes "exit" event to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?exit-event'); const pageUrl = 'file://' + htmlPath; w.loadURL(pageUrl); const [, url] = await emittedOnce(ipcMain, 'answer'); const expectedUrl = process.platform === 'win32' ? 'file:///' + htmlPath.replace(/\\/g, '/') : pageUrl; expect(url).to.equal(expectedUrl); }); it('should open windows in same domain with cross-scripting enabled', async () => { const w = new BrowserWindow({ show: true, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload } } })); const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?window-open'); const pageUrl = 'file://' + htmlPath; const answer = emittedOnce(ipcMain, 'answer'); w.loadURL(pageUrl); const [, { url, frameName, options }] = await emittedOnce(w.webContents, 'did-create-window'); const expectedUrl = process.platform === 'win32' ? 'file:///' + htmlPath.replace(/\\/g, '/') : pageUrl; expect(url).to.equal(expectedUrl); expect(frameName).to.equal('popup!'); expect(options.width).to.equal(500); expect(options.height).to.equal(600); const [, html] = await answer; expect(html).to.equal('<h1>scripting from opener</h1>'); }); it('should open windows in another domain with cross-scripting disabled', async () => { const w = new BrowserWindow({ show: true, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload } } })); w.loadFile( path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'window-open-external' } ); // Wait for a message from the main window saying that it's ready. await emittedOnce(ipcMain, 'opener-loaded'); // Ask the opener to open a popup with window.opener. const expectedPopupUrl = `${serverUrl}/cross-site`; // Set in "sandbox.html". w.webContents.send('open-the-popup', expectedPopupUrl); // The page is going to open a popup that it won't be able to close. // We have to close it from here later. const [, popupWindow] = await emittedOnce(app, 'browser-window-created'); // Ask the popup window for details. const detailsAnswer = emittedOnce(ipcMain, 'child-loaded'); popupWindow.webContents.send('provide-details'); const [, openerIsNull, , locationHref] = await detailsAnswer; expect(openerIsNull).to.be.false('window.opener is null'); expect(locationHref).to.equal(expectedPopupUrl); // Ask the page to access the popup. const touchPopupResult = emittedOnce(ipcMain, 'answer'); w.webContents.send('touch-the-popup'); const [, popupAccessMessage] = await touchPopupResult; // Ask the popup to access the opener. const touchOpenerResult = emittedOnce(ipcMain, 'answer'); popupWindow.webContents.send('touch-the-opener'); const [, openerAccessMessage] = await touchOpenerResult; // We don't need the popup anymore, and its parent page can't close it, // so let's close it from here before we run any checks. await closeWindow(popupWindow, { assertNotWindows: false }); expect(popupAccessMessage).to.be.a('string', 'child\'s .document is accessible from its parent window'); expect(popupAccessMessage).to.match(/^Blocked a frame with origin/); expect(openerAccessMessage).to.be.a('string', 'opener .document is accessible from a popup window'); expect(openerAccessMessage).to.match(/^Blocked a frame with origin/); }); it('should inherit the sandbox setting in opened windows', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [, { argv }] = await emittedOnce(ipcMain, 'answer'); expect(argv).to.include('--enable-sandbox'); }); it('should open windows with the options configured via new-window event listeners', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath, contextIsolation: false } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [[, childWebContents]] = await Promise.all([ emittedOnce(app, 'web-contents-created'), emittedOnce(ipcMain, 'answer') ]); const webPreferences = childWebContents.getLastWebPreferences(); expect(webPreferences.contextIsolation).to.equal(false); }); it('should set ipc event sender correctly', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); let childWc: WebContents | null = null; w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload, contextIsolation: false } } })); w.webContents.on('did-create-window', (win) => { childWc = win.webContents; expect(w.webContents).to.not.equal(childWc); }); ipcMain.once('parent-ready', function (event) { expect(event.sender).to.equal(w.webContents, 'sender should be the parent'); event.sender.send('verified'); }); ipcMain.once('child-ready', function (event) { expect(childWc).to.not.be.null('child webcontents should be available'); expect(event.sender).to.equal(childWc, 'sender should be the child'); event.sender.send('verified'); }); const done = Promise.all([ 'parent-answer', 'child-answer' ].map(name => emittedOnce(ipcMain, name))); w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'verify-ipc-sender' }); await done; }); describe('event handling', () => { let w: BrowserWindow = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); }); it('works for window events', async () => { const pageTitleUpdated = emittedOnce(w, 'page-title-updated'); w.loadURL('data:text/html,<script>document.title = \'changed\'</script>'); await pageTitleUpdated; }); it('works for stop events', async () => { const done = Promise.all([ 'did-navigate', 'did-fail-load', 'did-stop-loading' ].map(name => emittedOnce(w.webContents, name))); w.loadURL('data:text/html,<script>stop()</script>'); await done; }); it('works for web contents events', async () => { const done = Promise.all([ 'did-finish-load', 'did-frame-finish-load', 'did-navigate-in-page', 'will-navigate', 'did-start-loading', 'did-stop-loading', 'did-frame-finish-load', 'dom-ready' ].map(name => emittedOnce(w.webContents, name))); w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'webcontents-events' }); await done; }); }); it('supports calling preventDefault on new-window events', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const initialWebContents = webContents.getAllWebContents().map((i) => i.id); w.webContents.once('new-window', (e) => { e.preventDefault(); // We need to give it some time so the windows get properly disposed (at least on OSX). setTimeout(() => { const currentWebContents = webContents.getAllWebContents().map((i) => i.id); try { expect(currentWebContents).to.deep.equal(initialWebContents); done(); } catch (error) { done(e); } }, 100); }); w.loadFile(path.join(fixtures, 'pages', 'window-open.html')); }); it('validates process APIs access in sandboxed renderer', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.once('preload-error', (event, preloadPath, error) => { throw error; }); process.env.sandboxmain = 'foo'; w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test.hasCrash).to.be.true('has crash'); expect(test.hasHang).to.be.true('has hang'); expect(test.heapStatistics).to.be.an('object'); expect(test.blinkMemoryInfo).to.be.an('object'); expect(test.processMemoryInfo).to.be.an('object'); expect(test.systemVersion).to.be.a('string'); expect(test.cpuUsage).to.be.an('object'); expect(test.ioCounters).to.be.an('object'); expect(test.uptime).to.be.a('number'); expect(test.arch).to.equal(process.arch); expect(test.platform).to.equal(process.platform); expect(test.env).to.deep.equal(process.env); expect(test.execPath).to.equal(process.helperExecPath); expect(test.sandboxed).to.be.true('sandboxed'); expect(test.contextIsolated).to.be.false('contextIsolated'); expect(test.type).to.equal('renderer'); expect(test.version).to.equal(process.version); expect(test.versions).to.deep.equal(process.versions); expect(test.contextId).to.be.a('string'); if (process.platform === 'linux' && test.osSandbox) { expect(test.creationTime).to.be.null('creation time'); expect(test.systemMemoryInfo).to.be.null('system memory info'); } else { expect(test.creationTime).to.be.a('number'); expect(test.systemMemoryInfo).to.be.an('object'); } }); it('webview in sandbox renderer', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, webviewTag: true, contextIsolation: false } }); const didAttachWebview = emittedOnce(w.webContents, 'did-attach-webview'); const webviewDomReady = emittedOnce(ipcMain, 'webview-dom-ready'); w.loadFile(path.join(fixtures, 'pages', 'webview-did-attach-event.html')); const [, webContents] = await didAttachWebview; const [, id] = await webviewDomReady; expect(webContents.id).to.equal(id); }); }); describe('child windows', () => { let w: BrowserWindow = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, // tests relies on preloads in opened windows nodeIntegrationInSubFrames: true, contextIsolation: false } }); }); it('opens window of about:blank with cross-scripting enabled', async () => { const answer = emittedOnce(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-blank.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('opens window of same domain with cross-scripting enabled', async () => { const answer = emittedOnce(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-file.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('blocks accessing cross-origin frames', async () => { const answer = emittedOnce(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-cross-origin.html')); const [, content] = await answer; expect(content).to.equal('Blocked a frame with origin "file://" from accessing a cross-origin frame.'); }); it('opens window from <iframe> tags', async () => { const answer = emittedOnce(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-iframe.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('opens window with cross-scripting enabled from isolated context', async () => { const w = new BrowserWindow({ show: false, webPreferences: { preload: path.join(fixtures, 'api', 'native-window-open-isolated-preload.js') } }); w.loadFile(path.join(fixtures, 'api', 'native-window-open-isolated.html')); const [, content] = await emittedOnce(ipcMain, 'answer'); expect(content).to.equal('Hello'); }); ifit(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('loads native addons correctly after reload', async () => { w.loadFile(path.join(__dirname, 'fixtures', 'api', 'native-window-open-native-addon.html')); { const [, content] = await emittedOnce(ipcMain, 'answer'); expect(content).to.equal('function'); } w.reload(); { const [, content] = await emittedOnce(ipcMain, 'answer'); expect(content).to.equal('function'); } }); it('<webview> works in a scriptable popup', async () => { const preload = path.join(fixtures, 'api', 'new-window-webview-preload.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegrationInSubFrames: true, webviewTag: true, contextIsolation: false, preload } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { show: false, webPreferences: { contextIsolation: false, webviewTag: true, nodeIntegrationInSubFrames: true } } })); w.webContents.once('new-window', (event, url, frameName, disposition, options) => { options.show = false; }); const webviewLoaded = emittedOnce(ipcMain, 'webview-loaded'); w.loadFile(path.join(fixtures, 'api', 'new-window-webview.html')); await webviewLoaded; }); it('should open windows with the options configured via new-window event listeners', async () => { const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath, contextIsolation: false } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [[, childWebContents]] = await Promise.all([ emittedOnce(app, 'web-contents-created'), emittedOnce(ipcMain, 'answer') ]); const webPreferences = childWebContents.getLastWebPreferences(); expect(webPreferences.contextIsolation).to.equal(false); }); describe('window.location', () => { const protocols = [ ['foo', path.join(fixtures, 'api', 'window-open-location-change.html')], ['bar', path.join(fixtures, 'api', 'window-open-location-final.html')] ]; beforeEach(() => { for (const [scheme, path] of protocols) { protocol.registerBufferProtocol(scheme, (request, callback) => { callback({ mimeType: 'text/html', data: fs.readFileSync(path) }); }); } }); afterEach(() => { for (const [scheme] of protocols) { protocol.unregisterProtocol(scheme); } }); it('retains the original web preferences when window.location is changed to a new origin', async () => { const w = new BrowserWindow({ show: false, webPreferences: { // test relies on preloads in opened window nodeIntegrationInSubFrames: true, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: path.join(mainFixtures, 'api', 'window-open-preload.js'), contextIsolation: false, nodeIntegrationInSubFrames: true } } })); w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html')); const [, { nodeIntegration, typeofProcess }] = await emittedOnce(ipcMain, 'answer'); expect(nodeIntegration).to.be.false(); expect(typeofProcess).to.eql('undefined'); }); it('window.opener is not null when window.location is changed to a new origin', async () => { const w = new BrowserWindow({ show: false, webPreferences: { // test relies on preloads in opened window nodeIntegrationInSubFrames: true } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: path.join(mainFixtures, 'api', 'window-open-preload.js') } } })); w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html')); const [, { windowOpenerIsNull }] = await emittedOnce(ipcMain, 'answer'); expect(windowOpenerIsNull).to.be.false('window.opener is null'); }); }); }); describe('"disableHtmlFullscreenWindowResize" option', () => { it('prevents window from resizing when set', async () => { const w = new BrowserWindow({ show: false, webPreferences: { disableHtmlFullscreenWindowResize: true } }); await w.loadURL('about:blank'); const size = w.getSize(); const enterHtmlFullScreen = emittedOnce(w.webContents, 'enter-html-full-screen'); w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true); await enterHtmlFullScreen; expect(w.getSize()).to.deep.equal(size); }); }); }); describe('beforeunload handler', function () { let w: BrowserWindow = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(closeAllWindows); it('returning undefined would not prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html')); const wait = emittedOnce(w, 'closed'); w.close(); await wait; }); it('returning false would prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); const [, proceed] = await emittedOnce(w.webContents, 'before-unload-fired'); expect(proceed).to.equal(false); }); it('returning empty string would prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-empty-string.html')); w.close(); const [, proceed] = await emittedOnce(w.webContents, 'before-unload-fired'); expect(proceed).to.equal(false); }); it('emits for each close attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const destroyListener = () => { expect.fail('Close was not prevented'); }; w.webContents.once('destroyed', destroyListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await emittedOnce(w.webContents, 'console-message'); w.close(); await emittedOnce(w.webContents, 'before-unload-fired'); w.close(); await emittedOnce(w.webContents, 'before-unload-fired'); w.webContents.removeListener('destroyed', destroyListener); const wait = emittedOnce(w, 'closed'); w.close(); await wait; }); it('emits for each reload attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const navigationListener = () => { expect.fail('Reload was not prevented'); }; w.webContents.once('did-start-navigation', navigationListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await emittedOnce(w.webContents, 'console-message'); w.reload(); // Chromium does not emit 'before-unload-fired' on WebContents for // navigations, so we have to use other ways to know if beforeunload // is fired. await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.reload(); await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.webContents.removeListener('did-start-navigation', navigationListener); w.reload(); await emittedOnce(w.webContents, 'did-finish-load'); }); it('emits for each navigation attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const navigationListener = () => { expect.fail('Reload was not prevented'); }; w.webContents.once('did-start-navigation', navigationListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await emittedOnce(w.webContents, 'console-message'); w.loadURL('about:blank'); // Chromium does not emit 'before-unload-fired' on WebContents for // navigations, so we have to use other ways to know if beforeunload // is fired. await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.loadURL('about:blank'); await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.webContents.removeListener('did-start-navigation', navigationListener); await w.loadURL('about:blank'); }); }); describe('document.visibilityState/hidden', () => { afterEach(closeAllWindows); it('visibilityState is initially visible despite window being hidden', async () => { const w = new BrowserWindow({ show: false, width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); let readyToShow = false; w.once('ready-to-show', () => { readyToShow = true; }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(readyToShow).to.be.false('ready to show'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform !== 'win32')('visibilityState changes when window is hidden', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.hide(); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform !== 'win32')('visibilityState changes when window is shown', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); if (process.platform === 'darwin') { // See https://github.com/electron/electron/issues/8664 await emittedOnce(w, 'show'); } w.hide(); w.show(); const [, visibilityState] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); }); ifit(process.platform !== 'win32')('visibilityState changes when window is shown inactive', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); if (process.platform === 'darwin') { // See https://github.com/electron/electron/issues/8664 await emittedOnce(w, 'show'); } w.hide(); w.showInactive(); const [, visibilityState] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform === 'darwin')('visibilityState changes when window is minimized', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.minimize(); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } }); // FIXME(MarshallOfSound): This test fails locally 100% of the time, on CI it started failing // when we introduced the compositor recycling patch. Should figure out how to fix this it.skip('visibilityState remains visible if backgroundThrottling is disabled', async () => { const w = new BrowserWindow({ show: false, width: 100, height: 100, webPreferences: { backgroundThrottling: false, nodeIntegration: true } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } ipcMain.once('pong', (event, visibilityState, hidden) => { throw new Error(`Unexpected visibility change event. visibilityState: ${visibilityState} hidden: ${hidden}`); }); try { const shown1 = emittedOnce(w, 'show'); w.show(); await shown1; const hidden = emittedOnce(w, 'hide'); w.hide(); await hidden; const shown2 = emittedOnce(w, 'show'); w.show(); await shown2; } finally { ipcMain.removeAllListeners('pong'); } }); }); describe('new-window event', () => { afterEach(closeAllWindows); it('emits when window.open is called', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); w.webContents.once('new-window', (e, url, frameName, disposition, options) => { e.preventDefault(); try { expect(url).to.equal('http://host/'); expect(frameName).to.equal('host'); expect((options as any)['this-is-not-a-standard-feature']).to.equal(true); done(); } catch (e) { done(e); } }); w.loadFile(path.join(fixtures, 'pages', 'window-open.html')); }); it('emits when window.open is called with no webPreferences', (done) => { const w = new BrowserWindow({ show: false }); w.webContents.once('new-window', function (e, url, frameName, disposition, options) { e.preventDefault(); try { expect(url).to.equal('http://host/'); expect(frameName).to.equal('host'); expect((options as any)['this-is-not-a-standard-feature']).to.equal(true); done(); } catch (e) { done(e); } }); w.loadFile(path.join(fixtures, 'pages', 'window-open.html')); }); it('emits when link with target is called', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); w.webContents.once('new-window', (e, url, frameName) => { e.preventDefault(); try { expect(url).to.equal('http://host/'); expect(frameName).to.equal('target'); done(); } catch (e) { done(e); } }); w.loadFile(path.join(fixtures, 'pages', 'target-name.html')); }); it('includes all properties', async () => { const w = new BrowserWindow({ show: false }); const p = new Promise<{ url: string, frameName: string, disposition: string, options: BrowserWindowConstructorOptions, additionalFeatures: string[], referrer: Electron.Referrer, postBody: Electron.PostBody }>((resolve) => { w.webContents.once('new-window', (e, url, frameName, disposition, options, additionalFeatures, referrer, postBody) => { e.preventDefault(); resolve({ url, frameName, disposition, options, additionalFeatures, referrer, postBody }); }); }); w.loadURL(`data:text/html,${encodeURIComponent(` <form target="_blank" method="POST" id="form" action="http://example.com/test"> <input type="text" name="post-test-key" value="post-test-value"></input> </form> <script>form.submit()</script> `)}`); const { url, frameName, disposition, options, additionalFeatures, referrer, postBody } = await p; expect(url).to.equal('http://example.com/test'); expect(frameName).to.equal(''); expect(disposition).to.equal('foreground-tab'); expect(options).to.be.an('object').not.null(); expect(referrer.policy).to.equal('strict-origin-when-cross-origin'); expect(referrer.url).to.equal(''); expect(additionalFeatures).to.deep.equal([]); expect(postBody.data).to.have.length(1); expect(postBody.data[0].type).to.equal('rawData'); expect((postBody.data[0] as any).bytes).to.deep.equal(Buffer.from('post-test-key=post-test-value')); expect(postBody.contentType).to.equal('application/x-www-form-urlencoded'); }); }); ifdescribe(process.platform !== 'linux')('max/minimize events', () => { afterEach(closeAllWindows); it('emits an event when window is maximized', async () => { const w = new BrowserWindow({ show: false }); const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; }); it('emits an event when a transparent window is maximized', async () => { const w = new BrowserWindow({ show: false, frame: false, transparent: true }); const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; }); it('emits only one event when frameless window is maximized', () => { const w = new BrowserWindow({ show: false, frame: false }); let emitted = 0; w.on('maximize', () => emitted++); w.show(); w.maximize(); expect(emitted).to.equal(1); }); it('emits an event when window is unmaximized', async () => { const w = new BrowserWindow({ show: false }); const unmaximize = emittedOnce(w, 'unmaximize'); w.show(); w.maximize(); w.unmaximize(); await unmaximize; }); it('emits an event when a transparent window is unmaximized', async () => { const w = new BrowserWindow({ show: false, frame: false, transparent: true }); const maximize = emittedOnce(w, 'maximize'); const unmaximize = emittedOnce(w, 'unmaximize'); w.show(); w.maximize(); await maximize; w.unmaximize(); await unmaximize; }); it('emits an event when window is minimized', async () => { const w = new BrowserWindow({ show: false }); const minimize = emittedOnce(w, 'minimize'); w.show(); w.minimize(); await minimize; }); }); describe('beginFrameSubscription method', () => { it('does not crash when callback returns nothing', (done) => { const w = new BrowserWindow({ show: false }); 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(() => { w.webContents.endFrameSubscription(); done(); }); }); }); }); it('subscribes to frame updates', (done) => { const w = new BrowserWindow({ show: false }); let called = false; w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); w.webContents.on('dom-ready', () => { w.webContents.beginFrameSubscription(function (data) { // This callback might be called twice. if (called) return; called = true; try { expect(data.constructor.name).to.equal('NativeImage'); expect(data.isEmpty()).to.be.false('data is empty'); done(); } catch (e) { done(e); } finally { w.webContents.endFrameSubscription(); } }); }); }); it('subscribes to frame updates (only dirty rectangle)', (done) => { const w = new BrowserWindow({ show: false }); let called = false; let gotInitialFullSizeFrame = false; const [contentWidth, contentHeight] = w.getContentSize(); w.webContents.on('did-finish-load', () => { w.webContents.beginFrameSubscription(true, (image, rect) => { if (image.isEmpty()) { // Chromium sometimes sends a 0x0 frame at the beginning of the // page load. return; } if (rect.height === contentHeight && rect.width === contentWidth && !gotInitialFullSizeFrame) { // The initial frame is full-size, but we're looking for a call // with just the dirty-rect. The next frame should be a smaller // rect. gotInitialFullSizeFrame = true; return; } // This callback might be called twice. if (called) return; // We asked for just the dirty rectangle, so we expect to receive a // rect smaller than the full size. // TODO(jeremy): this is failing on windows currently; investigate. // assert(rect.width < contentWidth || rect.height < contentHeight) called = true; try { const expectedSize = rect.width * rect.height * 4; expect(image.getBitmap()).to.be.an.instanceOf(Buffer).with.lengthOf(expectedSize); done(); } catch (e) { done(e); } finally { w.webContents.endFrameSubscription(); } }); }); w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); }); it('throws error when subscriber is not well defined', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.webContents.beginFrameSubscription(true, true as any); // TODO(zcbenz): gin is weak at guessing parameter types, we should // upstream native_mate's implementation to gin. }).to.throw('Error processing argument at index 1, conversion failure from '); }); }); describe('savePage method', () => { const savePageDir = path.join(fixtures, 'save_page'); const savePageHtmlPath = path.join(savePageDir, 'save_page.html'); const savePageJsPath = path.join(savePageDir, 'save_page_files', 'test.js'); const savePageCssPath = path.join(savePageDir, 'save_page_files', 'test.css'); afterEach(() => { closeAllWindows(); try { fs.unlinkSync(savePageCssPath); fs.unlinkSync(savePageJsPath); fs.unlinkSync(savePageHtmlPath); fs.rmdirSync(path.join(savePageDir, 'save_page_files')); fs.rmdirSync(savePageDir); } catch {} }); it('should throw when passing relative paths', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await expect( w.webContents.savePage('save_page.html', 'HTMLComplete') ).to.eventually.be.rejectedWith('Path must be absolute'); await expect( w.webContents.savePage('save_page.html', 'HTMLOnly') ).to.eventually.be.rejectedWith('Path must be absolute'); await expect( w.webContents.savePage('save_page.html', 'MHTML') ).to.eventually.be.rejectedWith('Path must be absolute'); }); it('should save page to disk with HTMLOnly', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'HTMLOnly'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.false('js path'); expect(fs.existsSync(savePageCssPath)).to.be.false('css path'); }); it('should save page to disk with MHTML', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'MHTML'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.false('js path'); expect(fs.existsSync(savePageCssPath)).to.be.false('css path'); }); it('should save page to disk with HTMLComplete', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'HTMLComplete'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.true('js path'); expect(fs.existsSync(savePageCssPath)).to.be.true('css path'); }); }); describe('BrowserWindow options argument is optional', () => { afterEach(closeAllWindows); it('should create a window with default size (800x600)', () => { const w = new BrowserWindow(); expect(w.getSize()).to.deep.equal([800, 600]); }); }); describe('BrowserWindow.restore()', () => { afterEach(closeAllWindows); it('should restore the previous window size', () => { const w = new BrowserWindow({ minWidth: 800, width: 800 }); const initialSize = w.getSize(); w.minimize(); w.restore(); expectBoundsEqual(w.getSize(), initialSize); }); it('does not crash when restoring hidden minimized window', () => { const w = new BrowserWindow({}); w.minimize(); w.hide(); w.show(); }); }); // 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 = emittedOnce(w, 'hide'); let shown = emittedOnce(w, 'show'); const maximize = emittedOnce(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 = emittedOnce(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 = emittedOnce(w, 'minimize'); w.minimize(); await minimize; w.unmaximize(); await delay(1000); expect(w.isMinimized()).to.be.true(); }); it('should not change the size or position of a normal window', async () => { const w = new BrowserWindow(); const initialSize = w.getSize(); const initialPosition = w.getPosition(); w.unmaximize(); await delay(1000); expectBoundsEqual(w.getSize(), initialSize); expectBoundsEqual(w.getPosition(), initialPosition); }); 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 delay(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 = emittedOnce(w, 'show'); // start fullscreen and hidden w.setFullScreen(true); w.show(); await shown; const leftFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leftFullScreen; expect(w.isVisible()).to.be.true('visible'); expect(w.isFullScreen()).to.be.false('fullscreen'); }); it('should keep window hidden if already in hidden state', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const leftFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leftFullScreen; expect(w.isVisible()).to.be.false('visible'); expect(w.isFullScreen()).to.be.false('fullscreen'); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setFullScreen(false) when HTML fullscreen', () => { it('exits HTML fullscreen when window leaves fullscreen', async () => { const w = new BrowserWindow(); await w.loadURL('about:blank'); await w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true); await emittedOnce(w, 'enter-full-screen'); // Wait a tick for the full-screen state to 'stick' await delay(); w.setFullScreen(false); await emittedOnce(w, 'leave-html-full-screen'); }); }); }); describe('parent window', () => { afterEach(closeAllWindows); ifit(process.platform === 'darwin')('sheet-begin event emits when window opens a sheet', async () => { const w = new BrowserWindow(); const sheetBegin = emittedOnce(w, 'sheet-begin'); // eslint-disable-next-line no-new new BrowserWindow({ modal: true, parent: w }); await sheetBegin; }); ifit(process.platform === 'darwin')('sheet-end event emits when window has closed a sheet', async () => { const w = new BrowserWindow(); const sheet = new BrowserWindow({ modal: true, parent: w }); const sheetEnd = emittedOnce(w, 'sheet-end'); sheet.close(); await sheetEnd; }); describe('parent option', () => { it('sets parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(c.getParentWindow()).to.equal(w); }); it('adds window to child windows of parent', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(w.getChildWindows()).to.deep.equal([c]); }); it('removes from child windows of parent when window is closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); const closed = emittedOnce(c, 'closed'); c.close(); await closed; // The child window list is not immediately cleared, so wait a tick until it's ready. await delay(); expect(w.getChildWindows().length).to.equal(0); }); it('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 delay(); 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 = emittedOnce(c, 'closed'); c.setParentWindow(w); c.close(); await closed; // The child window list is not immediately cleared, so wait a tick until it's ready. await delay(); expect(w.getChildWindows().length).to.equal(0); }); }); describe('modal option', () => { it('does not freeze or crash', async () => { const parentWindow = new BrowserWindow(); const createTwo = async () => { const two = new BrowserWindow({ width: 300, height: 200, parent: parentWindow, modal: true, show: false }); const twoShown = emittedOnce(two, 'show'); two.show(); await twoShown; setTimeout(() => two.close(), 500); await emittedOnce(two, 'closed'); }; const one = new BrowserWindow({ width: 600, height: 400, parent: parentWindow, modal: true, show: false }); const oneShown = emittedOnce(one, 'show'); one.show(); await oneShown; setTimeout(() => one.destroy(), 500); await emittedOnce(one, 'closed'); await createTwo(); }); ifit(process.platform !== 'darwin')('disables parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); expect(w.isEnabled()).to.be.true('w.isEnabled'); c.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); }); ifit(process.platform !== 'darwin')('re-enables an enabled parent window when closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const closed = emittedOnce(c, 'closed'); c.show(); c.close(); await closed; expect(w.isEnabled()).to.be.true('w.isEnabled'); }); ifit(process.platform !== 'darwin')('does not re-enable a disabled parent window when closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const closed = emittedOnce(c, 'closed'); w.setEnabled(false); c.show(); c.close(); await closed; expect(w.isEnabled()).to.be.false('w.isEnabled'); }); ifit(process.platform !== 'darwin')('disables parent window recursively', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const c2 = new BrowserWindow({ show: false, parent: w, modal: true }); c.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c2.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c.destroy(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c2.destroy(); expect(w.isEnabled()).to.be.true('w.isEnabled'); }); }); }); describe('window states', () => { afterEach(closeAllWindows); it('does not resize frameless windows when states change', () => { const w = new BrowserWindow({ frame: false, width: 300, height: 200, show: false }); w.minimizable = false; w.minimizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.resizable = false; w.resizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.maximizable = false; w.maximizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.fullScreenable = false; w.fullScreenable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.closable = false; w.closable = true; expect(w.getSize()).to.deep.equal([300, 200]); }); describe('resizable state', () => { it('with properties', () => { it('can be set with resizable constructor option', () => { const w = new BrowserWindow({ show: false, resizable: false }); expect(w.resizable).to.be.false('resizable'); if (process.platform === 'darwin') { expect(w.maximizable).to.to.true('maximizable'); } }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.resizable).to.be.true('resizable'); w.resizable = false; expect(w.resizable).to.be.false('resizable'); w.resizable = true; expect(w.resizable).to.be.true('resizable'); }); }); it('with functions', () => { it('can be set with resizable constructor option', () => { const w = new BrowserWindow({ show: false, resizable: false }); expect(w.isResizable()).to.be.false('resizable'); if (process.platform === 'darwin') { expect(w.isMaximizable()).to.to.true('maximizable'); } }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isResizable()).to.be.true('resizable'); w.setResizable(false); expect(w.isResizable()).to.be.false('resizable'); w.setResizable(true); expect(w.isResizable()).to.be.true('resizable'); }); }); it('works for a frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); expect(w.resizable).to.be.true('resizable'); if (process.platform === 'win32') { const w = new BrowserWindow({ show: false, thickFrame: false }); expect(w.resizable).to.be.false('resizable'); } }); // On Linux there is no "resizable" property of a window. ifit(process.platform !== 'linux')('does affect maximizability when disabled and enabled', () => { const w = new BrowserWindow({ show: false }); expect(w.resizable).to.be.true('resizable'); expect(w.maximizable).to.be.true('maximizable'); w.resizable = false; expect(w.maximizable).to.be.false('not maximizable'); w.resizable = true; expect(w.maximizable).to.be.true('maximizable'); }); ifit(process.platform === 'win32')('works for a window smaller than 64x64', () => { const w = new BrowserWindow({ show: false, frame: false, resizable: false, transparent: true }); w.setContentSize(60, 60); expectBoundsEqual(w.getContentSize(), [60, 60]); w.setContentSize(30, 30); expectBoundsEqual(w.getContentSize(), [30, 30]); w.setContentSize(10, 10); expectBoundsEqual(w.getContentSize(), [10, 10]); }); }); describe('loading main frame state', () => { let server: http.Server = null as unknown as http.Server; let serverUrl: string = null as unknown as string; before((done) => { server = http.createServer((request, response) => { response.end(); }).listen(0, '127.0.0.1', () => { serverUrl = 'http://127.0.0.1:' + (server.address() as AddressInfo).port; done(); }); }); after(() => { server.close(); }); it('is true when the main frame is loading', async () => { const w = new BrowserWindow({ show: false }); const didStartLoading = emittedOnce(w.webContents, 'did-start-loading'); w.webContents.loadURL(serverUrl); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame'); }); it('is false when only a subframe is loading', async () => { const w = new BrowserWindow({ show: false }); const didStopLoading = emittedOnce(w.webContents, 'did-stop-loading'); w.webContents.loadURL(serverUrl); await didStopLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); const didStartLoading = emittedOnce(w.webContents, 'did-start-loading'); w.webContents.executeJavaScript(` var iframe = document.createElement('iframe') iframe.src = '${serverUrl}/page2' document.body.appendChild(iframe) `); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); }); it('is true when navigating to pages from the same origin', async () => { const w = new BrowserWindow({ show: false }); const didStopLoading = emittedOnce(w.webContents, 'did-stop-loading'); w.webContents.loadURL(serverUrl); await didStopLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); const didStartLoading = emittedOnce(w.webContents, 'did-start-loading'); w.webContents.loadURL(`${serverUrl}/page2`); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame'); }); }); }); ifdescribe(process.platform !== 'linux')('window states (excluding Linux)', () => { // Not implemented on Linux. afterEach(closeAllWindows); describe('movable state', () => { it('with properties', () => { it('can be set with movable constructor option', () => { const w = new BrowserWindow({ show: false, movable: false }); expect(w.movable).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.movable).to.be.true('movable'); w.movable = false; expect(w.movable).to.be.false('movable'); w.movable = true; expect(w.movable).to.be.true('movable'); }); }); it('with functions', () => { it('can be set with movable constructor option', () => { const w = new BrowserWindow({ show: false, movable: false }); expect(w.isMovable()).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMovable()).to.be.true('movable'); w.setMovable(false); expect(w.isMovable()).to.be.false('movable'); w.setMovable(true); expect(w.isMovable()).to.be.true('movable'); }); }); }); describe('visibleOnAllWorkspaces state', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.visibleOnAllWorkspaces).to.be.false(); w.visibleOnAllWorkspaces = true; expect(w.visibleOnAllWorkspaces).to.be.true(); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isVisibleOnAllWorkspaces()).to.be.false(); w.setVisibleOnAllWorkspaces(true); expect(w.isVisibleOnAllWorkspaces()).to.be.true(); }); }); }); ifdescribe(process.platform === 'darwin')('documentEdited state', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.documentEdited).to.be.false(); w.documentEdited = true; expect(w.documentEdited).to.be.true(); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isDocumentEdited()).to.be.false(); w.setDocumentEdited(true); expect(w.isDocumentEdited()).to.be.true(); }); }); }); ifdescribe(process.platform === 'darwin')('representedFilename', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.representedFilename).to.eql(''); w.representedFilename = 'a name'; expect(w.representedFilename).to.eql('a name'); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.getRepresentedFilename()).to.eql(''); w.setRepresentedFilename('a name'); expect(w.getRepresentedFilename()).to.eql('a name'); }); }); }); describe('native window title', () => { it('with properties', () => { it('can be set with title constructor option', () => { const w = new BrowserWindow({ show: false, title: 'mYtItLe' }); expect(w.title).to.eql('mYtItLe'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.title).to.eql('Electron Test Main'); w.title = 'NEW TITLE'; expect(w.title).to.eql('NEW TITLE'); }); }); it('with functions', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, title: 'mYtItLe' }); expect(w.getTitle()).to.eql('mYtItLe'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.getTitle()).to.eql('Electron Test Main'); w.setTitle('NEW TITLE'); expect(w.getTitle()).to.eql('NEW TITLE'); }); }); }); describe('minimizable state', () => { it('with properties', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, minimizable: false }); expect(w.minimizable).to.be.false('minimizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.minimizable).to.be.true('minimizable'); w.minimizable = false; expect(w.minimizable).to.be.false('minimizable'); w.minimizable = true; expect(w.minimizable).to.be.true('minimizable'); }); }); it('with functions', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, minimizable: false }); expect(w.isMinimizable()).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMinimizable()).to.be.true('isMinimizable'); w.setMinimizable(false); expect(w.isMinimizable()).to.be.false('isMinimizable'); w.setMinimizable(true); expect(w.isMinimizable()).to.be.true('isMinimizable'); }); }); }); describe('maximizable state (property)', () => { it('with properties', () => { it('can be set with maximizable constructor option', () => { const w = new BrowserWindow({ show: false, maximizable: false }); expect(w.maximizable).to.be.false('maximizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.maximizable).to.be.true('maximizable'); w.maximizable = false; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; expect(w.maximizable).to.be.true('maximizable'); }); it('is not affected when changing other states', () => { const w = new BrowserWindow({ show: false }); w.maximizable = false; expect(w.maximizable).to.be.false('maximizable'); w.minimizable = false; expect(w.maximizable).to.be.false('maximizable'); w.closable = false; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; expect(w.maximizable).to.be.true('maximizable'); w.closable = true; expect(w.maximizable).to.be.true('maximizable'); w.fullScreenable = false; expect(w.maximizable).to.be.true('maximizable'); }); }); it('with functions', () => { it('can be set with maximizable constructor option', () => { const w = new BrowserWindow({ show: false, maximizable: false }); expect(w.isMaximizable()).to.be.false('isMaximizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setMaximizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); it('is not affected when changing other states', () => { const w = new BrowserWindow({ show: false }); w.setMaximizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMinimizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setClosable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setClosable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setFullScreenable(false); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); }); }); ifdescribe(process.platform === 'win32')('maximizable state', () => { it('with properties', () => { it('is reset to its former state', () => { const w = new BrowserWindow({ show: false }); w.maximizable = false; w.resizable = false; w.resizable = true; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; w.resizable = false; w.resizable = true; expect(w.maximizable).to.be.true('maximizable'); }); }); it('with functions', () => { it('is reset to its former state', () => { const w = new BrowserWindow({ show: false }); w.setMaximizable(false); w.setResizable(false); w.setResizable(true); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); w.setResizable(false); w.setResizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); }); }); ifdescribe(process.platform !== 'darwin')('menuBarVisible state', () => { describe('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.menuBarVisible).to.be.true(); w.menuBarVisible = false; expect(w.menuBarVisible).to.be.false(); w.menuBarVisible = true; expect(w.menuBarVisible).to.be.true(); }); }); describe('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); w.setMenuBarVisibility(false); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); w.setMenuBarVisibility(true); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); }); }); }); ifdescribe(process.platform === 'darwin')('fullscreenable state', () => { it('with functions', () => { it('can be set with fullscreenable constructor option', () => { const w = new BrowserWindow({ show: false, fullscreenable: false }); expect(w.isFullScreenable()).to.be.false('isFullScreenable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isFullScreenable()).to.be.true('isFullScreenable'); w.setFullScreenable(false); expect(w.isFullScreenable()).to.be.false('isFullScreenable'); w.setFullScreenable(true); expect(w.isFullScreenable()).to.be.true('isFullScreenable'); }); }); }); // fullscreen events are dispatched eagerly and twiddling things too fast can confuse poor Electron ifdescribe(process.platform === 'darwin')('kiosk state', () => { it('with properties', () => { it('can be set with a constructor property', () => { const w = new BrowserWindow({ kiosk: true }); expect(w.kiosk).to.be.true(); }); it('can be changed ', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.kiosk = true; expect(w.isKiosk()).to.be.true('isKiosk'); await enterFullScreen; await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.kiosk = false; expect(w.isKiosk()).to.be.false('isKiosk'); await leaveFullScreen; }); }); it('with functions', () => { it('can be set with a constructor property', () => { const w = new BrowserWindow({ kiosk: true }); expect(w.isKiosk()).to.be.true(); }); it('can be changed ', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setKiosk(true); expect(w.isKiosk()).to.be.true('isKiosk'); await enterFullScreen; await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setKiosk(false); expect(w.isKiosk()).to.be.false('isKiosk'); await leaveFullScreen; }); }); }); ifdescribe(process.platform === 'darwin')('fullscreen state with resizable set', () => { it('resizable flag should be set to true and restored', async () => { const w = new BrowserWindow({ resizable: false }); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.resizable).to.be.true('resizable'); await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.resizable).to.be.false('resizable'); }); }); ifdescribe(process.platform === 'darwin')('fullscreen state', () => { it('should not cause a crash if called when exiting fullscreen', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; }); it('can be changed with setFullScreen method', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('isFullScreen'); }); it('handles several transitions starting with fullscreen', async () => { const w = new BrowserWindow({ fullscreen: true, show: true }); expect(w.isFullScreen()).to.be.true('not fullscreen'); w.setFullScreen(false); w.setFullScreen(true); const enterFullScreen = emittedNTimes(w, 'enter-full-screen', 2); await enterFullScreen; expect(w.isFullScreen()).to.be.true('not fullscreen'); await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); }); it('handles several transitions in close proximity', async () => { const w = new BrowserWindow(); expect(w.isFullScreen()).to.be.false('is fullscreen'); w.setFullScreen(true); w.setFullScreen(false); w.setFullScreen(true); const enterFullScreen = emittedNTimes(w, 'enter-full-screen', 2); await enterFullScreen; expect(w.isFullScreen()).to.be.true('not fullscreen'); }); it('does not crash when exiting simpleFullScreen (properties)', async () => { const w = new BrowserWindow(); w.setSimpleFullScreen(true); await delay(1000); w.setFullScreen(!w.isFullScreen()); }); it('does not crash when exiting simpleFullScreen (functions)', async () => { const w = new BrowserWindow(); w.simpleFullScreen = true; await delay(1000); w.setFullScreen(!w.isFullScreen()); }); it('should not be changed by setKiosk method', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await delay(); w.setKiosk(true); await delay(); w.setKiosk(false); expect(w.isFullScreen()).to.be.true('isFullScreen'); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('isFullScreen'); }); // FIXME: https://github.com/electron/electron/issues/30140 xit('multiple windows inherit correct fullscreen state', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await delay(); const w2 = new BrowserWindow({ show: false }); const enterFullScreen2 = emittedOnce(w2, 'enter-full-screen'); w2.show(); await enterFullScreen2; expect(w2.isFullScreen()).to.be.true('isFullScreen'); }); }); describe('closable state', () => { it('with properties', () => { it('can be set with closable constructor option', () => { const w = new BrowserWindow({ show: false, closable: false }); expect(w.closable).to.be.false('closable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.closable).to.be.true('closable'); w.closable = false; expect(w.closable).to.be.false('closable'); w.closable = true; expect(w.closable).to.be.true('closable'); }); }); it('with functions', () => { it('can be set with closable constructor option', () => { const w = new BrowserWindow({ show: false, closable: false }); expect(w.isClosable()).to.be.false('isClosable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isClosable()).to.be.true('isClosable'); w.setClosable(false); expect(w.isClosable()).to.be.false('isClosable'); w.setClosable(true); expect(w.isClosable()).to.be.true('isClosable'); }); }); }); describe('hasShadow state', () => { it('with properties', () => { it('returns a boolean on all platforms', () => { const w = new BrowserWindow({ show: false }); expect(w.shadow).to.be.a('boolean'); }); // On Windows there's no shadow by default & it can't be changed dynamically. it('can be changed with hasShadow option', () => { const hasShadow = process.platform !== 'darwin'; const w = new BrowserWindow({ show: false, hasShadow }); expect(w.shadow).to.equal(hasShadow); }); it('can be changed with setHasShadow method', () => { const w = new BrowserWindow({ show: false }); w.shadow = false; expect(w.shadow).to.be.false('hasShadow'); w.shadow = true; expect(w.shadow).to.be.true('hasShadow'); w.shadow = false; expect(w.shadow).to.be.false('hasShadow'); }); }); describe('with functions', () => { it('returns a boolean on all platforms', () => { const w = new BrowserWindow({ show: false }); const hasShadow = w.hasShadow(); expect(hasShadow).to.be.a('boolean'); }); // On Windows there's no shadow by default & it can't be changed dynamically. it('can be changed with hasShadow option', () => { const hasShadow = process.platform !== 'darwin'; const w = new BrowserWindow({ show: false, hasShadow }); expect(w.hasShadow()).to.equal(hasShadow); }); it('can be changed with setHasShadow method', () => { const w = new BrowserWindow({ show: false }); w.setHasShadow(false); expect(w.hasShadow()).to.be.false('hasShadow'); w.setHasShadow(true); expect(w.hasShadow()).to.be.true('hasShadow'); w.setHasShadow(false); expect(w.hasShadow()).to.be.false('hasShadow'); }); }); }); }); describe('window.getMediaSourceId()', () => { afterEach(closeAllWindows); it('returns valid source id', async () => { const w = new BrowserWindow({ show: false }); const shown = emittedOnce(w, 'show'); w.show(); await shown; // Check format 'window:1234:0'. const sourceId = w.getMediaSourceId(); expect(sourceId).to.match(/^window:\d+:\d+$/); }); }); ifdescribe(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('window.getNativeWindowHandle()', () => { afterEach(closeAllWindows); it('returns valid handle', () => { const w = new BrowserWindow({ show: false }); // The module's source code is hosted at // https://github.com/electron/node-is-valid-window const isValidWindow = require('is-valid-window'); expect(isValidWindow(w.getNativeWindowHandle())).to.be.true('is valid window'); }); }); ifdescribe(process.platform === 'darwin')('previewFile', () => { afterEach(closeAllWindows); it('opens the path in Quick Look on macOS', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.previewFile(__filename); w.closeFilePreview(); }).to.not.throw(); }); }); describe('contextIsolation option with and without sandbox option', () => { const expectedContextData = { preloadContext: { preloadProperty: 'number', pageProperty: 'undefined', typeofRequire: 'function', typeofProcess: 'object', typeofArrayPush: 'function', typeofFunctionApply: 'function', typeofPreloadExecuteJavaScriptProperty: 'undefined' }, pageContext: { preloadProperty: 'undefined', pageProperty: 'string', typeofRequire: 'undefined', typeofProcess: 'undefined', typeofArrayPush: 'number', typeofFunctionApply: 'boolean', typeofPreloadExecuteJavaScriptProperty: 'number', typeofOpenedWindow: 'object' } }; afterEach(closeAllWindows); it('separates the page context from the Electron/preload context', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = emittedOnce(ipcMain, 'isolated-world'); iw.loadFile(path.join(fixtures, 'api', 'isolated.html')); const [, data] = await p; expect(data).to.deep.equal(expectedContextData); }); it('recreates the contexts on reload', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); await iw.loadFile(path.join(fixtures, 'api', 'isolated.html')); const isolatedWorld = emittedOnce(ipcMain, 'isolated-world'); iw.webContents.reload(); const [, data] = await isolatedWorld; expect(data).to.deep.equal(expectedContextData); }); it('enables context isolation on child windows', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const browserWindowCreated = emittedOnce(app, 'browser-window-created'); iw.loadFile(path.join(fixtures, 'pages', 'window-open.html')); const [, window] = await browserWindowCreated; expect(window.webContents.getLastWebPreferences().contextIsolation).to.be.true('contextIsolation'); }); it('separates the page context from the Electron/preload context with sandbox on', async () => { const ws = new BrowserWindow({ show: false, webPreferences: { sandbox: true, contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = emittedOnce(ipcMain, 'isolated-world'); ws.loadFile(path.join(fixtures, 'api', 'isolated.html')); const [, data] = await p; expect(data).to.deep.equal(expectedContextData); }); it('recreates the contexts on reload with sandbox on', async () => { const ws = new BrowserWindow({ show: false, webPreferences: { sandbox: true, contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); await ws.loadFile(path.join(fixtures, 'api', 'isolated.html')); const isolatedWorld = emittedOnce(ipcMain, 'isolated-world'); ws.webContents.reload(); const [, data] = await isolatedWorld; expect(data).to.deep.equal(expectedContextData); }); it('supports fetch api', async () => { const fetchWindow = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-fetch-preload.js') } }); const p = emittedOnce(ipcMain, 'isolated-fetch-error'); fetchWindow.loadURL('about:blank'); const [, error] = await p; expect(error).to.equal('Failed to fetch'); }); it('doesn\'t break ipc serialization', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = emittedOnce(ipcMain, 'isolated-world'); iw.loadURL('about:blank'); iw.webContents.executeJavaScript(` const opened = window.open() openedLocation = opened.location.href opened.close() window.postMessage({openedLocation}, '*') `); const [, data] = await p; expect(data.pageContext.openedLocation).to.equal('about:blank'); }); it('reports process.contextIsolated', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-process.js') } }); const p = emittedOnce(ipcMain, 'context-isolation'); iw.loadURL('about:blank'); const [, contextIsolation] = await p; expect(contextIsolation).to.be.true('contextIsolation'); }); }); it('reloading does not cause Node.js module API hangs after reload', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); let count = 0; ipcMain.on('async-node-api-done', () => { if (count === 3) { ipcMain.removeAllListeners('async-node-api-done'); done(); } else { count++; w.reload(); } }); w.loadFile(path.join(fixtures, 'pages', 'send-after-node.html')); }); describe('window.webContents.focus()', () => { afterEach(closeAllWindows); it('focuses window', async () => { const w1 = new BrowserWindow({ x: 100, y: 300, width: 300, height: 200 }); w1.loadURL('about:blank'); const w2 = new BrowserWindow({ x: 300, y: 300, width: 300, height: 200 }); w2.loadURL('about:blank'); const w1Focused = emittedOnce(w1, 'focus'); w1.webContents.focus(); await w1Focused; expect(w1.webContents.isFocused()).to.be.true('focuses window'); }); }); ifdescribe(features.isOffscreenRenderingEnabled())('offscreen rendering', () => { let w: BrowserWindow; beforeEach(function () { w = new BrowserWindow({ width: 100, height: 100, show: false, webPreferences: { backgroundThrottling: false, offscreen: true } }); }); afterEach(closeAllWindows); it('creates offscreen window with correct size', async () => { const paint = emittedOnce(w.webContents, 'paint'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); const [,, data] = await paint; expect(data.constructor.name).to.equal('NativeImage'); expect(data.isEmpty()).to.be.false('data is empty'); const size = data.getSize(); const { scaleFactor } = screen.getPrimaryDisplay(); expect(size.width).to.be.closeTo(100 * scaleFactor, 2); expect(size.height).to.be.closeTo(100 * scaleFactor, 2); }); it('does not crash after navigation', () => { w.webContents.loadURL('about:blank'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); }); describe('window.webContents.isOffscreen()', () => { it('is true for offscreen type', () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); expect(w.webContents.isOffscreen()).to.be.true('isOffscreen'); }); it('is false for regular window', () => { const c = new BrowserWindow({ show: false }); expect(c.webContents.isOffscreen()).to.be.false('isOffscreen'); c.destroy(); }); }); describe('window.webContents.isPainting()', () => { it('returns whether is currently painting', async () => { const paint = emittedOnce(w.webContents, 'paint'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await paint; expect(w.webContents.isPainting()).to.be.true('isPainting'); }); }); describe('window.webContents.stopPainting()', () => { it('stops painting', async () => { const domReady = emittedOnce(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.stopPainting(); expect(w.webContents.isPainting()).to.be.false('isPainting'); }); }); describe('window.webContents.startPainting()', () => { it('starts painting', async () => { const domReady = emittedOnce(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.stopPainting(); w.webContents.startPainting(); await emittedOnce(w.webContents, 'paint'); expect(w.webContents.isPainting()).to.be.true('isPainting'); }); }); describe('frameRate APIs', () => { it('has default frame rate (function)', async () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await emittedOnce(w.webContents, 'paint'); expect(w.webContents.getFrameRate()).to.equal(60); }); it('has default frame rate (property)', async () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await emittedOnce(w.webContents, 'paint'); expect(w.webContents.frameRate).to.equal(60); }); it('sets custom frame rate (function)', async () => { const domReady = emittedOnce(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.setFrameRate(30); await emittedOnce(w.webContents, 'paint'); expect(w.webContents.getFrameRate()).to.equal(30); }); it('sets custom frame rate (property)', async () => { const domReady = emittedOnce(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.frameRate = 30; await emittedOnce(w.webContents, 'paint'); expect(w.webContents.frameRate).to.equal(30); }); }); }); describe('"transparent" option', () => { afterEach(closeAllWindows); // Only applicable on Windows where transparent windows can't be maximized. ifit(process.platform === 'win32')('can show maximized frameless window', async () => { const display = screen.getPrimaryDisplay(); const w = new BrowserWindow({ ...display.bounds, frame: false, transparent: true, show: true }); w.loadURL('about:blank'); await emittedOnce(w, 'ready-to-show'); expect(w.isMaximized()).to.be.true(); // Fails when the transparent HWND is in an invalid maximized state. expect(w.getBounds()).to.deep.equal(display.workArea); const newBounds = { width: 256, height: 256, x: 0, y: 0 }; w.setBounds(newBounds); expect(w.getBounds()).to.deep.equal(newBounds); }); // Linux and arm64 platforms (WOA and macOS) do not return any capture sources ifit(process.platform !== 'linux' && process.arch !== 'arm64')('should not display a visible background', async () => { const display = screen.getPrimaryDisplay(); const backgroundWindow = new BrowserWindow({ ...display.bounds, frame: false, backgroundColor: CHROMA_COLOR_HEX, hasShadow: false }); await backgroundWindow.loadURL('about:blank'); const foregroundWindow = new BrowserWindow({ ...display.bounds, show: true, transparent: true, frame: false, hasShadow: false }); foregroundWindow.loadFile(path.join(__dirname, 'fixtures', 'pages', 'half-background-color.html')); await emittedOnce(foregroundWindow, 'ready-to-show'); const screenCapture = await captureScreen(); const leftHalfColor = getPixelColor(screenCapture, { x: display.size.width / 4, y: display.size.height / 2 }); const rightHalfColor = getPixelColor(screenCapture, { x: display.size.width - (display.size.width / 4), y: display.size.height / 2 }); expect(areColorsSimilar(leftHalfColor, CHROMA_COLOR_HEX)).to.be.true(); expect(areColorsSimilar(rightHalfColor, '#ff0000')).to.be.true(); }); }); describe('"backgroundColor" option', () => { afterEach(closeAllWindows); // Linux/WOA doesn't return any capture sources. ifit(process.platform !== 'linux' && (process.platform !== 'win32' || process.arch !== 'arm64'))('should display the set color', async () => { const display = screen.getPrimaryDisplay(); const w = new BrowserWindow({ ...display.bounds, show: true, backgroundColor: CHROMA_COLOR_HEX }); w.loadURL('about:blank'); await emittedOnce(w, 'ready-to-show'); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); expect(areColorsSimilar(centerColor, CHROMA_COLOR_HEX)).to.be.true(); }); }); });
closed
electron/electron
https://github.com/electron/electron
34,152
[Bug]: Non-default window dispositions fail to load initial URL
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 18.2.1 ### What operating system are you using? - Windows - macOS ### Operating System Version - Windows 10 21H2 - macOS 12.3.1 ### What arch are you using? x64 ### Last Known Working Electron version 17.4.3 ### Expected Behavior `Shift+LeftClick` (new-window) or `Ctrl+Shift+LeftClick` (foreground-tab) on links should open and load them in a new window. ### Actual Behavior `Shift+LeftClick` or `Ctrl+Shift+LeftClick` on links opens a new window and never loads. ### Testcase Gist URL https://gist.github.com/samuelmaddock/d8e8c64c5143df9b3493592c75fa33b8 ### Additional Information Bug initially introduced in v18.0.0-alpha.1
https://github.com/electron/electron/issues/34152
https://github.com/electron/electron/pull/34159
6f8a36f4047ba6300f93d4470193d6b54afabacf
dd6ce91f5766c9eea0ffca23e42ef8766851e0a2
2022-05-09T21:13:02Z
c++
2022-05-11T18:34:33Z
spec-main/fixtures/apps/open-new-window-from-link/index.html
closed
electron/electron
https://github.com/electron/electron
34,152
[Bug]: Non-default window dispositions fail to load initial URL
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 18.2.1 ### What operating system are you using? - Windows - macOS ### Operating System Version - Windows 10 21H2 - macOS 12.3.1 ### What arch are you using? x64 ### Last Known Working Electron version 17.4.3 ### Expected Behavior `Shift+LeftClick` (new-window) or `Ctrl+Shift+LeftClick` (foreground-tab) on links should open and load them in a new window. ### Actual Behavior `Shift+LeftClick` or `Ctrl+Shift+LeftClick` on links opens a new window and never loads. ### Testcase Gist URL https://gist.github.com/samuelmaddock/d8e8c64c5143df9b3493592c75fa33b8 ### Additional Information Bug initially introduced in v18.0.0-alpha.1
https://github.com/electron/electron/issues/34152
https://github.com/electron/electron/pull/34159
6f8a36f4047ba6300f93d4470193d6b54afabacf
dd6ce91f5766c9eea0ffca23e42ef8766851e0a2
2022-05-09T21:13:02Z
c++
2022-05-11T18:34:33Z
spec-main/fixtures/apps/open-new-window-from-link/main.js
closed
electron/electron
https://github.com/electron/electron
34,152
[Bug]: Non-default window dispositions fail to load initial URL
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 18.2.1 ### What operating system are you using? - Windows - macOS ### Operating System Version - Windows 10 21H2 - macOS 12.3.1 ### What arch are you using? x64 ### Last Known Working Electron version 17.4.3 ### Expected Behavior `Shift+LeftClick` (new-window) or `Ctrl+Shift+LeftClick` (foreground-tab) on links should open and load them in a new window. ### Actual Behavior `Shift+LeftClick` or `Ctrl+Shift+LeftClick` on links opens a new window and never loads. ### Testcase Gist URL https://gist.github.com/samuelmaddock/d8e8c64c5143df9b3493592c75fa33b8 ### Additional Information Bug initially introduced in v18.0.0-alpha.1
https://github.com/electron/electron/issues/34152
https://github.com/electron/electron/pull/34159
6f8a36f4047ba6300f93d4470193d6b54afabacf
dd6ce91f5766c9eea0ffca23e42ef8766851e0a2
2022-05-09T21:13:02Z
c++
2022-05-11T18:34:33Z
spec-main/fixtures/apps/open-new-window-from-link/new-window-page.html
closed
electron/electron
https://github.com/electron/electron
34,152
[Bug]: Non-default window dispositions fail to load initial URL
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 18.2.1 ### What operating system are you using? - Windows - macOS ### Operating System Version - Windows 10 21H2 - macOS 12.3.1 ### What arch are you using? x64 ### Last Known Working Electron version 17.4.3 ### Expected Behavior `Shift+LeftClick` (new-window) or `Ctrl+Shift+LeftClick` (foreground-tab) on links should open and load them in a new window. ### Actual Behavior `Shift+LeftClick` or `Ctrl+Shift+LeftClick` on links opens a new window and never loads. ### Testcase Gist URL https://gist.github.com/samuelmaddock/d8e8c64c5143df9b3493592c75fa33b8 ### Additional Information Bug initially introduced in v18.0.0-alpha.1
https://github.com/electron/electron/issues/34152
https://github.com/electron/electron/pull/34159
6f8a36f4047ba6300f93d4470193d6b54afabacf
dd6ce91f5766c9eea0ffca23e42ef8766851e0a2
2022-05-09T21:13:02Z
c++
2022-05-11T18:34:33Z
spec-main/fixtures/apps/open-new-window-from-link/package.json
closed
electron/electron
https://github.com/electron/electron
34,152
[Bug]: Non-default window dispositions fail to load initial URL
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 18.2.1 ### What operating system are you using? - Windows - macOS ### Operating System Version - Windows 10 21H2 - macOS 12.3.1 ### What arch are you using? x64 ### Last Known Working Electron version 17.4.3 ### Expected Behavior `Shift+LeftClick` (new-window) or `Ctrl+Shift+LeftClick` (foreground-tab) on links should open and load them in a new window. ### Actual Behavior `Shift+LeftClick` or `Ctrl+Shift+LeftClick` on links opens a new window and never loads. ### Testcase Gist URL https://gist.github.com/samuelmaddock/d8e8c64c5143df9b3493592c75fa33b8 ### Additional Information Bug initially introduced in v18.0.0-alpha.1
https://github.com/electron/electron/issues/34152
https://github.com/electron/electron/pull/34159
6f8a36f4047ba6300f93d4470193d6b54afabacf
dd6ce91f5766c9eea0ffca23e42ef8766851e0a2
2022-05-09T21:13:02Z
c++
2022-05-11T18:34:33Z
spec-main/fixtures/apps/open-new-window-from-link/preload.js
closed
electron/electron
https://github.com/electron/electron
34,152
[Bug]: Non-default window dispositions fail to load initial URL
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 18.2.1 ### What operating system are you using? - Windows - macOS ### Operating System Version - Windows 10 21H2 - macOS 12.3.1 ### What arch are you using? x64 ### Last Known Working Electron version 17.4.3 ### Expected Behavior `Shift+LeftClick` (new-window) or `Ctrl+Shift+LeftClick` (foreground-tab) on links should open and load them in a new window. ### Actual Behavior `Shift+LeftClick` or `Ctrl+Shift+LeftClick` on links opens a new window and never loads. ### Testcase Gist URL https://gist.github.com/samuelmaddock/d8e8c64c5143df9b3493592c75fa33b8 ### Additional Information Bug initially introduced in v18.0.0-alpha.1
https://github.com/electron/electron/issues/34152
https://github.com/electron/electron/pull/34159
6f8a36f4047ba6300f93d4470193d6b54afabacf
dd6ce91f5766c9eea0ffca23e42ef8766851e0a2
2022-05-09T21:13:02Z
c++
2022-05-11T18:34:33Z
lib/browser/guest-window-manager.ts
/** * Create and minimally track guest windows at the direction of the renderer * (via window.open). Here, "guest" roughly means "child" — it's not necessarily * emblematic of its process status; both in-process (same-origin) and * out-of-process (cross-origin) are created here. "Embedder" roughly means * "parent." */ import { BrowserWindow } from 'electron/main'; import type { BrowserWindowConstructorOptions, Referrer, WebContents, LoadURLOptions } from 'electron/main'; import { parseFeatures } from '@electron/internal/browser/parse-features-string'; type PostData = LoadURLOptions['postData'] export type WindowOpenArgs = { url: string, frameName: string, features: string, } const frameNamesToWindow = new Map<string, BrowserWindow>(); const registerFrameNameToGuestWindow = (name: string, win: BrowserWindow) => frameNamesToWindow.set(name, win); const unregisterFrameName = (name: string) => frameNamesToWindow.delete(name); const getGuestWindowByFrameName = (name: string) => frameNamesToWindow.get(name); /** * `openGuestWindow` is called to create and setup event handling for the new * window. * * Until its removal in 12.0.0, the `new-window` event is fired, allowing the * user to preventDefault() on the passed event (which ends up calling * DestroyWebContents). */ export function openGuestWindow ({ event, embedder, guest, referrer, disposition, postData, overrideBrowserWindowOptions, windowOpenArgs, outlivesOpener }: { event: { sender: WebContents, defaultPrevented: boolean }, embedder: WebContents, guest?: WebContents, referrer: Referrer, disposition: string, postData?: PostData, overrideBrowserWindowOptions?: BrowserWindowConstructorOptions, windowOpenArgs: WindowOpenArgs, outlivesOpener: boolean, }): BrowserWindow | undefined { const { url, frameName, features } = windowOpenArgs; const { options: browserWindowOptions } = makeBrowserWindowOptions({ embedder, features, overrideOptions: overrideBrowserWindowOptions }); const didCancelEvent = emitDeprecatedNewWindowEvent({ event, embedder, guest, browserWindowOptions, windowOpenArgs, disposition, postData, referrer }); if (didCancelEvent) return; // To spec, subsequent window.open calls with the same frame name (`target` in // spec parlance) will reuse the previous window. // https://html.spec.whatwg.org/multipage/window-object.html#apis-for-creating-and-navigating-browsing-contexts-by-name const existingWindow = getGuestWindowByFrameName(frameName); if (existingWindow) { if (existingWindow.isDestroyed() || existingWindow.webContents.isDestroyed()) { // FIXME(t57ser): The webContents is destroyed for some reason, unregister the frame name unregisterFrameName(frameName); } else { existingWindow.loadURL(url); return existingWindow; } } const window = new BrowserWindow({ webContents: guest, ...browserWindowOptions }); handleWindowLifecycleEvents({ embedder, frameName, guest: window, outlivesOpener }); embedder.emit('did-create-window', window, { url, frameName, options: browserWindowOptions, disposition, referrer, postData }); return window; } /** * Manage the relationship between embedder window and guest window. When the * guest is destroyed, notify the embedder. When the embedder is destroyed, so * too is the guest destroyed; this is Electron convention and isn't based in * browser behavior. */ const handleWindowLifecycleEvents = function ({ embedder, guest, frameName, outlivesOpener }: { embedder: WebContents, guest: BrowserWindow, frameName: string, outlivesOpener: boolean }) { const closedByEmbedder = function () { guest.removeListener('closed', closedByUser); guest.destroy(); }; const closedByUser = function () { // Embedder might have been closed if (!embedder.isDestroyed() && !outlivesOpener) { embedder.removeListener('current-render-view-deleted' as any, closedByEmbedder); } }; if (!outlivesOpener) { embedder.once('current-render-view-deleted' as any, closedByEmbedder); } guest.once('closed', closedByUser); if (frameName) { registerFrameNameToGuestWindow(frameName, guest); guest.once('closed', function () { unregisterFrameName(frameName); }); } }; /** * Deprecated in favor of `webContents.setWindowOpenHandler` and * `did-create-window` in 11.0.0. Will be removed in 12.0.0. */ function emitDeprecatedNewWindowEvent ({ event, embedder, guest, windowOpenArgs, browserWindowOptions, disposition, referrer, postData }: { event: { sender: WebContents, defaultPrevented: boolean, newGuest?: BrowserWindow }, embedder: WebContents, guest?: WebContents, windowOpenArgs: WindowOpenArgs, browserWindowOptions: BrowserWindowConstructorOptions, disposition: string, referrer: Referrer, postData?: PostData, }): boolean { const { url, frameName } = windowOpenArgs; const isWebViewWithPopupsDisabled = embedder.getType() === 'webview' && embedder.getLastWebPreferences()!.disablePopups; const postBody = postData ? { data: postData, ...parseContentTypeFormat(postData) } : null; embedder.emit( 'new-window', event, url, frameName, disposition, { ...browserWindowOptions, webContents: guest }, [], // additionalFeatures referrer, postBody ); const { newGuest } = event; if (isWebViewWithPopupsDisabled) return true; if (event.defaultPrevented) { if (newGuest) { if (guest === newGuest.webContents) { // The webContents is not changed, so set defaultPrevented to false to // stop the callers of this event from destroying the webContents. event.defaultPrevented = false; } handleWindowLifecycleEvents({ embedder: event.sender, guest: newGuest, frameName, outlivesOpener: false }); } return true; } return false; } // Security options that child windows will always inherit from parent windows const securityWebPreferences: { [key: string]: boolean } = { contextIsolation: true, javascript: false, nodeIntegration: false, sandbox: true, webviewTag: false, nodeIntegrationInSubFrames: false, enableWebSQL: false }; function makeBrowserWindowOptions ({ embedder, features, overrideOptions }: { embedder: WebContents, features: string, overrideOptions?: BrowserWindowConstructorOptions, }) { const { options: parsedOptions, webPreferences: parsedWebPreferences } = parseFeatures(features); return { options: { show: true, width: 800, height: 600, ...parsedOptions, ...overrideOptions, // Note that for normal code path an existing WebContents created by // Chromium will be used, with web preferences parsed in the // |-will-add-new-contents| event. // The |webPreferences| here is only used by the |new-window| event. webPreferences: makeWebPreferences({ embedder, insecureParsedWebPreferences: parsedWebPreferences, secureOverrideWebPreferences: overrideOptions && overrideOptions.webPreferences }) } as Electron.BrowserViewConstructorOptions }; } export function makeWebPreferences ({ embedder, secureOverrideWebPreferences = {}, insecureParsedWebPreferences: parsedWebPreferences = {} }: { embedder: WebContents, insecureParsedWebPreferences?: ReturnType<typeof parseFeatures>['webPreferences'], // Note that override preferences are considered elevated, and should only be // sourced from the main process, as they override security defaults. If you // have unvetted prefs, use parsedWebPreferences. secureOverrideWebPreferences?: BrowserWindowConstructorOptions['webPreferences'], }) { const parentWebPreferences = embedder.getLastWebPreferences()!; const securityWebPreferencesFromParent = (Object.keys(securityWebPreferences).reduce((map, key) => { if (securityWebPreferences[key] === parentWebPreferences[key as keyof Electron.WebPreferences]) { (map as any)[key] = parentWebPreferences[key as keyof Electron.WebPreferences]; } return map; }, {} as Electron.WebPreferences)); return { ...parsedWebPreferences, // Note that order is key here, we want to disallow the renderer's // ability to change important security options but allow main (via // setWindowOpenHandler) to change them. ...securityWebPreferencesFromParent, ...secureOverrideWebPreferences }; } const MULTIPART_CONTENT_TYPE = 'multipart/form-data'; const URL_ENCODED_CONTENT_TYPE = 'application/x-www-form-urlencoded'; // Figure out appropriate headers for post data. export const parseContentTypeFormat = function (postData: Exclude<PostData, undefined>) { if (postData.length) { if (postData[0].type === 'rawData') { // For multipart forms, the first element will start with the boundary // notice, which looks something like `------WebKitFormBoundary12345678` // Note, this regex would fail when submitting a urlencoded form with an // input attribute of name="--theKey", but, uhh, don't do that? const postDataFront = postData[0].bytes.toString(); const boundary = /^--.*[^-\r\n]/.exec(postDataFront); if (boundary) { return { boundary: boundary[0].substr(2), contentType: MULTIPART_CONTENT_TYPE }; } } } // Either the form submission didn't contain any inputs (the postData array // was empty), or we couldn't find the boundary and thus we can assume this is // a key=value style form. return { contentType: URL_ENCODED_CONTENT_TYPE }; };
closed
electron/electron
https://github.com/electron/electron
34,152
[Bug]: Non-default window dispositions fail to load initial URL
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 18.2.1 ### What operating system are you using? - Windows - macOS ### Operating System Version - Windows 10 21H2 - macOS 12.3.1 ### What arch are you using? x64 ### Last Known Working Electron version 17.4.3 ### Expected Behavior `Shift+LeftClick` (new-window) or `Ctrl+Shift+LeftClick` (foreground-tab) on links should open and load them in a new window. ### Actual Behavior `Shift+LeftClick` or `Ctrl+Shift+LeftClick` on links opens a new window and never loads. ### Testcase Gist URL https://gist.github.com/samuelmaddock/d8e8c64c5143df9b3493592c75fa33b8 ### Additional Information Bug initially introduced in v18.0.0-alpha.1
https://github.com/electron/electron/issues/34152
https://github.com/electron/electron/pull/34159
6f8a36f4047ba6300f93d4470193d6b54afabacf
dd6ce91f5766c9eea0ffca23e42ef8766851e0a2
2022-05-09T21:13:02Z
c++
2022-05-11T18:34:33Z
spec-main/api-browser-window-spec.ts
import { expect } from 'chai'; import * as childProcess from 'child_process'; import * as path from 'path'; import * as fs from 'fs'; import * as os from 'os'; import * as qs from 'querystring'; import * as http from 'http'; import * as semver from 'semver'; import { AddressInfo } from 'net'; import { app, BrowserWindow, BrowserView, dialog, ipcMain, OnBeforeSendHeadersListenerDetails, protocol, screen, webContents, session, WebContents, BrowserWindowConstructorOptions } from 'electron/main'; import { emittedOnce, emittedUntil, emittedNTimes } from './events-helpers'; import { ifit, ifdescribe, defer, delay } from './spec-helpers'; import { closeWindow, closeAllWindows } from './window-helpers'; import { areColorsSimilar, captureScreen, CHROMA_COLOR_HEX, getPixelColor } from './screen-helpers'; const features = process._linkedBinding('electron_common_features'); const fixtures = path.resolve(__dirname, '..', 'spec', 'fixtures'); const mainFixtures = path.resolve(__dirname, 'fixtures'); // Is the display's scale factor possibly causing rounding of pixel coordinate // values? const isScaleFactorRounding = () => { const { scaleFactor } = screen.getPrimaryDisplay(); // Return true if scale factor is non-integer value if (Math.round(scaleFactor) !== scaleFactor) return true; // Return true if scale factor is odd number above 2 return scaleFactor > 2 && scaleFactor % 2 === 1; }; const expectBoundsEqual = (actual: any, expected: any) => { if (!isScaleFactorRounding()) { expect(expected).to.deep.equal(actual); } else if (Array.isArray(actual)) { expect(actual[0]).to.be.closeTo(expected[0], 1); expect(actual[1]).to.be.closeTo(expected[1], 1); } else { expect(actual.x).to.be.closeTo(expected.x, 1); expect(actual.y).to.be.closeTo(expected.y, 1); expect(actual.width).to.be.closeTo(expected.width, 1); expect(actual.height).to.be.closeTo(expected.height, 1); } }; const isBeforeUnload = (event: Event, level: number, message: string) => { return (message === 'beforeunload'); }; describe('BrowserWindow module', () => { describe('BrowserWindow constructor', () => { it('allows passing void 0 as the webContents', async () => { expect(() => { const w = new BrowserWindow({ show: false, // apparently void 0 had different behaviour from undefined in the // issue that this test is supposed to catch. webContents: void 0 // eslint-disable-line no-void } as any); w.destroy(); }).not.to.throw(); }); ifit(process.platform === 'linux')('does not crash when setting large window icons', async () => { const appPath = path.join(__dirname, 'spec-main', 'fixtures', 'apps', 'xwindow-icon'); const appProcess = childProcess.spawn(process.execPath, [appPath]); await new Promise((resolve) => { appProcess.once('exit', resolve); }); }); it('does not crash or throw when passed an invalid icon', async () => { expect(() => { const w = new BrowserWindow({ icon: undefined } as any); w.destroy(); }).not.to.throw(); }); }); describe('garbage collection', () => { const v8Util = process._linkedBinding('electron_common_v8_util'); afterEach(closeAllWindows); it('window does not get garbage collected when opened', async () => { const w = new BrowserWindow({ show: false }); // Keep a weak reference to the window. // eslint-disable-next-line no-undef const wr = new WeakRef(w); await delay(); // Do garbage collection, since |w| is not referenced in this closure // it would be gone after next call if there is no other reference. v8Util.requestGarbageCollectionForTesting(); await delay(); expect(wr.deref()).to.not.be.undefined(); }); }); describe('BrowserWindow.close()', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('should work if called when a messageBox is showing', async () => { const closed = emittedOnce(w, 'closed'); dialog.showMessageBox(w, { message: 'Hello Error' }); w.close(); await closed; }); it('closes window without rounded corners', async () => { await closeWindow(w); w = new BrowserWindow({ show: false, frame: false, roundedCorners: false }); const closed = emittedOnce(w, 'closed'); w.close(); await closed; }); it('should not crash if called after webContents is destroyed', () => { w.webContents.destroy(); w.webContents.on('destroyed', () => w.close()); }); it('should emit unload handler', async () => { await w.loadFile(path.join(fixtures, 'api', 'unload.html')); const closed = emittedOnce(w, 'closed'); w.close(); await closed; const test = path.join(fixtures, 'api', 'unload'); const content = fs.readFileSync(test); fs.unlinkSync(test); expect(String(content)).to.equal('unload'); }); it('should emit beforeunload handler', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); await emittedOnce(w.webContents, 'before-unload-fired'); }); it('should not crash when keyboard event is sent before closing', async () => { await w.loadURL('data:text/html,pls no crash'); const closed = emittedOnce(w, 'closed'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' }); w.close(); await closed; }); describe('when invoked synchronously inside navigation observer', () => { let server: http.Server = null as unknown as http.Server; let url: string = null as unknown as string; before((done) => { server = http.createServer((request, response) => { switch (request.url) { case '/net-error': response.destroy(); break; case '/301': response.statusCode = 301; response.setHeader('Location', '/200'); response.end(); break; case '/200': response.statusCode = 200; response.end('hello'); break; case '/title': response.statusCode = 200; response.end('<title>Hello</title>'); break; default: throw new Error(`unsupported endpoint: ${request.url}`); } }).listen(0, '127.0.0.1', () => { url = 'http://127.0.0.1:' + (server.address() as AddressInfo).port; done(); }); }); after(() => { server.close(); }); const events = [ { name: 'did-start-loading', path: '/200' }, { name: 'dom-ready', path: '/200' }, { name: 'page-title-updated', path: '/title' }, { name: 'did-stop-loading', path: '/200' }, { name: 'did-finish-load', path: '/200' }, { name: 'did-frame-finish-load', path: '/200' }, { name: 'did-fail-load', path: '/net-error' } ]; for (const { name, path } of events) { it(`should not crash when closed during ${name}`, async () => { const w = new BrowserWindow({ show: false }); w.webContents.once((name as any), () => { w.close(); }); const destroyed = emittedOnce(w.webContents, 'destroyed'); w.webContents.loadURL(url + path); await destroyed; }); } }); }); describe('window.close()', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('should emit unload event', async () => { w.loadFile(path.join(fixtures, 'api', 'close.html')); await emittedOnce(w, 'closed'); const test = path.join(fixtures, 'api', 'close'); const content = fs.readFileSync(test).toString(); fs.unlinkSync(test); expect(content).to.equal('close'); }); it('should emit beforeunload event', async function () { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.webContents.executeJavaScript('window.close()', true); await emittedOnce(w.webContents, 'before-unload-fired'); }); }); describe('BrowserWindow.destroy()', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('prevents users to access methods of webContents', async () => { const contents = w.webContents; w.destroy(); await new Promise(setImmediate); expect(() => { contents.getProcessId(); }).to.throw('Object has been destroyed'); }); it('should not crash when destroying windows with pending events', () => { const focusListener = () => { }; app.on('browser-window-focus', focusListener); const windowCount = 3; const windowOptions = { show: false, width: 400, height: 400, webPreferences: { backgroundThrottling: false } }; const windows = Array.from(Array(windowCount)).map(() => new BrowserWindow(windowOptions)); windows.forEach(win => win.show()); windows.forEach(win => win.focus()); windows.forEach(win => win.destroy()); app.removeListener('browser-window-focus', focusListener); }); }); describe('BrowserWindow.loadURL(url)', () => { let w = null as unknown as BrowserWindow; const scheme = 'other'; const srcPath = path.join(fixtures, 'api', 'loaded-from-dataurl.js'); before(() => { protocol.registerFileProtocol(scheme, (request, callback) => { callback(srcPath); }); }); after(() => { protocol.unregisterProtocol(scheme); }); beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); let server = null as unknown as http.Server; let url = null as unknown as string; let postData = null as any; before((done) => { const filePath = path.join(fixtures, 'pages', 'a.html'); const fileStats = fs.statSync(filePath); postData = [ { type: 'rawData', bytes: Buffer.from('username=test&file=') }, { type: 'file', filePath: filePath, offset: 0, length: fileStats.size, modificationTime: fileStats.mtime.getTime() / 1000 } ]; server = http.createServer((req, res) => { function respond () { if (req.method === 'POST') { let body = ''; req.on('data', (data) => { if (data) body += data; }); req.on('end', () => { const parsedData = qs.parse(body); fs.readFile(filePath, (err, data) => { if (err) return; if (parsedData.username === 'test' && parsedData.file === data.toString()) { res.end(); } }); }); } else if (req.url === '/302') { res.setHeader('Location', '/200'); res.statusCode = 302; res.end(); } else { res.end(); } } setTimeout(respond, req.url && req.url.includes('slow') ? 200 : 0); }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; done(); }); }); after(() => { server.close(); }); it('should emit did-start-loading event', async () => { const didStartLoading = emittedOnce(w.webContents, 'did-start-loading'); w.loadURL('about:blank'); await didStartLoading; }); it('should emit ready-to-show event', async () => { const readyToShow = emittedOnce(w, 'ready-to-show'); w.loadURL('about:blank'); await readyToShow; }); // TODO(deepak1556): The error code now seems to be `ERR_FAILED`, verify what // changed and adjust the test. it.skip('should emit did-fail-load event for files that do not exist', async () => { const didFailLoad = emittedOnce(w.webContents, 'did-fail-load'); w.loadURL('file://a.txt'); const [, code, desc,, isMainFrame] = await didFailLoad; expect(code).to.equal(-6); expect(desc).to.equal('ERR_FILE_NOT_FOUND'); expect(isMainFrame).to.equal(true); }); it('should emit did-fail-load event for invalid URL', async () => { const didFailLoad = emittedOnce(w.webContents, 'did-fail-load'); w.loadURL('http://example:port'); const [, code, desc,, isMainFrame] = await didFailLoad; expect(desc).to.equal('ERR_INVALID_URL'); expect(code).to.equal(-300); expect(isMainFrame).to.equal(true); }); it('should set `mainFrame = false` on did-fail-load events in iframes', async () => { const didFailLoad = emittedOnce(w.webContents, 'did-fail-load'); w.loadFile(path.join(fixtures, 'api', 'did-fail-load-iframe.html')); const [,,,, isMainFrame] = await didFailLoad; expect(isMainFrame).to.equal(false); }); it('does not crash in did-fail-provisional-load handler', (done) => { w.webContents.once('did-fail-provisional-load', () => { w.loadURL('http://127.0.0.1:11111'); done(); }); w.loadURL('http://127.0.0.1:11111'); }); it('should emit did-fail-load event for URL exceeding character limit', async () => { const data = Buffer.alloc(2 * 1024 * 1024).toString('base64'); const didFailLoad = emittedOnce(w.webContents, 'did-fail-load'); w.loadURL(`data:image/png;base64,${data}`); const [, code, desc,, isMainFrame] = await didFailLoad; expect(desc).to.equal('ERR_INVALID_URL'); expect(code).to.equal(-300); expect(isMainFrame).to.equal(true); }); it('should return a promise', () => { const p = w.loadURL('about:blank'); expect(p).to.have.property('then'); }); it('should return a promise that resolves', async () => { await expect(w.loadURL('about:blank')).to.eventually.be.fulfilled(); }); it('should return a promise that rejects on a load failure', async () => { const data = Buffer.alloc(2 * 1024 * 1024).toString('base64'); const p = w.loadURL(`data:image/png;base64,${data}`); await expect(p).to.eventually.be.rejected; }); it('should return a promise that resolves even if pushState occurs during navigation', async () => { const p = w.loadURL('data:text/html,<script>window.history.pushState({}, "/foo")</script>'); await expect(p).to.eventually.be.fulfilled; }); describe('POST navigations', () => { afterEach(() => { w.webContents.session.webRequest.onBeforeSendHeaders(null); }); it('supports specifying POST data', async () => { await w.loadURL(url, { postData }); }); it('sets the content type header on URL encoded forms', async () => { await w.loadURL(url); const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => { w.webContents.session.webRequest.onBeforeSendHeaders((details) => { resolve(details); }); }); w.webContents.executeJavaScript(` form = document.createElement('form') document.body.appendChild(form) form.method = 'POST' form.submit() `); const details = await requestDetails; expect(details.requestHeaders['Content-Type']).to.equal('application/x-www-form-urlencoded'); }); it('sets the content type header on multi part forms', async () => { await w.loadURL(url); const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => { w.webContents.session.webRequest.onBeforeSendHeaders((details) => { resolve(details); }); }); w.webContents.executeJavaScript(` form = document.createElement('form') document.body.appendChild(form) form.method = 'POST' form.enctype = 'multipart/form-data' file = document.createElement('input') file.type = 'file' file.name = 'file' form.appendChild(file) form.submit() `); const details = await requestDetails; expect(details.requestHeaders['Content-Type'].startsWith('multipart/form-data; boundary=----WebKitFormBoundary')).to.equal(true); }); }); it('should support base url for data urls', async () => { await w.loadURL('data:text/html,<script src="loaded-from-dataurl.js"></script>', { baseURLForDataURL: `other://${path.join(fixtures, 'api')}${path.sep}` }); expect(await w.webContents.executeJavaScript('window.ping')).to.equal('pong'); }); }); for (const sandbox of [false, true]) { describe(`navigation events${sandbox ? ' with sandbox' : ''}`, () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: false, sandbox } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('will-navigate event', () => { let server = null as unknown as http.Server; let url = null as unknown as string; before((done) => { server = http.createServer((req, res) => { if (req.url === '/navigate-top') { res.end('<a target=_top href="/">navigate _top</a>'); } else { res.end(''); } }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/`; done(); }); }); after(() => { server.close(); }); it('allows the window to be closed from the event listener', (done) => { w.webContents.once('will-navigate', () => { w.close(); done(); }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('can be prevented', (done) => { let willNavigate = false; w.webContents.once('will-navigate', (e) => { willNavigate = true; e.preventDefault(); }); w.webContents.on('did-stop-loading', () => { if (willNavigate) { // i.e. it shouldn't have had '?navigated' appended to it. try { expect(w.webContents.getURL().endsWith('will-navigate.html')).to.be.true(); done(); } catch (e) { done(e); } } }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('is triggered when navigating from file: to http:', async () => { await w.loadFile(path.join(fixtures, 'api', 'blank.html')); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-navigate', (e, url) => { e.preventDefault(); resolve(url); }); }); expect(navigatedTo).to.equal(url); expect(w.webContents.getURL()).to.match(/^file:/); }); it('is triggered when navigating from about:blank to http:', async () => { await w.loadURL('about:blank'); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-navigate', (e, url) => { e.preventDefault(); resolve(url); }); }); expect(navigatedTo).to.equal(url); expect(w.webContents.getURL()).to.equal('about:blank'); }); it('is triggered when a cross-origin iframe navigates _top', async () => { await w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-top"></iframe>`); await delay(1000); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const iframeTarget = targets.targetInfos.find((t: any) => t.type === 'iframe'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: iframeTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); let willNavigateEmitted = false; w.webContents.on('will-navigate', () => { willNavigateEmitted = true; }); await emittedOnce(w.webContents, 'did-navigate'); expect(willNavigateEmitted).to.be.true(); }); }); describe('will-redirect event', () => { let server = null as unknown as http.Server; let url = null as unknown as string; before((done) => { server = http.createServer((req, res) => { if (req.url === '/302') { res.setHeader('Location', '/200'); res.statusCode = 302; res.end(); } else if (req.url === '/navigate-302') { res.end(`<html><body><script>window.location='${url}/302'</script></body></html>`); } else { res.end(); } }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; done(); }); }); after(() => { server.close(); }); it('is emitted on redirects', async () => { const willRedirect = emittedOnce(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await willRedirect; }); it('is emitted after will-navigate on redirects', async () => { let navigateCalled = false; w.webContents.on('will-navigate', () => { navigateCalled = true; }); const willRedirect = emittedOnce(w.webContents, 'will-redirect'); w.loadURL(`${url}/navigate-302`); await willRedirect; expect(navigateCalled).to.equal(true, 'should have called will-navigate first'); }); it('is emitted before did-stop-loading on redirects', async () => { let stopCalled = false; w.webContents.on('did-stop-loading', () => { stopCalled = true; }); const willRedirect = emittedOnce(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await willRedirect; expect(stopCalled).to.equal(false, 'should not have called did-stop-loading first'); }); it('allows the window to be closed from the event listener', (done) => { w.webContents.once('will-redirect', () => { w.close(); done(); }); w.loadURL(`${url}/302`); }); it('can be prevented', (done) => { w.webContents.once('will-redirect', (event) => { event.preventDefault(); }); w.webContents.on('will-navigate', (e, u) => { expect(u).to.equal(`${url}/302`); }); w.webContents.on('did-stop-loading', () => { try { expect(w.webContents.getURL()).to.equal( `${url}/navigate-302`, 'url should not have changed after navigation event' ); done(); } catch (e) { done(e); } }); w.webContents.on('will-redirect', (e, u) => { try { expect(u).to.equal(`${url}/200`); } catch (e) { done(e); } }); w.loadURL(`${url}/navigate-302`); }); }); }); } describe('focus and visibility', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.show()', () => { it('should focus on window', async () => { await emittedOnce(w, 'focus', () => w.show()); expect(w.isFocused()).to.equal(true); }); it('should make the window visible', async () => { await emittedOnce(w, 'focus', () => w.show()); expect(w.isVisible()).to.equal(true); }); it('emits when window is shown', async () => { const show = emittedOnce(w, 'show'); w.show(); await show; expect(w.isVisible()).to.equal(true); }); }); describe('BrowserWindow.hide()', () => { it('should defocus on window', () => { w.hide(); expect(w.isFocused()).to.equal(false); }); it('should make the window not visible', () => { w.show(); w.hide(); expect(w.isVisible()).to.equal(false); }); it('emits when window is hidden', async () => { const shown = emittedOnce(w, 'show'); w.show(); await shown; const hidden = emittedOnce(w, 'hide'); w.hide(); await hidden; expect(w.isVisible()).to.equal(false); }); }); describe('BrowserWindow.showInactive()', () => { it('should not focus on window', () => { w.showInactive(); expect(w.isFocused()).to.equal(false); }); // TODO(dsanders11): Enable for Linux once CI plays nice with these kinds of tests ifit(process.platform !== 'linux')('should not restore maximized windows', async () => { const maximize = emittedOnce(w, 'maximize'); const shown = emittedOnce(w, 'show'); w.maximize(); // TODO(dsanders11): The maximize event isn't firing on macOS for a window initially hidden if (process.platform !== 'darwin') { await maximize; } else { await delay(1000); } w.showInactive(); await shown; expect(w.isMaximized()).to.equal(true); }); }); describe('BrowserWindow.focus()', () => { it('does not make the window become visible', () => { expect(w.isVisible()).to.equal(false); w.focus(); expect(w.isVisible()).to.equal(false); }); ifit(process.platform !== 'win32')('focuses a blurred window', async () => { { const isBlurred = emittedOnce(w, 'blur'); const isShown = emittedOnce(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 = emittedOnce(w3, 'focus'); const isShown1 = emittedOnce(w1, 'show'); const isShown2 = emittedOnce(w2, 'show'); const isShown3 = emittedOnce(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 = emittedOnce(w1, 'closed'); const isClosed2 = emittedOnce(w2, 'closed'); const isClosed3 = emittedOnce(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 = emittedOnce(w, 'focus'); const isShown = emittedOnce(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 = emittedOnce(w3, 'focus'); const isShown1 = emittedOnce(w1, 'show'); const isShown2 = emittedOnce(w2, 'show'); const isShown3 = emittedOnce(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 = emittedOnce(w1, 'closed'); const isClosed2 = emittedOnce(w2, 'closed'); const isClosed3 = emittedOnce(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 () => { await emittedOnce(w, 'focus', () => w.show()); w.webContents.openDevTools({ mode: 'undocked' }); await emittedOnce(w.webContents, 'devtools-focused'); expect(BrowserWindow.getFocusedWindow()).to.equal(w); }); }); describe('BrowserWindow.moveTop()', () => { it('should not steal focus', async () => { const posDelta = 50; const wShownInactive = emittedOnce(w, 'show'); w.showInactive(); await wShownInactive; expect(w.isFocused()).to.equal(false); const otherWindow = new BrowserWindow({ show: false, title: 'otherWindow' }); const otherWindowShown = emittedOnce(otherWindow, 'show'); const otherWindowFocused = emittedOnce(otherWindow, 'focus'); otherWindow.show(); await otherWindowShown; await otherWindowFocused; expect(otherWindow.isFocused()).to.equal(true); w.moveTop(); const wPos = w.getPosition(); const wMoving = emittedOnce(w, 'move'); w.setPosition(wPos[0] + posDelta, wPos[1] + posDelta); await wMoving; expect(w.isFocused()).to.equal(false); expect(otherWindow.isFocused()).to.equal(true); const wFocused = emittedOnce(w, 'focus'); const otherWindowBlurred = emittedOnce(otherWindow, 'blur'); w.focus(); await wFocused; await otherWindowBlurred; expect(w.isFocused()).to.equal(true); otherWindow.moveTop(); const otherWindowPos = otherWindow.getPosition(); const otherWindowMoving = emittedOnce(otherWindow, 'move'); otherWindow.setPosition(otherWindowPos[0] + posDelta, otherWindowPos[1] + posDelta); await otherWindowMoving; expect(otherWindow.isFocused()).to.equal(false); expect(w.isFocused()).to.equal(true); await closeWindow(otherWindow, { assertNotWindows: false }); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1); }); }); ifdescribe(features.isDesktopCapturerEnabled())('BrowserWindow.moveAbove(mediaSourceId)', () => { it('should throw an exception if wrong formatting', async () => { const fakeSourceIds = [ 'none', 'screen:0', 'window:fake', 'window:1234', 'foobar:1:2' ]; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Invalid media source id/); }); }); it('should throw an exception if wrong type', async () => { const fakeSourceIds = [null as any, 123 as any]; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Error processing argument at index 0 */); }); }); it('should throw an exception if invalid window', async () => { // It is very unlikely that these window id exist. const fakeSourceIds = ['window:99999999:0', 'window:123456:1', 'window:123456:9']; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Invalid media source id/); }); }); it('should not throw an exception', async () => { const w2 = new BrowserWindow({ show: false, title: 'window2' }); const w2Shown = emittedOnce(w2, 'show'); w2.show(); await w2Shown; expect(() => { w.moveAbove(w2.getMediaSourceId()); }).to.not.throw(); await closeWindow(w2, { assertNotWindows: false }); }); }); describe('BrowserWindow.setFocusable()', () => { it('can set unfocusable window to focusable', async () => { const w2 = new BrowserWindow({ focusable: false }); const w2Focused = emittedOnce(w2, 'focus'); w2.setFocusable(true); w2.focus(); await w2Focused; await closeWindow(w2, { assertNotWindows: false }); }); }); describe('BrowserWindow.isFocusable()', () => { it('correctly returns whether a window is focusable', async () => { const w2 = new BrowserWindow({ focusable: false }); expect(w2.isFocusable()).to.be.false(); w2.setFocusable(true); expect(w2.isFocusable()).to.be.true(); await closeWindow(w2, { assertNotWindows: false }); }); }); }); describe('sizing', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, width: 400, height: 400 }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.setBounds(bounds[, animate])', () => { it('sets the window bounds with full bounds', () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds); expectBoundsEqual(w.getBounds(), fullBounds); }); it('sets the window bounds with partial bounds', () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds); const boundsUpdate = { width: 200 }; w.setBounds(boundsUpdate as any); const expectedBounds = Object.assign(fullBounds, boundsUpdate); expectBoundsEqual(w.getBounds(), expectedBounds); }); ifit(process.platform === 'darwin')('on macOS', () => { it('emits \'resized\' event after animating', async () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds, true); await expect(emittedOnce(w, 'resized')).to.eventually.be.fulfilled(); }); }); }); describe('BrowserWindow.setSize(width, height)', () => { it('sets the window size', async () => { const size = [300, 400]; const resized = emittedOnce(w, 'resize'); w.setSize(size[0], size[1]); await resized; expectBoundsEqual(w.getSize(), size); }); ifit(process.platform === 'darwin')('on macOS', () => { it('emits \'resized\' event after animating', async () => { const size = [300, 400]; w.setSize(size[0], size[1], true); await expect(emittedOnce(w, 'resized')).to.eventually.be.fulfilled(); }); }); }); describe('BrowserWindow.setMinimum/MaximumSize(width, height)', () => { it('sets the maximum and minimum size of the window', () => { expect(w.getMinimumSize()).to.deep.equal([0, 0]); expect(w.getMaximumSize()).to.deep.equal([0, 0]); w.setMinimumSize(100, 100); expectBoundsEqual(w.getMinimumSize(), [100, 100]); expectBoundsEqual(w.getMaximumSize(), [0, 0]); w.setMaximumSize(900, 600); expectBoundsEqual(w.getMinimumSize(), [100, 100]); expectBoundsEqual(w.getMaximumSize(), [900, 600]); }); }); describe('BrowserWindow.setAspectRatio(ratio)', () => { it('resets the behaviour when passing in 0', async () => { const size = [300, 400]; w.setAspectRatio(1 / 2); w.setAspectRatio(0); const resize = emittedOnce(w, 'resize'); w.setSize(size[0], size[1]); await resize; expectBoundsEqual(w.getSize(), size); }); it('doesn\'t change bounds when maximum size is set', () => { w.setMenu(null); w.setMaximumSize(400, 400); // Without https://github.com/electron/electron/pull/29101 // following call would shrink the window to 384x361. // There would be also DCHECK in resize_utils.cc on // debug build. w.setAspectRatio(1.0); expectBoundsEqual(w.getSize(), [400, 400]); }); }); describe('BrowserWindow.setPosition(x, y)', () => { it('sets the window position', async () => { const pos = [10, 10]; const move = emittedOnce(w, 'move'); w.setPosition(pos[0], pos[1]); await move; expect(w.getPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setContentSize(width, height)', () => { it('sets the content size', async () => { // NB. The CI server has a very small screen. Attempting to size the window // larger than the screen will limit the window's size to the screen and // cause the test to fail. const size = [456, 567]; w.setContentSize(size[0], size[1]); await new Promise(setImmediate); const after = w.getContentSize(); expect(after).to.deep.equal(size); }); it('works for a frameless window', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 400, height: 400 }); const size = [456, 567]; w.setContentSize(size[0], size[1]); await new Promise(setImmediate); const after = w.getContentSize(); expect(after).to.deep.equal(size); }); }); describe('BrowserWindow.setContentBounds(bounds)', () => { it('sets the content size and position', async () => { const bounds = { x: 10, y: 10, width: 250, height: 250 }; const resize = emittedOnce(w, 'resize'); w.setContentBounds(bounds); await resize; await delay(); expectBoundsEqual(w.getContentBounds(), bounds); }); it('works for a frameless window', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300 }); const bounds = { x: 10, y: 10, width: 250, height: 250 }; const resize = emittedOnce(w, 'resize'); w.setContentBounds(bounds); await resize; await delay(); expectBoundsEqual(w.getContentBounds(), bounds); }); }); describe('BrowserWindow.getBackgroundColor()', () => { it('returns default value if no backgroundColor is set', () => { w.destroy(); w = new BrowserWindow({}); expect(w.getBackgroundColor()).to.equal('#FFFFFF'); }); it('returns correct value if backgroundColor is set', () => { const backgroundColor = '#BBAAFF'; w.destroy(); w = new BrowserWindow({ backgroundColor: backgroundColor }); expect(w.getBackgroundColor()).to.equal(backgroundColor); }); it('returns correct value from setBackgroundColor()', () => { const backgroundColor = '#AABBFF'; w.destroy(); w = new BrowserWindow({}); w.setBackgroundColor(backgroundColor); expect(w.getBackgroundColor()).to.equal(backgroundColor); }); 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 = emittedOnce(w, 'resize'); w.setSize(size[0], size[1]); await resize; expectBoundsEqual(w.getNormalBounds(), w.getBounds()); }); it('checks normal bounds after move', async () => { const pos = [10, 10]; const move = emittedOnce(w, 'move'); w.setPosition(pos[0], pos[1]); await move; expectBoundsEqual(w.getNormalBounds(), w.getBounds()); }); }); ifdescribe(process.platform !== 'linux')('Maximized state', () => { it('checks normal bounds when maximized', async () => { const bounds = w.getBounds(); const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('checks normal bounds when unmaximized', async () => { const bounds = w.getBounds(); w.once('maximize', () => { w.unmaximize(); }); const unmaximize = emittedOnce(w, 'unmaximize'); w.show(); w.maximize(); await unmaximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('does not change size for a frameless window with min size', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300, minWidth: 300, minHeight: 300 }); const bounds = w.getBounds(); w.once('maximize', () => { w.unmaximize(); }); const unmaximize = emittedOnce(w, 'unmaximize'); w.show(); w.maximize(); await unmaximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('correctly checks transparent window maximization state', async () => { w.destroy(); w = new BrowserWindow({ show: false, width: 300, height: 300, transparent: true }); const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; expect(w.isMaximized()).to.equal(true); const unmaximize = emittedOnce(w, 'unmaximize'); w.unmaximize(); await unmaximize; expect(w.isMaximized()).to.equal(false); }); it('returns the correct value for windows with an aspect ratio', async () => { w.destroy(); w = new BrowserWindow({ show: false, fullscreenable: false }); w.setAspectRatio(16 / 11); const maximize = emittedOnce(w, 'resize'); w.show(); w.maximize(); await maximize; expect(w.isMaximized()).to.equal(true); w.resizable = false; expect(w.isMaximized()).to.equal(true); }); }); ifdescribe(process.platform !== 'linux')('Minimized state', () => { it('checks normal bounds when minimized', async () => { const bounds = w.getBounds(); const minimize = emittedOnce(w, 'minimize'); w.show(); w.minimize(); await minimize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('checks normal bounds when restored', async () => { const bounds = w.getBounds(); w.once('minimize', () => { w.restore(); }); const restore = emittedOnce(w, 'restore'); w.show(); w.minimize(); await restore; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('does not change size for a frameless window with min size', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300, minWidth: 300, minHeight: 300 }); const bounds = w.getBounds(); w.once('minimize', () => { w.restore(); }); const restore = emittedOnce(w, 'restore'); w.show(); w.minimize(); await restore; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); ifdescribe(process.platform === 'win32')('Fullscreen state', () => { it('with properties', () => { it('can be set with the fullscreen constructor option', () => { w = new BrowserWindow({ fullscreen: true }); expect(w.fullScreen).to.be.true(); }); it('can be changed', () => { w.fullScreen = false; expect(w.fullScreen).to.be.false(); w.fullScreen = true; expect(w.fullScreen).to.be.true(); }); it('checks normal bounds when fullscreen\'ed', async () => { const bounds = w.getBounds(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.show(); w.fullScreen = true; await enterFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('checks normal bounds when unfullscreen\'ed', async () => { const bounds = w.getBounds(); w.once('enter-full-screen', () => { w.fullScreen = false; }); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.show(); w.fullScreen = true; await leaveFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); it('with functions', () => { it('can be set with the fullscreen constructor option', () => { w = new BrowserWindow({ fullscreen: true }); expect(w.isFullScreen()).to.be.true(); }); it('can be changed', () => { w.setFullScreen(false); expect(w.isFullScreen()).to.be.false(); w.setFullScreen(true); expect(w.isFullScreen()).to.be.true(); }); it('checks normal bounds when fullscreen\'ed', async () => { const bounds = w.getBounds(); w.show(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('checks normal bounds when unfullscreen\'ed', async () => { const bounds = w.getBounds(); w.show(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); }); }); }); ifdescribe(process.platform === 'darwin')('tabbed windows', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.selectPreviousTab()', () => { it('does not throw', () => { expect(() => { w.selectPreviousTab(); }).to.not.throw(); }); }); describe('BrowserWindow.selectNextTab()', () => { it('does not throw', () => { expect(() => { w.selectNextTab(); }).to.not.throw(); }); }); describe('BrowserWindow.mergeAllWindows()', () => { it('does not throw', () => { expect(() => { w.mergeAllWindows(); }).to.not.throw(); }); }); describe('BrowserWindow.moveTabToNewWindow()', () => { it('does not throw', () => { expect(() => { w.moveTabToNewWindow(); }).to.not.throw(); }); }); describe('BrowserWindow.toggleTabBar()', () => { it('does not throw', () => { expect(() => { w.toggleTabBar(); }).to.not.throw(); }); }); describe('BrowserWindow.addTabbedWindow()', () => { it('does not throw', async () => { const tabbedWindow = new BrowserWindow({}); expect(() => { w.addTabbedWindow(tabbedWindow); }).to.not.throw(); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(2); // w + tabbedWindow await closeWindow(tabbedWindow, { assertNotWindows: false }); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1); // w }); it('throws when called on itself', () => { expect(() => { w.addTabbedWindow(w); }).to.throw('AddTabbedWindow cannot be called by a window on itself.'); }); }); }); describe('autoHideMenuBar state', () => { afterEach(closeAllWindows); it('for properties', () => { it('can be set with autoHideMenuBar constructor option', () => { const w = new BrowserWindow({ show: false, autoHideMenuBar: true }); expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); w.autoHideMenuBar = true; expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); w.autoHideMenuBar = false; expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); }); }); it('for functions', () => { it('can be set with autoHideMenuBar constructor option', () => { const w = new BrowserWindow({ show: false, autoHideMenuBar: true }); expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar'); w.setAutoHideMenuBar(true); expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar'); w.setAutoHideMenuBar(false); expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar'); }); }); }); describe('BrowserWindow.capturePage(rect)', () => { afterEach(closeAllWindows); it('returns a Promise with a Buffer', async () => { const w = new BrowserWindow({ show: false }); const image = await w.capturePage({ x: 0, y: 0, width: 100, height: 100 }); expect(image.isEmpty()).to.equal(true); }); it('resolves after the window is hidden', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixtures, 'pages', 'a.html')); await emittedOnce(w, 'ready-to-show'); w.show(); const visibleImage = await w.capturePage(); expect(visibleImage.isEmpty()).to.equal(false); w.hide(); const hiddenImage = await w.capturePage(); const isEmpty = process.platform !== 'darwin'; expect(hiddenImage.isEmpty()).to.equal(isEmpty); }); it('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 emittedOnce(w, 'ready-to-show'); w.webContents.incrementCapturerCount(); 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 emittedOnce(w, 'ready-to-show'); w.show(); const image = await w.capturePage(); const imgBuffer = image.toPNG(); // Check the 25th byte in the PNG. // Values can be 0,2,3,4, or 6. We want 6, which is RGB + Alpha expect(imgBuffer[25]).to.equal(6); }); it('should increase the capturer count', () => { const w = new BrowserWindow({ show: false }); w.webContents.incrementCapturerCount(); expect(w.webContents.isBeingCaptured()).to.be.true(); w.webContents.decrementCapturerCount(); expect(w.webContents.isBeingCaptured()).to.be.false(); }); }); describe('BrowserWindow.setProgressBar(progress)', () => { let w = null as unknown as BrowserWindow; before(() => { w = new BrowserWindow({ show: false }); }); after(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('sets the progress', () => { expect(() => { if (process.platform === 'darwin') { app.dock.setIcon(path.join(fixtures, 'assets', 'logo.png')); } w.setProgressBar(0.5); if (process.platform === 'darwin') { app.dock.setIcon(null as any); } w.setProgressBar(-1); }).to.not.throw(); }); it('sets the progress using "paused" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'paused' }); }).to.not.throw(); }); it('sets the progress using "error" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'error' }); }).to.not.throw(); }); it('sets the progress using "normal" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'normal' }); }).to.not.throw(); }); }); describe('BrowserWindow.setAlwaysOnTop(flag, level)', () => { let w = null as unknown as BrowserWindow; afterEach(closeAllWindows); beforeEach(() => { w = new BrowserWindow({ show: true }); }); it('sets the window as always on top', () => { expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); w.setAlwaysOnTop(false); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); }); ifit(process.platform === 'darwin')('resets the windows level on minimize', () => { expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); w.minimize(); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.restore(); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); }); it('causes the right value to be emitted on `always-on-top-changed`', async () => { const alwaysOnTopChanged = emittedOnce(w, 'always-on-top-changed'); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true); const [, alwaysOnTop] = await alwaysOnTopChanged; expect(alwaysOnTop).to.be.true('is not alwaysOnTop'); }); ifit(process.platform === 'darwin')('honors the alwaysOnTop level of a child window', () => { w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ parent: w }); c.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.false(); expect(c.isAlwaysOnTop()).to.be.true('child is not always on top'); expect((c as any)._getAlwaysOnTopLevel()).to.equal('screen-saver'); }); }); describe('preconnect feature', () => { let w = null as unknown as BrowserWindow; let server = null as unknown as http.Server; let url = null as unknown as string; let connections = 0; beforeEach(async () => { connections = 0; server = http.createServer((req, res) => { if (req.url === '/link') { res.setHeader('Content-type', 'text/html'); res.end('<head><link rel="preconnect" href="//example.com" /></head><body>foo</body>'); return; } res.end(); }); server.on('connection', () => { connections++; }); await new Promise<void>(resolve => server.listen(0, '127.0.0.1', () => resolve())); url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; }); afterEach(async () => { server.close(); await closeWindow(w); w = null as unknown as BrowserWindow; server = null as unknown as http.Server; }); it('calling preconnect() connects to the server', async () => { w = new BrowserWindow({ show: false }); w.webContents.on('did-start-navigation', (event, url) => { w.webContents.session.preconnect({ url, numSockets: 4 }); }); await w.loadURL(url); expect(connections).to.equal(4); }); it('does not preconnect unless requested', async () => { w = new BrowserWindow({ show: false }); await w.loadURL(url); expect(connections).to.equal(1); }); it('parses <link rel=preconnect>', async () => { w = new BrowserWindow({ show: true }); const p = emittedOnce(w.webContents.session, 'preconnect'); w.loadURL(url + '/link'); const [, preconnectUrl, allowCredentials] = await p; expect(preconnectUrl).to.equal('http://example.com/'); expect(allowCredentials).to.be.true('allowCredentials'); }); }); describe('BrowserWindow.setAutoHideCursor(autoHide)', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); ifit(process.platform === 'darwin')('on macOS', () => { it('allows changing cursor auto-hiding', () => { expect(() => { w.setAutoHideCursor(false); w.setAutoHideCursor(true); }).to.not.throw(); }); }); ifit(process.platform !== 'darwin')('on non-macOS platforms', () => { it('is not available', () => { expect(w.setAutoHideCursor).to.be.undefined('setAutoHideCursor function'); }); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setWindowButtonVisibility()', () => { afterEach(closeAllWindows); it('does not throw', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setWindowButtonVisibility(true); w.setWindowButtonVisibility(false); }).to.not.throw(); }); it('changes window button visibility for normal window', () => { const w = new BrowserWindow({ show: false }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); it('changes window button visibility for frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); }); it('changes window button visibility for hiddenInset window', () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hiddenInset' }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); // Buttons of customButtonsOnHover are always hidden unless hovered. it('does not change window button visibility for customButtonsOnHover window', () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'customButtonsOnHover' }); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setVibrancy(type)', () => { let appProcess: childProcess.ChildProcessWithoutNullStreams | undefined; afterEach(() => { if (appProcess && !appProcess.killed) { appProcess.kill(); appProcess = undefined; } closeAllWindows(); }); it('allows setting, changing, and removing the vibrancy', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setVibrancy('light'); w.setVibrancy('dark'); w.setVibrancy(null); w.setVibrancy('ultra-dark'); w.setVibrancy('' as any); }).to.not.throw(); }); it('does not crash if vibrancy is set to an invalid value', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setVibrancy('i-am-not-a-valid-vibrancy-type' as any); }).to.not.throw(); }); it('Allows setting a transparent window via CSS', async () => { const appPath = path.join(__dirname, 'fixtures', 'apps', 'background-color-transparent'); appProcess = childProcess.spawn(process.execPath, [appPath]); const [code] = await emittedOnce(appProcess, 'exit'); expect(code).to.equal(0); }); }); ifdescribe(process.platform === 'darwin')('trafficLightPosition', () => { const pos = { x: 10, y: 10 }; afterEach(closeAllWindows); describe('BrowserWindow.getTrafficLightPosition(pos)', () => { it('gets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); expect(w.getTrafficLightPosition()).to.deep.equal(pos); }); it('gets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); expect(w.getTrafficLightPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setTrafficLightPosition(pos)', () => { it('sets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setTrafficLightPosition(newPos); expect(w.getTrafficLightPosition()).to.deep.equal(newPos); }); it('sets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setTrafficLightPosition(newPos); expect(w.getTrafficLightPosition()).to.deep.equal(newPos); }); }); }); ifdescribe(process.platform === 'win32')('BrowserWindow.setAppDetails(options)', () => { afterEach(closeAllWindows); it('supports setting the app details', () => { const w = new BrowserWindow({ show: false }); const iconPath = path.join(fixtures, 'assets', 'icon.ico'); expect(() => { w.setAppDetails({ appId: 'my.app.id' }); w.setAppDetails({ appIconPath: iconPath, appIconIndex: 0 }); w.setAppDetails({ appIconPath: iconPath }); w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name' }); w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2' }); w.setAppDetails({ relaunchDisplayName: 'My app name' }); w.setAppDetails({ appId: 'my.app.id', appIconPath: iconPath, appIconIndex: 0, relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name' }); w.setAppDetails({}); }).to.not.throw(); expect(() => { (w.setAppDetails as any)(); }).to.throw('Insufficient number of arguments.'); }); }); describe('BrowserWindow.fromId(id)', () => { afterEach(closeAllWindows); it('returns the window with id', () => { const w = new BrowserWindow({ show: false }); expect(BrowserWindow.fromId(w.id)!.id).to.equal(w.id); }); }); describe('BrowserWindow.fromWebContents(webContents)', () => { afterEach(closeAllWindows); it('returns the window with the webContents', () => { const w = new BrowserWindow({ show: false }); const found = BrowserWindow.fromWebContents(w.webContents); expect(found!.id).to.equal(w.id); }); it('returns null for webContents without a BrowserWindow', () => { const contents = (webContents as any).create({}); try { expect(BrowserWindow.fromWebContents(contents)).to.be.null('BrowserWindow.fromWebContents(contents)'); } finally { contents.destroy(); } }); it('returns the correct window for a BrowserView webcontents', async () => { const w = new BrowserWindow({ show: false }); const bv = new BrowserView(); w.setBrowserView(bv); defer(() => { w.removeBrowserView(bv); (bv.webContents as any).destroy(); }); await bv.webContents.loadURL('about:blank'); expect(BrowserWindow.fromWebContents(bv.webContents)!.id).to.equal(w.id); }); it('returns the correct window for a WebView webcontents', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } }); w.loadURL('data:text/html,<webview src="data:text/html,hi"></webview>'); // NOTE(nornagon): Waiting for 'did-attach-webview' is a workaround for // https://github.com/electron/electron/issues/25413, and is not integral // to the test. const p = emittedOnce(w.webContents, 'did-attach-webview'); const [, webviewContents] = await emittedOnce(app, 'web-contents-created'); expect(BrowserWindow.fromWebContents(webviewContents)!.id).to.equal(w.id); await p; }); 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((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 as any).destroy(); }); expect(BrowserWindow.fromBrowserView(bv)!.id).to.equal(w.id); }); it('returns the window when there are multiple BrowserViews', () => { const w = new BrowserWindow({ show: false }); const bv1 = new BrowserView(); w.addBrowserView(bv1); const bv2 = new BrowserView(); w.addBrowserView(bv2); defer(() => { w.removeBrowserView(bv1); w.removeBrowserView(bv2); (bv1.webContents as any).destroy(); (bv2.webContents as any).destroy(); }); expect(BrowserWindow.fromBrowserView(bv1)!.id).to.equal(w.id); expect(BrowserWindow.fromBrowserView(bv2)!.id).to.equal(w.id); }); it('returns undefined if not attached', () => { const bv = new BrowserView(); defer(() => { (bv.webContents as any).destroy(); }); expect(BrowserWindow.fromBrowserView(bv)).to.be.null('BrowserWindow associated with bv'); }); }); describe('BrowserWindow.setOpacity(opacity)', () => { afterEach(closeAllWindows); ifdescribe(process.platform !== 'linux')(('Windows and Mac'), () => { it('make window with initial opacity', () => { const w = new BrowserWindow({ show: false, opacity: 0.5 }); expect(w.getOpacity()).to.equal(0.5); }); it('allows setting the opacity', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setOpacity(0.0); expect(w.getOpacity()).to.equal(0.0); w.setOpacity(0.5); expect(w.getOpacity()).to.equal(0.5); w.setOpacity(1.0); expect(w.getOpacity()).to.equal(1.0); }).to.not.throw(); }); it('clamps opacity to [0.0...1.0]', () => { const w = new BrowserWindow({ show: false, opacity: 0.5 }); w.setOpacity(100); expect(w.getOpacity()).to.equal(1.0); w.setOpacity(-100); expect(w.getOpacity()).to.equal(0.0); }); }); ifdescribe(process.platform === 'linux')(('Linux'), () => { it('sets 1 regardless of parameter', () => { const w = new BrowserWindow({ show: false }); w.setOpacity(0); expect(w.getOpacity()).to.equal(1.0); w.setOpacity(0.5); expect(w.getOpacity()).to.equal(1.0); }); }); }); describe('BrowserWindow.setShape(rects)', () => { afterEach(closeAllWindows); it('allows setting shape', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setShape([]); w.setShape([{ x: 0, y: 0, width: 100, height: 100 }]); w.setShape([{ x: 0, y: 0, width: 100, height: 100 }, { x: 0, y: 200, width: 1000, height: 100 }]); w.setShape([]); }).to.not.throw(); }); }); describe('"useContentSize" option', () => { afterEach(closeAllWindows); it('make window created with content size when used', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, useContentSize: true }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); it('make window created with window size when not used', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400 }); const size = w.getSize(); expect(size).to.deep.equal([400, 400]); }); it('works for a frameless window', () => { const w = new BrowserWindow({ show: false, frame: false, width: 400, height: 400, useContentSize: true }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); const size = w.getSize(); expect(size).to.deep.equal([400, 400]); }); }); ifdescribe(process.platform === 'win32' || (process.platform === 'darwin' && semver.gte(os.release(), '14.0.0')))('"titleBarStyle" option', () => { const testWindowsOverlay = async (style: any) => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: style, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: true }); const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); if (process.platform === 'darwin') { await w.loadFile(overlayHTML); } else { const overlayReady = emittedOnce(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const overlayRect = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(overlayRect.y).to.equal(0); if (process.platform === 'darwin') { expect(overlayRect.x).to.be.greaterThan(0); } else { expect(overlayRect.x).to.equal(0); } expect(overlayRect.width).to.be.greaterThan(0); expect(overlayRect.height).to.be.greaterThan(0); const cssOverlayRect = await w.webContents.executeJavaScript('getCssOverlayProperties();'); expect(cssOverlayRect).to.deep.equal(overlayRect); const geometryChange = emittedOnce(ipcMain, 'geometrychange'); w.setBounds({ width: 800 }); const [, newOverlayRect] = await geometryChange; expect(newOverlayRect.width).to.equal(overlayRect.width + 400); }; afterEach(closeAllWindows); afterEach(() => { ipcMain.removeAllListeners('geometrychange'); }); it('creates browser window with hidden title bar', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden' }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); ifit(process.platform === 'darwin')('creates browser window with hidden inset title bar', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hiddenInset' }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); it('sets Window Control Overlay with hidden title bar', async () => { await testWindowsOverlay('hidden'); }); ifit(process.platform === 'darwin')('sets Window Control Overlay with hidden inset title bar', async () => { await testWindowsOverlay('hiddenInset'); }); }); ifdescribe(process.platform === 'win32' || (process.platform === 'darwin' && semver.gte(os.release(), '14.0.0')))('"titleBarOverlay" option', () => { const testWindowsOverlayHeight = async (size: any) => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden', webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { height: size } }); const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); if (process.platform === 'darwin') { await w.loadFile(overlayHTML); } else { const overlayReady = emittedOnce(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const overlayRectPreMax = await w.webContents.executeJavaScript('getJSOverlayProperties()'); await w.maximize(); const max = await w.isMaximized(); expect(max).to.equal(true); const overlayRectPostMax = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(overlayRectPreMax.y).to.equal(0); if (process.platform === 'darwin') { expect(overlayRectPreMax.x).to.be.greaterThan(0); } else { expect(overlayRectPreMax.x).to.equal(0); } expect(overlayRectPreMax.width).to.be.greaterThan(0); expect(overlayRectPreMax.height).to.equal(size); // Confirm that maximization only affected the height of the buttons and not the title bar expect(overlayRectPostMax.height).to.equal(size); }; afterEach(closeAllWindows); afterEach(() => { ipcMain.removeAllListeners('geometrychange'); }); it('sets Window Control Overlay with title bar height of 40', async () => { await testWindowsOverlayHeight(40); }); }); ifdescribe(process.platform === 'darwin')('"enableLargerThanScreen" option', () => { afterEach(closeAllWindows); it('can move the window out of screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); w.setPosition(-10, 50); const after = w.getPosition(); expect(after).to.deep.equal([-10, 50]); }); it('cannot move the window behind menu bar', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[1]).to.be.at.least(0); }); it('can move the window behind menu bar if it has no frame', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true, frame: false }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[0]).to.be.equal(-10); expect(after[1]).to.be.equal(-10); }); it('without it, cannot move the window out of screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: false }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[1]).to.be.at.least(0); }); it('can set the window larger than screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); const size = screen.getPrimaryDisplay().size; size.width += 100; size.height += 100; w.setSize(size.width, size.height); expectBoundsEqual(w.getSize(), [size.width, size.height]); }); it('without it, cannot set the window larger than screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: false }); const size = screen.getPrimaryDisplay().size; size.width += 100; size.height += 100; w.setSize(size.width, size.height); expect(w.getSize()[1]).to.at.most(screen.getPrimaryDisplay().size.height); }); }); ifdescribe(process.platform === 'darwin')('"zoomToPageWidth" option', () => { afterEach(closeAllWindows); it('sets the window width to the page width when used', () => { const w = new BrowserWindow({ show: false, width: 500, height: 400, zoomToPageWidth: true }); w.maximize(); expect(w.getSize()[0]).to.equal(500); }); }); describe('"tabbingIdentifier" option', () => { afterEach(closeAllWindows); it('can be set on a window', () => { expect(() => { /* eslint-disable no-new */ new BrowserWindow({ tabbingIdentifier: 'group1' }); new BrowserWindow({ tabbingIdentifier: 'group2', frame: false }); /* eslint-enable no-new */ }).not.to.throw(); }); }); describe('"webPreferences" option', () => { afterEach(() => { ipcMain.removeAllListeners('answer'); }); afterEach(closeAllWindows); describe('"preload" option', () => { const doesNotLeakSpec = (name: string, webPrefs: { nodeIntegration: boolean, sandbox: boolean, contextIsolation: boolean }) => { it(name, async () => { const w = new BrowserWindow({ webPreferences: { ...webPrefs, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'no-leak.html')); const [, result] = await emittedOnce(ipcMain, 'leak-result'); expect(result).to.have.property('require', 'undefined'); expect(result).to.have.property('exports', 'undefined'); expect(result).to.have.property('windowExports', 'undefined'); expect(result).to.have.property('windowPreload', 'undefined'); expect(result).to.have.property('windowRequire', 'undefined'); }); }; doesNotLeakSpec('does not leak require', { nodeIntegration: false, sandbox: false, contextIsolation: false }); doesNotLeakSpec('does not leak require when sandbox is enabled', { nodeIntegration: false, sandbox: true, contextIsolation: false }); doesNotLeakSpec('does not leak require when context isolation is enabled', { nodeIntegration: false, sandbox: false, contextIsolation: true }); doesNotLeakSpec('does not leak require when context isolation and sandbox are enabled', { nodeIntegration: false, sandbox: true, contextIsolation: true }); it('does not leak any node globals on the window object with nodeIntegration is disabled', async () => { let w = new BrowserWindow({ webPreferences: { contextIsolation: false, nodeIntegration: false, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'globals.html')); const [, notIsolated] = await emittedOnce(ipcMain, 'leak-result'); expect(notIsolated).to.have.property('globals'); w.destroy(); w = new BrowserWindow({ webPreferences: { contextIsolation: true, nodeIntegration: false, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'globals.html')); const [, isolated] = await emittedOnce(ipcMain, 'leak-result'); expect(isolated).to.have.property('globals'); const notIsolatedGlobals = new Set(notIsolated.globals); for (const isolatedGlobal of isolated.globals) { notIsolatedGlobals.delete(isolatedGlobal); } expect([...notIsolatedGlobals]).to.deep.equal([], 'non-isoalted renderer should have no additional globals'); }); it('loads the script before other scripts in window', async () => { const preload = path.join(fixtures, 'module', 'set-global.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false, preload } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test).to.eql('preload'); }); it('has synchronous access to all eventual window APIs', async () => { const preload = path.join(fixtures, 'module', 'access-blink-apis.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false, preload } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test).to.be.an('object'); expect(test.atPreload).to.be.an('array'); expect(test.atLoad).to.be.an('array'); expect(test.atPreload).to.deep.equal(test.atLoad, 'should have access to the same window APIs'); }); }); describe('session preload scripts', function () { const preloads = [ path.join(fixtures, 'module', 'set-global-preload-1.js'), path.join(fixtures, 'module', 'set-global-preload-2.js'), path.relative(process.cwd(), path.join(fixtures, 'module', 'set-global-preload-3.js')) ]; const defaultSession = session.defaultSession; beforeEach(() => { expect(defaultSession.getPreloads()).to.deep.equal([]); defaultSession.setPreloads(preloads); }); afterEach(() => { defaultSession.setPreloads([]); }); it('can set multiple session preload script', () => { expect(defaultSession.getPreloads()).to.deep.equal(preloads); }); const generateSpecs = (description: string, sandbox: boolean) => { describe(description, () => { it('loads the script before other scripts in window including normal preloads', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox, preload: path.join(fixtures, 'module', 'get-global-preload.js'), contextIsolation: false } }); w.loadURL('about:blank'); const [, preload1, preload2, preload3] = await emittedOnce(ipcMain, 'vars'); expect(preload1).to.equal('preload-1'); expect(preload2).to.equal('preload-1-2'); expect(preload3).to.be.undefined('preload 3'); }); }); }; generateSpecs('without sandbox', false); generateSpecs('with sandbox', true); }); describe('"additionalArguments" option', () => { it('adds extra args to process.argv in the renderer process', async () => { const preload = path.join(fixtures, 'module', 'check-arguments.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, preload, additionalArguments: ['--my-magic-arg'] } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, argv] = await emittedOnce(ipcMain, 'answer'); expect(argv).to.include('--my-magic-arg'); }); it('adds extra value args to process.argv in the renderer process', async () => { const preload = path.join(fixtures, 'module', 'check-arguments.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, preload, additionalArguments: ['--my-magic-arg=foo'] } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, argv] = await emittedOnce(ipcMain, 'answer'); expect(argv).to.include('--my-magic-arg=foo'); }); }); describe('"node-integration" option', () => { it('disables node integration by default', async () => { const preload = path.join(fixtures, 'module', 'send-later.js'); const w = new BrowserWindow({ show: false, webPreferences: { preload, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, typeofProcess, typeofBuffer] = await emittedOnce(ipcMain, 'answer'); expect(typeofProcess).to.equal('undefined'); expect(typeofBuffer).to.equal('undefined'); }); }); describe('"sandbox" option', () => { const preload = path.join(path.resolve(__dirname, 'fixtures'), 'module', 'preload-sandbox.js'); let server: http.Server = null as unknown as http.Server; let serverUrl: string = null as unknown as string; before((done) => { server = http.createServer((request, response) => { switch (request.url) { case '/cross-site': response.end(`<html><body><h1>${request.url}</h1></body></html>`); break; default: throw new Error(`unsupported endpoint: ${request.url}`); } }).listen(0, '127.0.0.1', () => { serverUrl = 'http://127.0.0.1:' + (server.address() as AddressInfo).port; done(); }); }); after(() => { server.close(); }); it('exposes ipcRenderer to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test).to.equal('preload'); }); it('exposes ipcRenderer to preload script (path has special chars)', async () => { const preloadSpecialChars = path.join(fixtures, 'module', 'preload-sandboxæø åü.js'); const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload: preloadSpecialChars, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test).to.equal('preload'); }); it('exposes "loaded" event to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload } }); w.loadURL('about:blank'); await emittedOnce(ipcMain, 'process-loaded'); }); it('exposes "exit" event to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?exit-event'); const pageUrl = 'file://' + htmlPath; w.loadURL(pageUrl); const [, url] = await emittedOnce(ipcMain, 'answer'); const expectedUrl = process.platform === 'win32' ? 'file:///' + htmlPath.replace(/\\/g, '/') : pageUrl; expect(url).to.equal(expectedUrl); }); it('should open windows in same domain with cross-scripting enabled', async () => { const w = new BrowserWindow({ show: true, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload } } })); const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?window-open'); const pageUrl = 'file://' + htmlPath; const answer = emittedOnce(ipcMain, 'answer'); w.loadURL(pageUrl); const [, { url, frameName, options }] = await emittedOnce(w.webContents, 'did-create-window'); const expectedUrl = process.platform === 'win32' ? 'file:///' + htmlPath.replace(/\\/g, '/') : pageUrl; expect(url).to.equal(expectedUrl); expect(frameName).to.equal('popup!'); expect(options.width).to.equal(500); expect(options.height).to.equal(600); const [, html] = await answer; expect(html).to.equal('<h1>scripting from opener</h1>'); }); it('should open windows in another domain with cross-scripting disabled', async () => { const w = new BrowserWindow({ show: true, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload } } })); w.loadFile( path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'window-open-external' } ); // Wait for a message from the main window saying that it's ready. await emittedOnce(ipcMain, 'opener-loaded'); // Ask the opener to open a popup with window.opener. const expectedPopupUrl = `${serverUrl}/cross-site`; // Set in "sandbox.html". w.webContents.send('open-the-popup', expectedPopupUrl); // The page is going to open a popup that it won't be able to close. // We have to close it from here later. const [, popupWindow] = await emittedOnce(app, 'browser-window-created'); // Ask the popup window for details. const detailsAnswer = emittedOnce(ipcMain, 'child-loaded'); popupWindow.webContents.send('provide-details'); const [, openerIsNull, , locationHref] = await detailsAnswer; expect(openerIsNull).to.be.false('window.opener is null'); expect(locationHref).to.equal(expectedPopupUrl); // Ask the page to access the popup. const touchPopupResult = emittedOnce(ipcMain, 'answer'); w.webContents.send('touch-the-popup'); const [, popupAccessMessage] = await touchPopupResult; // Ask the popup to access the opener. const touchOpenerResult = emittedOnce(ipcMain, 'answer'); popupWindow.webContents.send('touch-the-opener'); const [, openerAccessMessage] = await touchOpenerResult; // We don't need the popup anymore, and its parent page can't close it, // so let's close it from here before we run any checks. await closeWindow(popupWindow, { assertNotWindows: false }); expect(popupAccessMessage).to.be.a('string', 'child\'s .document is accessible from its parent window'); expect(popupAccessMessage).to.match(/^Blocked a frame with origin/); expect(openerAccessMessage).to.be.a('string', 'opener .document is accessible from a popup window'); expect(openerAccessMessage).to.match(/^Blocked a frame with origin/); }); it('should inherit the sandbox setting in opened windows', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [, { argv }] = await emittedOnce(ipcMain, 'answer'); expect(argv).to.include('--enable-sandbox'); }); it('should open windows with the options configured via new-window event listeners', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath, contextIsolation: false } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [[, childWebContents]] = await Promise.all([ emittedOnce(app, 'web-contents-created'), emittedOnce(ipcMain, 'answer') ]); const webPreferences = childWebContents.getLastWebPreferences(); expect(webPreferences.contextIsolation).to.equal(false); }); it('should set ipc event sender correctly', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); let childWc: WebContents | null = null; w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload, contextIsolation: false } } })); w.webContents.on('did-create-window', (win) => { childWc = win.webContents; expect(w.webContents).to.not.equal(childWc); }); ipcMain.once('parent-ready', function (event) { expect(event.sender).to.equal(w.webContents, 'sender should be the parent'); event.sender.send('verified'); }); ipcMain.once('child-ready', function (event) { expect(childWc).to.not.be.null('child webcontents should be available'); expect(event.sender).to.equal(childWc, 'sender should be the child'); event.sender.send('verified'); }); const done = Promise.all([ 'parent-answer', 'child-answer' ].map(name => emittedOnce(ipcMain, name))); w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'verify-ipc-sender' }); await done; }); describe('event handling', () => { let w: BrowserWindow = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); }); it('works for window events', async () => { const pageTitleUpdated = emittedOnce(w, 'page-title-updated'); w.loadURL('data:text/html,<script>document.title = \'changed\'</script>'); await pageTitleUpdated; }); it('works for stop events', async () => { const done = Promise.all([ 'did-navigate', 'did-fail-load', 'did-stop-loading' ].map(name => emittedOnce(w.webContents, name))); w.loadURL('data:text/html,<script>stop()</script>'); await done; }); it('works for web contents events', async () => { const done = Promise.all([ 'did-finish-load', 'did-frame-finish-load', 'did-navigate-in-page', 'will-navigate', 'did-start-loading', 'did-stop-loading', 'did-frame-finish-load', 'dom-ready' ].map(name => emittedOnce(w.webContents, name))); w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'webcontents-events' }); await done; }); }); it('supports calling preventDefault on new-window events', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const initialWebContents = webContents.getAllWebContents().map((i) => i.id); w.webContents.once('new-window', (e) => { e.preventDefault(); // We need to give it some time so the windows get properly disposed (at least on OSX). setTimeout(() => { const currentWebContents = webContents.getAllWebContents().map((i) => i.id); try { expect(currentWebContents).to.deep.equal(initialWebContents); done(); } catch (error) { done(e); } }, 100); }); w.loadFile(path.join(fixtures, 'pages', 'window-open.html')); }); it('validates process APIs access in sandboxed renderer', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.once('preload-error', (event, preloadPath, error) => { throw error; }); process.env.sandboxmain = 'foo'; w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test.hasCrash).to.be.true('has crash'); expect(test.hasHang).to.be.true('has hang'); expect(test.heapStatistics).to.be.an('object'); expect(test.blinkMemoryInfo).to.be.an('object'); expect(test.processMemoryInfo).to.be.an('object'); expect(test.systemVersion).to.be.a('string'); expect(test.cpuUsage).to.be.an('object'); expect(test.ioCounters).to.be.an('object'); expect(test.uptime).to.be.a('number'); expect(test.arch).to.equal(process.arch); expect(test.platform).to.equal(process.platform); expect(test.env).to.deep.equal(process.env); expect(test.execPath).to.equal(process.helperExecPath); expect(test.sandboxed).to.be.true('sandboxed'); expect(test.contextIsolated).to.be.false('contextIsolated'); expect(test.type).to.equal('renderer'); expect(test.version).to.equal(process.version); expect(test.versions).to.deep.equal(process.versions); expect(test.contextId).to.be.a('string'); if (process.platform === 'linux' && test.osSandbox) { expect(test.creationTime).to.be.null('creation time'); expect(test.systemMemoryInfo).to.be.null('system memory info'); } else { expect(test.creationTime).to.be.a('number'); expect(test.systemMemoryInfo).to.be.an('object'); } }); it('webview in sandbox renderer', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, webviewTag: true, contextIsolation: false } }); const didAttachWebview = emittedOnce(w.webContents, 'did-attach-webview'); const webviewDomReady = emittedOnce(ipcMain, 'webview-dom-ready'); w.loadFile(path.join(fixtures, 'pages', 'webview-did-attach-event.html')); const [, webContents] = await didAttachWebview; const [, id] = await webviewDomReady; expect(webContents.id).to.equal(id); }); }); describe('child windows', () => { let w: BrowserWindow = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, // tests relies on preloads in opened windows nodeIntegrationInSubFrames: true, contextIsolation: false } }); }); it('opens window of about:blank with cross-scripting enabled', async () => { const answer = emittedOnce(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-blank.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('opens window of same domain with cross-scripting enabled', async () => { const answer = emittedOnce(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-file.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('blocks accessing cross-origin frames', async () => { const answer = emittedOnce(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-cross-origin.html')); const [, content] = await answer; expect(content).to.equal('Blocked a frame with origin "file://" from accessing a cross-origin frame.'); }); it('opens window from <iframe> tags', async () => { const answer = emittedOnce(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-iframe.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('opens window with cross-scripting enabled from isolated context', async () => { const w = new BrowserWindow({ show: false, webPreferences: { preload: path.join(fixtures, 'api', 'native-window-open-isolated-preload.js') } }); w.loadFile(path.join(fixtures, 'api', 'native-window-open-isolated.html')); const [, content] = await emittedOnce(ipcMain, 'answer'); expect(content).to.equal('Hello'); }); ifit(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('loads native addons correctly after reload', async () => { w.loadFile(path.join(__dirname, 'fixtures', 'api', 'native-window-open-native-addon.html')); { const [, content] = await emittedOnce(ipcMain, 'answer'); expect(content).to.equal('function'); } w.reload(); { const [, content] = await emittedOnce(ipcMain, 'answer'); expect(content).to.equal('function'); } }); it('<webview> works in a scriptable popup', async () => { const preload = path.join(fixtures, 'api', 'new-window-webview-preload.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegrationInSubFrames: true, webviewTag: true, contextIsolation: false, preload } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { show: false, webPreferences: { contextIsolation: false, webviewTag: true, nodeIntegrationInSubFrames: true } } })); w.webContents.once('new-window', (event, url, frameName, disposition, options) => { options.show = false; }); const webviewLoaded = emittedOnce(ipcMain, 'webview-loaded'); w.loadFile(path.join(fixtures, 'api', 'new-window-webview.html')); await webviewLoaded; }); it('should open windows with the options configured via new-window event listeners', async () => { const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath, contextIsolation: false } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [[, childWebContents]] = await Promise.all([ emittedOnce(app, 'web-contents-created'), emittedOnce(ipcMain, 'answer') ]); const webPreferences = childWebContents.getLastWebPreferences(); expect(webPreferences.contextIsolation).to.equal(false); }); describe('window.location', () => { const protocols = [ ['foo', path.join(fixtures, 'api', 'window-open-location-change.html')], ['bar', path.join(fixtures, 'api', 'window-open-location-final.html')] ]; beforeEach(() => { for (const [scheme, path] of protocols) { protocol.registerBufferProtocol(scheme, (request, callback) => { callback({ mimeType: 'text/html', data: fs.readFileSync(path) }); }); } }); afterEach(() => { for (const [scheme] of protocols) { protocol.unregisterProtocol(scheme); } }); it('retains the original web preferences when window.location is changed to a new origin', async () => { const w = new BrowserWindow({ show: false, webPreferences: { // test relies on preloads in opened window nodeIntegrationInSubFrames: true, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: path.join(mainFixtures, 'api', 'window-open-preload.js'), contextIsolation: false, nodeIntegrationInSubFrames: true } } })); w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html')); const [, { nodeIntegration, typeofProcess }] = await emittedOnce(ipcMain, 'answer'); expect(nodeIntegration).to.be.false(); expect(typeofProcess).to.eql('undefined'); }); it('window.opener is not null when window.location is changed to a new origin', async () => { const w = new BrowserWindow({ show: false, webPreferences: { // test relies on preloads in opened window nodeIntegrationInSubFrames: true } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: path.join(mainFixtures, 'api', 'window-open-preload.js') } } })); w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html')); const [, { windowOpenerIsNull }] = await emittedOnce(ipcMain, 'answer'); expect(windowOpenerIsNull).to.be.false('window.opener is null'); }); }); }); describe('"disableHtmlFullscreenWindowResize" option', () => { it('prevents window from resizing when set', async () => { const w = new BrowserWindow({ show: false, webPreferences: { disableHtmlFullscreenWindowResize: true } }); await w.loadURL('about:blank'); const size = w.getSize(); const enterHtmlFullScreen = emittedOnce(w.webContents, 'enter-html-full-screen'); w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true); await enterHtmlFullScreen; expect(w.getSize()).to.deep.equal(size); }); }); }); describe('beforeunload handler', function () { let w: BrowserWindow = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(closeAllWindows); it('returning undefined would not prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html')); const wait = emittedOnce(w, 'closed'); w.close(); await wait; }); it('returning false would prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); const [, proceed] = await emittedOnce(w.webContents, 'before-unload-fired'); expect(proceed).to.equal(false); }); it('returning empty string would prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-empty-string.html')); w.close(); const [, proceed] = await emittedOnce(w.webContents, 'before-unload-fired'); expect(proceed).to.equal(false); }); it('emits for each close attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const destroyListener = () => { expect.fail('Close was not prevented'); }; w.webContents.once('destroyed', destroyListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await emittedOnce(w.webContents, 'console-message'); w.close(); await emittedOnce(w.webContents, 'before-unload-fired'); w.close(); await emittedOnce(w.webContents, 'before-unload-fired'); w.webContents.removeListener('destroyed', destroyListener); const wait = emittedOnce(w, 'closed'); w.close(); await wait; }); it('emits for each reload attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const navigationListener = () => { expect.fail('Reload was not prevented'); }; w.webContents.once('did-start-navigation', navigationListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await emittedOnce(w.webContents, 'console-message'); w.reload(); // Chromium does not emit 'before-unload-fired' on WebContents for // navigations, so we have to use other ways to know if beforeunload // is fired. await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.reload(); await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.webContents.removeListener('did-start-navigation', navigationListener); w.reload(); await emittedOnce(w.webContents, 'did-finish-load'); }); it('emits for each navigation attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const navigationListener = () => { expect.fail('Reload was not prevented'); }; w.webContents.once('did-start-navigation', navigationListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await emittedOnce(w.webContents, 'console-message'); w.loadURL('about:blank'); // Chromium does not emit 'before-unload-fired' on WebContents for // navigations, so we have to use other ways to know if beforeunload // is fired. await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.loadURL('about:blank'); await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.webContents.removeListener('did-start-navigation', navigationListener); await w.loadURL('about:blank'); }); }); describe('document.visibilityState/hidden', () => { afterEach(closeAllWindows); it('visibilityState is initially visible despite window being hidden', async () => { const w = new BrowserWindow({ show: false, width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); let readyToShow = false; w.once('ready-to-show', () => { readyToShow = true; }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(readyToShow).to.be.false('ready to show'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform !== 'win32')('visibilityState changes when window is hidden', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.hide(); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform !== 'win32')('visibilityState changes when window is shown', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); if (process.platform === 'darwin') { // See https://github.com/electron/electron/issues/8664 await emittedOnce(w, 'show'); } w.hide(); w.show(); const [, visibilityState] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); }); ifit(process.platform !== 'win32')('visibilityState changes when window is shown inactive', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); if (process.platform === 'darwin') { // See https://github.com/electron/electron/issues/8664 await emittedOnce(w, 'show'); } w.hide(); w.showInactive(); const [, visibilityState] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform === 'darwin')('visibilityState changes when window is minimized', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.minimize(); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } }); // FIXME(MarshallOfSound): This test fails locally 100% of the time, on CI it started failing // when we introduced the compositor recycling patch. Should figure out how to fix this it.skip('visibilityState remains visible if backgroundThrottling is disabled', async () => { const w = new BrowserWindow({ show: false, width: 100, height: 100, webPreferences: { backgroundThrottling: false, nodeIntegration: true } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } ipcMain.once('pong', (event, visibilityState, hidden) => { throw new Error(`Unexpected visibility change event. visibilityState: ${visibilityState} hidden: ${hidden}`); }); try { const shown1 = emittedOnce(w, 'show'); w.show(); await shown1; const hidden = emittedOnce(w, 'hide'); w.hide(); await hidden; const shown2 = emittedOnce(w, 'show'); w.show(); await shown2; } finally { ipcMain.removeAllListeners('pong'); } }); }); describe('new-window event', () => { afterEach(closeAllWindows); it('emits when window.open is called', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); w.webContents.once('new-window', (e, url, frameName, disposition, options) => { e.preventDefault(); try { expect(url).to.equal('http://host/'); expect(frameName).to.equal('host'); expect((options as any)['this-is-not-a-standard-feature']).to.equal(true); done(); } catch (e) { done(e); } }); w.loadFile(path.join(fixtures, 'pages', 'window-open.html')); }); it('emits when window.open is called with no webPreferences', (done) => { const w = new BrowserWindow({ show: false }); w.webContents.once('new-window', function (e, url, frameName, disposition, options) { e.preventDefault(); try { expect(url).to.equal('http://host/'); expect(frameName).to.equal('host'); expect((options as any)['this-is-not-a-standard-feature']).to.equal(true); done(); } catch (e) { done(e); } }); w.loadFile(path.join(fixtures, 'pages', 'window-open.html')); }); it('emits when link with target is called', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); w.webContents.once('new-window', (e, url, frameName) => { e.preventDefault(); try { expect(url).to.equal('http://host/'); expect(frameName).to.equal('target'); done(); } catch (e) { done(e); } }); w.loadFile(path.join(fixtures, 'pages', 'target-name.html')); }); it('includes all properties', async () => { const w = new BrowserWindow({ show: false }); const p = new Promise<{ url: string, frameName: string, disposition: string, options: BrowserWindowConstructorOptions, additionalFeatures: string[], referrer: Electron.Referrer, postBody: Electron.PostBody }>((resolve) => { w.webContents.once('new-window', (e, url, frameName, disposition, options, additionalFeatures, referrer, postBody) => { e.preventDefault(); resolve({ url, frameName, disposition, options, additionalFeatures, referrer, postBody }); }); }); w.loadURL(`data:text/html,${encodeURIComponent(` <form target="_blank" method="POST" id="form" action="http://example.com/test"> <input type="text" name="post-test-key" value="post-test-value"></input> </form> <script>form.submit()</script> `)}`); const { url, frameName, disposition, options, additionalFeatures, referrer, postBody } = await p; expect(url).to.equal('http://example.com/test'); expect(frameName).to.equal(''); expect(disposition).to.equal('foreground-tab'); expect(options).to.be.an('object').not.null(); expect(referrer.policy).to.equal('strict-origin-when-cross-origin'); expect(referrer.url).to.equal(''); expect(additionalFeatures).to.deep.equal([]); expect(postBody.data).to.have.length(1); expect(postBody.data[0].type).to.equal('rawData'); expect((postBody.data[0] as any).bytes).to.deep.equal(Buffer.from('post-test-key=post-test-value')); expect(postBody.contentType).to.equal('application/x-www-form-urlencoded'); }); }); ifdescribe(process.platform !== 'linux')('max/minimize events', () => { afterEach(closeAllWindows); it('emits an event when window is maximized', async () => { const w = new BrowserWindow({ show: false }); const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; }); it('emits an event when a transparent window is maximized', async () => { const w = new BrowserWindow({ show: false, frame: false, transparent: true }); const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; }); it('emits only one event when frameless window is maximized', () => { const w = new BrowserWindow({ show: false, frame: false }); let emitted = 0; w.on('maximize', () => emitted++); w.show(); w.maximize(); expect(emitted).to.equal(1); }); it('emits an event when window is unmaximized', async () => { const w = new BrowserWindow({ show: false }); const unmaximize = emittedOnce(w, 'unmaximize'); w.show(); w.maximize(); w.unmaximize(); await unmaximize; }); it('emits an event when a transparent window is unmaximized', async () => { const w = new BrowserWindow({ show: false, frame: false, transparent: true }); const maximize = emittedOnce(w, 'maximize'); const unmaximize = emittedOnce(w, 'unmaximize'); w.show(); w.maximize(); await maximize; w.unmaximize(); await unmaximize; }); it('emits an event when window is minimized', async () => { const w = new BrowserWindow({ show: false }); const minimize = emittedOnce(w, 'minimize'); w.show(); w.minimize(); await minimize; }); }); describe('beginFrameSubscription method', () => { it('does not crash when callback returns nothing', (done) => { const w = new BrowserWindow({ show: false }); 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(() => { w.webContents.endFrameSubscription(); done(); }); }); }); }); it('subscribes to frame updates', (done) => { const w = new BrowserWindow({ show: false }); let called = false; w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); w.webContents.on('dom-ready', () => { w.webContents.beginFrameSubscription(function (data) { // This callback might be called twice. if (called) return; called = true; try { expect(data.constructor.name).to.equal('NativeImage'); expect(data.isEmpty()).to.be.false('data is empty'); done(); } catch (e) { done(e); } finally { w.webContents.endFrameSubscription(); } }); }); }); it('subscribes to frame updates (only dirty rectangle)', (done) => { const w = new BrowserWindow({ show: false }); let called = false; let gotInitialFullSizeFrame = false; const [contentWidth, contentHeight] = w.getContentSize(); w.webContents.on('did-finish-load', () => { w.webContents.beginFrameSubscription(true, (image, rect) => { if (image.isEmpty()) { // Chromium sometimes sends a 0x0 frame at the beginning of the // page load. return; } if (rect.height === contentHeight && rect.width === contentWidth && !gotInitialFullSizeFrame) { // The initial frame is full-size, but we're looking for a call // with just the dirty-rect. The next frame should be a smaller // rect. gotInitialFullSizeFrame = true; return; } // This callback might be called twice. if (called) return; // We asked for just the dirty rectangle, so we expect to receive a // rect smaller than the full size. // TODO(jeremy): this is failing on windows currently; investigate. // assert(rect.width < contentWidth || rect.height < contentHeight) called = true; try { const expectedSize = rect.width * rect.height * 4; expect(image.getBitmap()).to.be.an.instanceOf(Buffer).with.lengthOf(expectedSize); done(); } catch (e) { done(e); } finally { w.webContents.endFrameSubscription(); } }); }); w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); }); it('throws error when subscriber is not well defined', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.webContents.beginFrameSubscription(true, true as any); // TODO(zcbenz): gin is weak at guessing parameter types, we should // upstream native_mate's implementation to gin. }).to.throw('Error processing argument at index 1, conversion failure from '); }); }); describe('savePage method', () => { const savePageDir = path.join(fixtures, 'save_page'); const savePageHtmlPath = path.join(savePageDir, 'save_page.html'); const savePageJsPath = path.join(savePageDir, 'save_page_files', 'test.js'); const savePageCssPath = path.join(savePageDir, 'save_page_files', 'test.css'); afterEach(() => { closeAllWindows(); try { fs.unlinkSync(savePageCssPath); fs.unlinkSync(savePageJsPath); fs.unlinkSync(savePageHtmlPath); fs.rmdirSync(path.join(savePageDir, 'save_page_files')); fs.rmdirSync(savePageDir); } catch {} }); it('should throw when passing relative paths', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await expect( w.webContents.savePage('save_page.html', 'HTMLComplete') ).to.eventually.be.rejectedWith('Path must be absolute'); await expect( w.webContents.savePage('save_page.html', 'HTMLOnly') ).to.eventually.be.rejectedWith('Path must be absolute'); await expect( w.webContents.savePage('save_page.html', 'MHTML') ).to.eventually.be.rejectedWith('Path must be absolute'); }); it('should save page to disk with HTMLOnly', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'HTMLOnly'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.false('js path'); expect(fs.existsSync(savePageCssPath)).to.be.false('css path'); }); it('should save page to disk with MHTML', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'MHTML'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.false('js path'); expect(fs.existsSync(savePageCssPath)).to.be.false('css path'); }); it('should save page to disk with HTMLComplete', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'HTMLComplete'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.true('js path'); expect(fs.existsSync(savePageCssPath)).to.be.true('css path'); }); }); describe('BrowserWindow options argument is optional', () => { afterEach(closeAllWindows); it('should create a window with default size (800x600)', () => { const w = new BrowserWindow(); expect(w.getSize()).to.deep.equal([800, 600]); }); }); describe('BrowserWindow.restore()', () => { afterEach(closeAllWindows); it('should restore the previous window size', () => { const w = new BrowserWindow({ minWidth: 800, width: 800 }); const initialSize = w.getSize(); w.minimize(); w.restore(); expectBoundsEqual(w.getSize(), initialSize); }); it('does not crash when restoring hidden minimized window', () => { const w = new BrowserWindow({}); w.minimize(); w.hide(); w.show(); }); }); // 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 = emittedOnce(w, 'hide'); let shown = emittedOnce(w, 'show'); const maximize = emittedOnce(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 = emittedOnce(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 = emittedOnce(w, 'minimize'); w.minimize(); await minimize; w.unmaximize(); await delay(1000); expect(w.isMinimized()).to.be.true(); }); it('should not change the size or position of a normal window', async () => { const w = new BrowserWindow(); const initialSize = w.getSize(); const initialPosition = w.getPosition(); w.unmaximize(); await delay(1000); expectBoundsEqual(w.getSize(), initialSize); expectBoundsEqual(w.getPosition(), initialPosition); }); 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 delay(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 = emittedOnce(w, 'show'); // start fullscreen and hidden w.setFullScreen(true); w.show(); await shown; const leftFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leftFullScreen; expect(w.isVisible()).to.be.true('visible'); expect(w.isFullScreen()).to.be.false('fullscreen'); }); it('should keep window hidden if already in hidden state', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const leftFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leftFullScreen; expect(w.isVisible()).to.be.false('visible'); expect(w.isFullScreen()).to.be.false('fullscreen'); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setFullScreen(false) when HTML fullscreen', () => { it('exits HTML fullscreen when window leaves fullscreen', async () => { const w = new BrowserWindow(); await w.loadURL('about:blank'); await w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true); await emittedOnce(w, 'enter-full-screen'); // Wait a tick for the full-screen state to 'stick' await delay(); w.setFullScreen(false); await emittedOnce(w, 'leave-html-full-screen'); }); }); }); describe('parent window', () => { afterEach(closeAllWindows); ifit(process.platform === 'darwin')('sheet-begin event emits when window opens a sheet', async () => { const w = new BrowserWindow(); const sheetBegin = emittedOnce(w, 'sheet-begin'); // eslint-disable-next-line no-new new BrowserWindow({ modal: true, parent: w }); await sheetBegin; }); ifit(process.platform === 'darwin')('sheet-end event emits when window has closed a sheet', async () => { const w = new BrowserWindow(); const sheet = new BrowserWindow({ modal: true, parent: w }); const sheetEnd = emittedOnce(w, 'sheet-end'); sheet.close(); await sheetEnd; }); describe('parent option', () => { it('sets parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(c.getParentWindow()).to.equal(w); }); it('adds window to child windows of parent', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(w.getChildWindows()).to.deep.equal([c]); }); it('removes from child windows of parent when window is closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); const closed = emittedOnce(c, 'closed'); c.close(); await closed; // The child window list is not immediately cleared, so wait a tick until it's ready. await delay(); expect(w.getChildWindows().length).to.equal(0); }); it('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 delay(); 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 = emittedOnce(c, 'closed'); c.setParentWindow(w); c.close(); await closed; // The child window list is not immediately cleared, so wait a tick until it's ready. await delay(); expect(w.getChildWindows().length).to.equal(0); }); }); describe('modal option', () => { it('does not freeze or crash', async () => { const parentWindow = new BrowserWindow(); const createTwo = async () => { const two = new BrowserWindow({ width: 300, height: 200, parent: parentWindow, modal: true, show: false }); const twoShown = emittedOnce(two, 'show'); two.show(); await twoShown; setTimeout(() => two.close(), 500); await emittedOnce(two, 'closed'); }; const one = new BrowserWindow({ width: 600, height: 400, parent: parentWindow, modal: true, show: false }); const oneShown = emittedOnce(one, 'show'); one.show(); await oneShown; setTimeout(() => one.destroy(), 500); await emittedOnce(one, 'closed'); await createTwo(); }); ifit(process.platform !== 'darwin')('disables parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); expect(w.isEnabled()).to.be.true('w.isEnabled'); c.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); }); ifit(process.platform !== 'darwin')('re-enables an enabled parent window when closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const closed = emittedOnce(c, 'closed'); c.show(); c.close(); await closed; expect(w.isEnabled()).to.be.true('w.isEnabled'); }); ifit(process.platform !== 'darwin')('does not re-enable a disabled parent window when closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const closed = emittedOnce(c, 'closed'); w.setEnabled(false); c.show(); c.close(); await closed; expect(w.isEnabled()).to.be.false('w.isEnabled'); }); ifit(process.platform !== 'darwin')('disables parent window recursively', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const c2 = new BrowserWindow({ show: false, parent: w, modal: true }); c.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c2.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c.destroy(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c2.destroy(); expect(w.isEnabled()).to.be.true('w.isEnabled'); }); }); }); describe('window states', () => { afterEach(closeAllWindows); it('does not resize frameless windows when states change', () => { const w = new BrowserWindow({ frame: false, width: 300, height: 200, show: false }); w.minimizable = false; w.minimizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.resizable = false; w.resizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.maximizable = false; w.maximizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.fullScreenable = false; w.fullScreenable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.closable = false; w.closable = true; expect(w.getSize()).to.deep.equal([300, 200]); }); describe('resizable state', () => { it('with properties', () => { it('can be set with resizable constructor option', () => { const w = new BrowserWindow({ show: false, resizable: false }); expect(w.resizable).to.be.false('resizable'); if (process.platform === 'darwin') { expect(w.maximizable).to.to.true('maximizable'); } }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.resizable).to.be.true('resizable'); w.resizable = false; expect(w.resizable).to.be.false('resizable'); w.resizable = true; expect(w.resizable).to.be.true('resizable'); }); }); it('with functions', () => { it('can be set with resizable constructor option', () => { const w = new BrowserWindow({ show: false, resizable: false }); expect(w.isResizable()).to.be.false('resizable'); if (process.platform === 'darwin') { expect(w.isMaximizable()).to.to.true('maximizable'); } }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isResizable()).to.be.true('resizable'); w.setResizable(false); expect(w.isResizable()).to.be.false('resizable'); w.setResizable(true); expect(w.isResizable()).to.be.true('resizable'); }); }); it('works for a frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); expect(w.resizable).to.be.true('resizable'); if (process.platform === 'win32') { const w = new BrowserWindow({ show: false, thickFrame: false }); expect(w.resizable).to.be.false('resizable'); } }); // On Linux there is no "resizable" property of a window. ifit(process.platform !== 'linux')('does affect maximizability when disabled and enabled', () => { const w = new BrowserWindow({ show: false }); expect(w.resizable).to.be.true('resizable'); expect(w.maximizable).to.be.true('maximizable'); w.resizable = false; expect(w.maximizable).to.be.false('not maximizable'); w.resizable = true; expect(w.maximizable).to.be.true('maximizable'); }); ifit(process.platform === 'win32')('works for a window smaller than 64x64', () => { const w = new BrowserWindow({ show: false, frame: false, resizable: false, transparent: true }); w.setContentSize(60, 60); expectBoundsEqual(w.getContentSize(), [60, 60]); w.setContentSize(30, 30); expectBoundsEqual(w.getContentSize(), [30, 30]); w.setContentSize(10, 10); expectBoundsEqual(w.getContentSize(), [10, 10]); }); }); describe('loading main frame state', () => { let server: http.Server = null as unknown as http.Server; let serverUrl: string = null as unknown as string; before((done) => { server = http.createServer((request, response) => { response.end(); }).listen(0, '127.0.0.1', () => { serverUrl = 'http://127.0.0.1:' + (server.address() as AddressInfo).port; done(); }); }); after(() => { server.close(); }); it('is true when the main frame is loading', async () => { const w = new BrowserWindow({ show: false }); const didStartLoading = emittedOnce(w.webContents, 'did-start-loading'); w.webContents.loadURL(serverUrl); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame'); }); it('is false when only a subframe is loading', async () => { const w = new BrowserWindow({ show: false }); const didStopLoading = emittedOnce(w.webContents, 'did-stop-loading'); w.webContents.loadURL(serverUrl); await didStopLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); const didStartLoading = emittedOnce(w.webContents, 'did-start-loading'); w.webContents.executeJavaScript(` var iframe = document.createElement('iframe') iframe.src = '${serverUrl}/page2' document.body.appendChild(iframe) `); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); }); it('is true when navigating to pages from the same origin', async () => { const w = new BrowserWindow({ show: false }); const didStopLoading = emittedOnce(w.webContents, 'did-stop-loading'); w.webContents.loadURL(serverUrl); await didStopLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); const didStartLoading = emittedOnce(w.webContents, 'did-start-loading'); w.webContents.loadURL(`${serverUrl}/page2`); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame'); }); }); }); ifdescribe(process.platform !== 'linux')('window states (excluding Linux)', () => { // Not implemented on Linux. afterEach(closeAllWindows); describe('movable state', () => { it('with properties', () => { it('can be set with movable constructor option', () => { const w = new BrowserWindow({ show: false, movable: false }); expect(w.movable).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.movable).to.be.true('movable'); w.movable = false; expect(w.movable).to.be.false('movable'); w.movable = true; expect(w.movable).to.be.true('movable'); }); }); it('with functions', () => { it('can be set with movable constructor option', () => { const w = new BrowserWindow({ show: false, movable: false }); expect(w.isMovable()).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMovable()).to.be.true('movable'); w.setMovable(false); expect(w.isMovable()).to.be.false('movable'); w.setMovable(true); expect(w.isMovable()).to.be.true('movable'); }); }); }); describe('visibleOnAllWorkspaces state', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.visibleOnAllWorkspaces).to.be.false(); w.visibleOnAllWorkspaces = true; expect(w.visibleOnAllWorkspaces).to.be.true(); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isVisibleOnAllWorkspaces()).to.be.false(); w.setVisibleOnAllWorkspaces(true); expect(w.isVisibleOnAllWorkspaces()).to.be.true(); }); }); }); ifdescribe(process.platform === 'darwin')('documentEdited state', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.documentEdited).to.be.false(); w.documentEdited = true; expect(w.documentEdited).to.be.true(); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isDocumentEdited()).to.be.false(); w.setDocumentEdited(true); expect(w.isDocumentEdited()).to.be.true(); }); }); }); ifdescribe(process.platform === 'darwin')('representedFilename', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.representedFilename).to.eql(''); w.representedFilename = 'a name'; expect(w.representedFilename).to.eql('a name'); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.getRepresentedFilename()).to.eql(''); w.setRepresentedFilename('a name'); expect(w.getRepresentedFilename()).to.eql('a name'); }); }); }); describe('native window title', () => { it('with properties', () => { it('can be set with title constructor option', () => { const w = new BrowserWindow({ show: false, title: 'mYtItLe' }); expect(w.title).to.eql('mYtItLe'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.title).to.eql('Electron Test Main'); w.title = 'NEW TITLE'; expect(w.title).to.eql('NEW TITLE'); }); }); it('with functions', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, title: 'mYtItLe' }); expect(w.getTitle()).to.eql('mYtItLe'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.getTitle()).to.eql('Electron Test Main'); w.setTitle('NEW TITLE'); expect(w.getTitle()).to.eql('NEW TITLE'); }); }); }); describe('minimizable state', () => { it('with properties', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, minimizable: false }); expect(w.minimizable).to.be.false('minimizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.minimizable).to.be.true('minimizable'); w.minimizable = false; expect(w.minimizable).to.be.false('minimizable'); w.minimizable = true; expect(w.minimizable).to.be.true('minimizable'); }); }); it('with functions', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, minimizable: false }); expect(w.isMinimizable()).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMinimizable()).to.be.true('isMinimizable'); w.setMinimizable(false); expect(w.isMinimizable()).to.be.false('isMinimizable'); w.setMinimizable(true); expect(w.isMinimizable()).to.be.true('isMinimizable'); }); }); }); describe('maximizable state (property)', () => { it('with properties', () => { it('can be set with maximizable constructor option', () => { const w = new BrowserWindow({ show: false, maximizable: false }); expect(w.maximizable).to.be.false('maximizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.maximizable).to.be.true('maximizable'); w.maximizable = false; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; expect(w.maximizable).to.be.true('maximizable'); }); it('is not affected when changing other states', () => { const w = new BrowserWindow({ show: false }); w.maximizable = false; expect(w.maximizable).to.be.false('maximizable'); w.minimizable = false; expect(w.maximizable).to.be.false('maximizable'); w.closable = false; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; expect(w.maximizable).to.be.true('maximizable'); w.closable = true; expect(w.maximizable).to.be.true('maximizable'); w.fullScreenable = false; expect(w.maximizable).to.be.true('maximizable'); }); }); it('with functions', () => { it('can be set with maximizable constructor option', () => { const w = new BrowserWindow({ show: false, maximizable: false }); expect(w.isMaximizable()).to.be.false('isMaximizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setMaximizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); it('is not affected when changing other states', () => { const w = new BrowserWindow({ show: false }); w.setMaximizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMinimizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setClosable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setClosable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setFullScreenable(false); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); }); }); ifdescribe(process.platform === 'win32')('maximizable state', () => { it('with properties', () => { it('is reset to its former state', () => { const w = new BrowserWindow({ show: false }); w.maximizable = false; w.resizable = false; w.resizable = true; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; w.resizable = false; w.resizable = true; expect(w.maximizable).to.be.true('maximizable'); }); }); it('with functions', () => { it('is reset to its former state', () => { const w = new BrowserWindow({ show: false }); w.setMaximizable(false); w.setResizable(false); w.setResizable(true); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); w.setResizable(false); w.setResizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); }); }); ifdescribe(process.platform !== 'darwin')('menuBarVisible state', () => { describe('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.menuBarVisible).to.be.true(); w.menuBarVisible = false; expect(w.menuBarVisible).to.be.false(); w.menuBarVisible = true; expect(w.menuBarVisible).to.be.true(); }); }); describe('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); w.setMenuBarVisibility(false); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); w.setMenuBarVisibility(true); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); }); }); }); ifdescribe(process.platform === 'darwin')('fullscreenable state', () => { it('with functions', () => { it('can be set with fullscreenable constructor option', () => { const w = new BrowserWindow({ show: false, fullscreenable: false }); expect(w.isFullScreenable()).to.be.false('isFullScreenable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isFullScreenable()).to.be.true('isFullScreenable'); w.setFullScreenable(false); expect(w.isFullScreenable()).to.be.false('isFullScreenable'); w.setFullScreenable(true); expect(w.isFullScreenable()).to.be.true('isFullScreenable'); }); }); }); // fullscreen events are dispatched eagerly and twiddling things too fast can confuse poor Electron ifdescribe(process.platform === 'darwin')('kiosk state', () => { it('with properties', () => { it('can be set with a constructor property', () => { const w = new BrowserWindow({ kiosk: true }); expect(w.kiosk).to.be.true(); }); it('can be changed ', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.kiosk = true; expect(w.isKiosk()).to.be.true('isKiosk'); await enterFullScreen; await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.kiosk = false; expect(w.isKiosk()).to.be.false('isKiosk'); await leaveFullScreen; }); }); it('with functions', () => { it('can be set with a constructor property', () => { const w = new BrowserWindow({ kiosk: true }); expect(w.isKiosk()).to.be.true(); }); it('can be changed ', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setKiosk(true); expect(w.isKiosk()).to.be.true('isKiosk'); await enterFullScreen; await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setKiosk(false); expect(w.isKiosk()).to.be.false('isKiosk'); await leaveFullScreen; }); }); }); ifdescribe(process.platform === 'darwin')('fullscreen state with resizable set', () => { it('resizable flag should be set to true and restored', async () => { const w = new BrowserWindow({ resizable: false }); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.resizable).to.be.true('resizable'); await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.resizable).to.be.false('resizable'); }); }); ifdescribe(process.platform === 'darwin')('fullscreen state', () => { it('should not cause a crash if called when exiting fullscreen', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; }); it('can be changed with setFullScreen method', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('isFullScreen'); }); it('handles several transitions starting with fullscreen', async () => { const w = new BrowserWindow({ fullscreen: true, show: true }); expect(w.isFullScreen()).to.be.true('not fullscreen'); w.setFullScreen(false); w.setFullScreen(true); const enterFullScreen = emittedNTimes(w, 'enter-full-screen', 2); await enterFullScreen; expect(w.isFullScreen()).to.be.true('not fullscreen'); await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); }); it('handles several transitions in close proximity', async () => { const w = new BrowserWindow(); expect(w.isFullScreen()).to.be.false('is fullscreen'); w.setFullScreen(true); w.setFullScreen(false); w.setFullScreen(true); const enterFullScreen = emittedNTimes(w, 'enter-full-screen', 2); await enterFullScreen; expect(w.isFullScreen()).to.be.true('not fullscreen'); }); it('does not crash when exiting simpleFullScreen (properties)', async () => { const w = new BrowserWindow(); w.setSimpleFullScreen(true); await delay(1000); w.setFullScreen(!w.isFullScreen()); }); it('does not crash when exiting simpleFullScreen (functions)', async () => { const w = new BrowserWindow(); w.simpleFullScreen = true; await delay(1000); w.setFullScreen(!w.isFullScreen()); }); it('should not be changed by setKiosk method', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await delay(); w.setKiosk(true); await delay(); w.setKiosk(false); expect(w.isFullScreen()).to.be.true('isFullScreen'); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('isFullScreen'); }); // FIXME: https://github.com/electron/electron/issues/30140 xit('multiple windows inherit correct fullscreen state', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await delay(); const w2 = new BrowserWindow({ show: false }); const enterFullScreen2 = emittedOnce(w2, 'enter-full-screen'); w2.show(); await enterFullScreen2; expect(w2.isFullScreen()).to.be.true('isFullScreen'); }); }); describe('closable state', () => { it('with properties', () => { it('can be set with closable constructor option', () => { const w = new BrowserWindow({ show: false, closable: false }); expect(w.closable).to.be.false('closable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.closable).to.be.true('closable'); w.closable = false; expect(w.closable).to.be.false('closable'); w.closable = true; expect(w.closable).to.be.true('closable'); }); }); it('with functions', () => { it('can be set with closable constructor option', () => { const w = new BrowserWindow({ show: false, closable: false }); expect(w.isClosable()).to.be.false('isClosable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isClosable()).to.be.true('isClosable'); w.setClosable(false); expect(w.isClosable()).to.be.false('isClosable'); w.setClosable(true); expect(w.isClosable()).to.be.true('isClosable'); }); }); }); describe('hasShadow state', () => { it('with properties', () => { it('returns a boolean on all platforms', () => { const w = new BrowserWindow({ show: false }); expect(w.shadow).to.be.a('boolean'); }); // On Windows there's no shadow by default & it can't be changed dynamically. it('can be changed with hasShadow option', () => { const hasShadow = process.platform !== 'darwin'; const w = new BrowserWindow({ show: false, hasShadow }); expect(w.shadow).to.equal(hasShadow); }); it('can be changed with setHasShadow method', () => { const w = new BrowserWindow({ show: false }); w.shadow = false; expect(w.shadow).to.be.false('hasShadow'); w.shadow = true; expect(w.shadow).to.be.true('hasShadow'); w.shadow = false; expect(w.shadow).to.be.false('hasShadow'); }); }); describe('with functions', () => { it('returns a boolean on all platforms', () => { const w = new BrowserWindow({ show: false }); const hasShadow = w.hasShadow(); expect(hasShadow).to.be.a('boolean'); }); // On Windows there's no shadow by default & it can't be changed dynamically. it('can be changed with hasShadow option', () => { const hasShadow = process.platform !== 'darwin'; const w = new BrowserWindow({ show: false, hasShadow }); expect(w.hasShadow()).to.equal(hasShadow); }); it('can be changed with setHasShadow method', () => { const w = new BrowserWindow({ show: false }); w.setHasShadow(false); expect(w.hasShadow()).to.be.false('hasShadow'); w.setHasShadow(true); expect(w.hasShadow()).to.be.true('hasShadow'); w.setHasShadow(false); expect(w.hasShadow()).to.be.false('hasShadow'); }); }); }); }); describe('window.getMediaSourceId()', () => { afterEach(closeAllWindows); it('returns valid source id', async () => { const w = new BrowserWindow({ show: false }); const shown = emittedOnce(w, 'show'); w.show(); await shown; // Check format 'window:1234:0'. const sourceId = w.getMediaSourceId(); expect(sourceId).to.match(/^window:\d+:\d+$/); }); }); ifdescribe(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('window.getNativeWindowHandle()', () => { afterEach(closeAllWindows); it('returns valid handle', () => { const w = new BrowserWindow({ show: false }); // The module's source code is hosted at // https://github.com/electron/node-is-valid-window const isValidWindow = require('is-valid-window'); expect(isValidWindow(w.getNativeWindowHandle())).to.be.true('is valid window'); }); }); ifdescribe(process.platform === 'darwin')('previewFile', () => { afterEach(closeAllWindows); it('opens the path in Quick Look on macOS', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.previewFile(__filename); w.closeFilePreview(); }).to.not.throw(); }); }); describe('contextIsolation option with and without sandbox option', () => { const expectedContextData = { preloadContext: { preloadProperty: 'number', pageProperty: 'undefined', typeofRequire: 'function', typeofProcess: 'object', typeofArrayPush: 'function', typeofFunctionApply: 'function', typeofPreloadExecuteJavaScriptProperty: 'undefined' }, pageContext: { preloadProperty: 'undefined', pageProperty: 'string', typeofRequire: 'undefined', typeofProcess: 'undefined', typeofArrayPush: 'number', typeofFunctionApply: 'boolean', typeofPreloadExecuteJavaScriptProperty: 'number', typeofOpenedWindow: 'object' } }; afterEach(closeAllWindows); it('separates the page context from the Electron/preload context', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = emittedOnce(ipcMain, 'isolated-world'); iw.loadFile(path.join(fixtures, 'api', 'isolated.html')); const [, data] = await p; expect(data).to.deep.equal(expectedContextData); }); it('recreates the contexts on reload', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); await iw.loadFile(path.join(fixtures, 'api', 'isolated.html')); const isolatedWorld = emittedOnce(ipcMain, 'isolated-world'); iw.webContents.reload(); const [, data] = await isolatedWorld; expect(data).to.deep.equal(expectedContextData); }); it('enables context isolation on child windows', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const browserWindowCreated = emittedOnce(app, 'browser-window-created'); iw.loadFile(path.join(fixtures, 'pages', 'window-open.html')); const [, window] = await browserWindowCreated; expect(window.webContents.getLastWebPreferences().contextIsolation).to.be.true('contextIsolation'); }); it('separates the page context from the Electron/preload context with sandbox on', async () => { const ws = new BrowserWindow({ show: false, webPreferences: { sandbox: true, contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = emittedOnce(ipcMain, 'isolated-world'); ws.loadFile(path.join(fixtures, 'api', 'isolated.html')); const [, data] = await p; expect(data).to.deep.equal(expectedContextData); }); it('recreates the contexts on reload with sandbox on', async () => { const ws = new BrowserWindow({ show: false, webPreferences: { sandbox: true, contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); await ws.loadFile(path.join(fixtures, 'api', 'isolated.html')); const isolatedWorld = emittedOnce(ipcMain, 'isolated-world'); ws.webContents.reload(); const [, data] = await isolatedWorld; expect(data).to.deep.equal(expectedContextData); }); it('supports fetch api', async () => { const fetchWindow = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-fetch-preload.js') } }); const p = emittedOnce(ipcMain, 'isolated-fetch-error'); fetchWindow.loadURL('about:blank'); const [, error] = await p; expect(error).to.equal('Failed to fetch'); }); it('doesn\'t break ipc serialization', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = emittedOnce(ipcMain, 'isolated-world'); iw.loadURL('about:blank'); iw.webContents.executeJavaScript(` const opened = window.open() openedLocation = opened.location.href opened.close() window.postMessage({openedLocation}, '*') `); const [, data] = await p; expect(data.pageContext.openedLocation).to.equal('about:blank'); }); it('reports process.contextIsolated', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-process.js') } }); const p = emittedOnce(ipcMain, 'context-isolation'); iw.loadURL('about:blank'); const [, contextIsolation] = await p; expect(contextIsolation).to.be.true('contextIsolation'); }); }); it('reloading does not cause Node.js module API hangs after reload', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); let count = 0; ipcMain.on('async-node-api-done', () => { if (count === 3) { ipcMain.removeAllListeners('async-node-api-done'); done(); } else { count++; w.reload(); } }); w.loadFile(path.join(fixtures, 'pages', 'send-after-node.html')); }); describe('window.webContents.focus()', () => { afterEach(closeAllWindows); it('focuses window', async () => { const w1 = new BrowserWindow({ x: 100, y: 300, width: 300, height: 200 }); w1.loadURL('about:blank'); const w2 = new BrowserWindow({ x: 300, y: 300, width: 300, height: 200 }); w2.loadURL('about:blank'); const w1Focused = emittedOnce(w1, 'focus'); w1.webContents.focus(); await w1Focused; expect(w1.webContents.isFocused()).to.be.true('focuses window'); }); }); ifdescribe(features.isOffscreenRenderingEnabled())('offscreen rendering', () => { let w: BrowserWindow; beforeEach(function () { w = new BrowserWindow({ width: 100, height: 100, show: false, webPreferences: { backgroundThrottling: false, offscreen: true } }); }); afterEach(closeAllWindows); it('creates offscreen window with correct size', async () => { const paint = emittedOnce(w.webContents, 'paint'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); const [,, data] = await paint; expect(data.constructor.name).to.equal('NativeImage'); expect(data.isEmpty()).to.be.false('data is empty'); const size = data.getSize(); const { scaleFactor } = screen.getPrimaryDisplay(); expect(size.width).to.be.closeTo(100 * scaleFactor, 2); expect(size.height).to.be.closeTo(100 * scaleFactor, 2); }); it('does not crash after navigation', () => { w.webContents.loadURL('about:blank'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); }); describe('window.webContents.isOffscreen()', () => { it('is true for offscreen type', () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); expect(w.webContents.isOffscreen()).to.be.true('isOffscreen'); }); it('is false for regular window', () => { const c = new BrowserWindow({ show: false }); expect(c.webContents.isOffscreen()).to.be.false('isOffscreen'); c.destroy(); }); }); describe('window.webContents.isPainting()', () => { it('returns whether is currently painting', async () => { const paint = emittedOnce(w.webContents, 'paint'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await paint; expect(w.webContents.isPainting()).to.be.true('isPainting'); }); }); describe('window.webContents.stopPainting()', () => { it('stops painting', async () => { const domReady = emittedOnce(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.stopPainting(); expect(w.webContents.isPainting()).to.be.false('isPainting'); }); }); describe('window.webContents.startPainting()', () => { it('starts painting', async () => { const domReady = emittedOnce(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.stopPainting(); w.webContents.startPainting(); await emittedOnce(w.webContents, 'paint'); expect(w.webContents.isPainting()).to.be.true('isPainting'); }); }); describe('frameRate APIs', () => { it('has default frame rate (function)', async () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await emittedOnce(w.webContents, 'paint'); expect(w.webContents.getFrameRate()).to.equal(60); }); it('has default frame rate (property)', async () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await emittedOnce(w.webContents, 'paint'); expect(w.webContents.frameRate).to.equal(60); }); it('sets custom frame rate (function)', async () => { const domReady = emittedOnce(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.setFrameRate(30); await emittedOnce(w.webContents, 'paint'); expect(w.webContents.getFrameRate()).to.equal(30); }); it('sets custom frame rate (property)', async () => { const domReady = emittedOnce(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.frameRate = 30; await emittedOnce(w.webContents, 'paint'); expect(w.webContents.frameRate).to.equal(30); }); }); }); describe('"transparent" option', () => { afterEach(closeAllWindows); // Only applicable on Windows where transparent windows can't be maximized. ifit(process.platform === 'win32')('can show maximized frameless window', async () => { const display = screen.getPrimaryDisplay(); const w = new BrowserWindow({ ...display.bounds, frame: false, transparent: true, show: true }); w.loadURL('about:blank'); await emittedOnce(w, 'ready-to-show'); expect(w.isMaximized()).to.be.true(); // Fails when the transparent HWND is in an invalid maximized state. expect(w.getBounds()).to.deep.equal(display.workArea); const newBounds = { width: 256, height: 256, x: 0, y: 0 }; w.setBounds(newBounds); expect(w.getBounds()).to.deep.equal(newBounds); }); // Linux and arm64 platforms (WOA and macOS) do not return any capture sources ifit(process.platform !== 'linux' && process.arch !== 'arm64')('should not display a visible background', async () => { const display = screen.getPrimaryDisplay(); const backgroundWindow = new BrowserWindow({ ...display.bounds, frame: false, backgroundColor: CHROMA_COLOR_HEX, hasShadow: false }); await backgroundWindow.loadURL('about:blank'); const foregroundWindow = new BrowserWindow({ ...display.bounds, show: true, transparent: true, frame: false, hasShadow: false }); foregroundWindow.loadFile(path.join(__dirname, 'fixtures', 'pages', 'half-background-color.html')); await emittedOnce(foregroundWindow, 'ready-to-show'); const screenCapture = await captureScreen(); const leftHalfColor = getPixelColor(screenCapture, { x: display.size.width / 4, y: display.size.height / 2 }); const rightHalfColor = getPixelColor(screenCapture, { x: display.size.width - (display.size.width / 4), y: display.size.height / 2 }); expect(areColorsSimilar(leftHalfColor, CHROMA_COLOR_HEX)).to.be.true(); expect(areColorsSimilar(rightHalfColor, '#ff0000')).to.be.true(); }); }); describe('"backgroundColor" option', () => { afterEach(closeAllWindows); // Linux/WOA doesn't return any capture sources. ifit(process.platform !== 'linux' && (process.platform !== 'win32' || process.arch !== 'arm64'))('should display the set color', async () => { const display = screen.getPrimaryDisplay(); const w = new BrowserWindow({ ...display.bounds, show: true, backgroundColor: CHROMA_COLOR_HEX }); w.loadURL('about:blank'); await emittedOnce(w, 'ready-to-show'); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); expect(areColorsSimilar(centerColor, CHROMA_COLOR_HEX)).to.be.true(); }); }); });
closed
electron/electron
https://github.com/electron/electron
34,152
[Bug]: Non-default window dispositions fail to load initial URL
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 18.2.1 ### What operating system are you using? - Windows - macOS ### Operating System Version - Windows 10 21H2 - macOS 12.3.1 ### What arch are you using? x64 ### Last Known Working Electron version 17.4.3 ### Expected Behavior `Shift+LeftClick` (new-window) or `Ctrl+Shift+LeftClick` (foreground-tab) on links should open and load them in a new window. ### Actual Behavior `Shift+LeftClick` or `Ctrl+Shift+LeftClick` on links opens a new window and never loads. ### Testcase Gist URL https://gist.github.com/samuelmaddock/d8e8c64c5143df9b3493592c75fa33b8 ### Additional Information Bug initially introduced in v18.0.0-alpha.1
https://github.com/electron/electron/issues/34152
https://github.com/electron/electron/pull/34159
6f8a36f4047ba6300f93d4470193d6b54afabacf
dd6ce91f5766c9eea0ffca23e42ef8766851e0a2
2022-05-09T21:13:02Z
c++
2022-05-11T18:34:33Z
spec-main/fixtures/apps/open-new-window-from-link/index.html
closed
electron/electron
https://github.com/electron/electron
34,152
[Bug]: Non-default window dispositions fail to load initial URL
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 18.2.1 ### What operating system are you using? - Windows - macOS ### Operating System Version - Windows 10 21H2 - macOS 12.3.1 ### What arch are you using? x64 ### Last Known Working Electron version 17.4.3 ### Expected Behavior `Shift+LeftClick` (new-window) or `Ctrl+Shift+LeftClick` (foreground-tab) on links should open and load them in a new window. ### Actual Behavior `Shift+LeftClick` or `Ctrl+Shift+LeftClick` on links opens a new window and never loads. ### Testcase Gist URL https://gist.github.com/samuelmaddock/d8e8c64c5143df9b3493592c75fa33b8 ### Additional Information Bug initially introduced in v18.0.0-alpha.1
https://github.com/electron/electron/issues/34152
https://github.com/electron/electron/pull/34159
6f8a36f4047ba6300f93d4470193d6b54afabacf
dd6ce91f5766c9eea0ffca23e42ef8766851e0a2
2022-05-09T21:13:02Z
c++
2022-05-11T18:34:33Z
spec-main/fixtures/apps/open-new-window-from-link/main.js
closed
electron/electron
https://github.com/electron/electron
34,152
[Bug]: Non-default window dispositions fail to load initial URL
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 18.2.1 ### What operating system are you using? - Windows - macOS ### Operating System Version - Windows 10 21H2 - macOS 12.3.1 ### What arch are you using? x64 ### Last Known Working Electron version 17.4.3 ### Expected Behavior `Shift+LeftClick` (new-window) or `Ctrl+Shift+LeftClick` (foreground-tab) on links should open and load them in a new window. ### Actual Behavior `Shift+LeftClick` or `Ctrl+Shift+LeftClick` on links opens a new window and never loads. ### Testcase Gist URL https://gist.github.com/samuelmaddock/d8e8c64c5143df9b3493592c75fa33b8 ### Additional Information Bug initially introduced in v18.0.0-alpha.1
https://github.com/electron/electron/issues/34152
https://github.com/electron/electron/pull/34159
6f8a36f4047ba6300f93d4470193d6b54afabacf
dd6ce91f5766c9eea0ffca23e42ef8766851e0a2
2022-05-09T21:13:02Z
c++
2022-05-11T18:34:33Z
spec-main/fixtures/apps/open-new-window-from-link/new-window-page.html
closed
electron/electron
https://github.com/electron/electron
34,152
[Bug]: Non-default window dispositions fail to load initial URL
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 18.2.1 ### What operating system are you using? - Windows - macOS ### Operating System Version - Windows 10 21H2 - macOS 12.3.1 ### What arch are you using? x64 ### Last Known Working Electron version 17.4.3 ### Expected Behavior `Shift+LeftClick` (new-window) or `Ctrl+Shift+LeftClick` (foreground-tab) on links should open and load them in a new window. ### Actual Behavior `Shift+LeftClick` or `Ctrl+Shift+LeftClick` on links opens a new window and never loads. ### Testcase Gist URL https://gist.github.com/samuelmaddock/d8e8c64c5143df9b3493592c75fa33b8 ### Additional Information Bug initially introduced in v18.0.0-alpha.1
https://github.com/electron/electron/issues/34152
https://github.com/electron/electron/pull/34159
6f8a36f4047ba6300f93d4470193d6b54afabacf
dd6ce91f5766c9eea0ffca23e42ef8766851e0a2
2022-05-09T21:13:02Z
c++
2022-05-11T18:34:33Z
spec-main/fixtures/apps/open-new-window-from-link/package.json
closed
electron/electron
https://github.com/electron/electron
34,152
[Bug]: Non-default window dispositions fail to load initial URL
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 18.2.1 ### What operating system are you using? - Windows - macOS ### Operating System Version - Windows 10 21H2 - macOS 12.3.1 ### What arch are you using? x64 ### Last Known Working Electron version 17.4.3 ### Expected Behavior `Shift+LeftClick` (new-window) or `Ctrl+Shift+LeftClick` (foreground-tab) on links should open and load them in a new window. ### Actual Behavior `Shift+LeftClick` or `Ctrl+Shift+LeftClick` on links opens a new window and never loads. ### Testcase Gist URL https://gist.github.com/samuelmaddock/d8e8c64c5143df9b3493592c75fa33b8 ### Additional Information Bug initially introduced in v18.0.0-alpha.1
https://github.com/electron/electron/issues/34152
https://github.com/electron/electron/pull/34159
6f8a36f4047ba6300f93d4470193d6b54afabacf
dd6ce91f5766c9eea0ffca23e42ef8766851e0a2
2022-05-09T21:13:02Z
c++
2022-05-11T18:34:33Z
spec-main/fixtures/apps/open-new-window-from-link/preload.js
closed
electron/electron
https://github.com/electron/electron
34,163
[Bug]: When Attempting to load extension with missing files, Electron Crashes.
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 18.0.3 ### What operating system are you using? macOS ### Operating System Version macOS Monterey, Ubuntu ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior When loading an extension extension with missing files, Electron should not crash. ### Actual Behavior When loading an extension extension with missing files Electron crashes with "Electron exited with signal SIGTRAP." ### Testcase Gist URL https://gist.github.com/jzoss/7fd8ad289c4ebbefeb766ec4e4e2829b ### Additional Information When loaded an extension that malformed is some way Electron crashes. I first saw this when I was unable to zip an extension and some of the files were missing. I am able to recreate it by removed all the files in a extension directory but leaving all the directories. for example in this gist.. if you make a dir "fmkadmapgofadopljbjfkapdkoienihi" and add 3 directories "build", "icons", "popups" Electron will crash.
https://github.com/electron/electron/issues/34163
https://github.com/electron/electron/pull/34168
4f8a84360603230059ffc4ca5f90b60708cc4869
d67532ee9f836857bc43989fbb8376d1fe769a48
2022-05-10T21:15:23Z
c++
2022-05-11T20:41:06Z
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/content/app/resources/content_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", "//content/app/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/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/content/dev_ui_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", "$root_gen_dir/ui/resources/webui_resources.pak", "$target_gen_dir/electron_resources.pak", ] deps = [ "//chrome/browser:dev_ui_browser_resources", "//chrome/browser:resources", "//chrome/common:resources", "//components/resources", "//content:content_resources", "//content:dev_ui_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_generated_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/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}/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: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", "//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
34,163
[Bug]: When Attempting to load extension with missing files, Electron Crashes.
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 18.0.3 ### What operating system are you using? macOS ### Operating System Version macOS Monterey, Ubuntu ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior When loading an extension extension with missing files, Electron should not crash. ### Actual Behavior When loading an extension extension with missing files Electron crashes with "Electron exited with signal SIGTRAP." ### Testcase Gist URL https://gist.github.com/jzoss/7fd8ad289c4ebbefeb766ec4e4e2829b ### Additional Information When loaded an extension that malformed is some way Electron crashes. I first saw this when I was unable to zip an extension and some of the files were missing. I am able to recreate it by removed all the files in a extension directory but leaving all the directories. for example in this gist.. if you make a dir "fmkadmapgofadopljbjfkapdkoienihi" and add 3 directories "build", "icons", "popups" Electron will crash.
https://github.com/electron/electron/issues/34163
https://github.com/electron/electron/pull/34168
4f8a84360603230059ffc4ca5f90b60708cc4869
d67532ee9f836857bc43989fbb8376d1fe769a48
2022-05-10T21:15:23Z
c++
2022-05-11T20:41:06Z
spec-main/extensions-spec.ts
import { expect } from 'chai'; import { app, session, BrowserWindow, ipcMain, WebContents, Extension, Session } from 'electron/main'; import { closeAllWindows, closeWindow } from './window-helpers'; import * as http from 'http'; import { AddressInfo } from 'net'; import * as path from 'path'; import * as fs from 'fs'; import * as WebSocket from 'ws'; import { emittedOnce, emittedNTimes, emittedUntil } from './events-helpers'; import { ifit } from './spec-helpers'; 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: string; 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'); } }); }); await new Promise<void>(resolve => server.listen(0, '127.0.0.1', () => { port = String((server.address() as AddressInfo).port); url = `http://127.0.0.1:${port}`; resolve(); })); }); 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 = emittedOnce(app, 'web-contents-created'); 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 = emittedOnce(app, 'web-contents-created'); 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 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 = emittedOnce(customSession, 'extension-loaded'); const extension = await customSession.loadExtension(path.join(fixtures, 'extensions', 'red-bg')); const [, loadedExtension] = await loadedPromise; const [, readyExtension] = await emittedUntil(customSession, 'extension-ready', (event: Event, extension: Extension) => { return extension.name !== 'Chromium PDF Viewer' && extension.name !== 'CryptoTokenExtension'; }); expect(loadedExtension).to.deep.equal(extension); expect(readyExtension).to.deep.equal(extension); const unloadedPromise = emittedOnce(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 = emittedOnce(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 = emittedOnce(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 = emittedOnce(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 } }); 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 } }); 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 emittedOnce(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 emittedOnce(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 emittedOnce(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 = emittedOnce(w2.webContents, 'did-navigate'); const message = { method: 'update', args: [w2.webContents.id, { url }] }; w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`); const [,, responseString] = await emittedOnce(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 emittedOnce(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 = emittedOnce(app, 'web-contents-created'); const { id } = await customSession.loadExtension(path.join(fixtures, 'extensions', 'persistent-background-page')); const [, bgPageContents] = await promise; expect(bgPageContents.getType()).to.equal('backgroundPage'); await emittedOnce(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 = emittedOnce(app, 'web-contents-created'); 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 = emittedOnce(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(() => { removeAllExtensions(); return closeWindow(w).then(() => { 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); }); }); // TODO(nornagon): real extensions don't load on file: urls, so this // test needs to be updated to serve its content over http. describe.skip('supports "all_frames" option', () => { const contentScript = path.resolve(fixtures, 'extensions/content-script'); // 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)'; before(() => { 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.loadFile(path.join(contentScript, 'frame-with-frame.html')); 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); if (isMainFrame) { expect(result.disabledColor).to.equal(COLOR_BLUE); } else { expect(result.disabledColor).to.equal(COLOR_TRANSPARENT); // null color } }) ); }); }); }); }; 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,163
[Bug]: When Attempting to load extension with missing files, Electron Crashes.
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 18.0.3 ### What operating system are you using? macOS ### Operating System Version macOS Monterey, Ubuntu ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior When loading an extension extension with missing files, Electron should not crash. ### Actual Behavior When loading an extension extension with missing files Electron crashes with "Electron exited with signal SIGTRAP." ### Testcase Gist URL https://gist.github.com/jzoss/7fd8ad289c4ebbefeb766ec4e4e2829b ### Additional Information When loaded an extension that malformed is some way Electron crashes. I first saw this when I was unable to zip an extension and some of the files were missing. I am able to recreate it by removed all the files in a extension directory but leaving all the directories. for example in this gist.. if you make a dir "fmkadmapgofadopljbjfkapdkoienihi" and add 3 directories "build", "icons", "popups" Electron will crash.
https://github.com/electron/electron/issues/34163
https://github.com/electron/electron/pull/34168
4f8a84360603230059ffc4ca5f90b60708cc4869
d67532ee9f836857bc43989fbb8376d1fe769a48
2022-05-10T21:15:23Z
c++
2022-05-11T20:41:06Z
spec-main/fixtures/extensions/missing-manifest/main.js
closed
electron/electron
https://github.com/electron/electron
34,163
[Bug]: When Attempting to load extension with missing files, Electron Crashes.
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 18.0.3 ### What operating system are you using? macOS ### Operating System Version macOS Monterey, Ubuntu ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior When loading an extension extension with missing files, Electron should not crash. ### Actual Behavior When loading an extension extension with missing files Electron crashes with "Electron exited with signal SIGTRAP." ### Testcase Gist URL https://gist.github.com/jzoss/7fd8ad289c4ebbefeb766ec4e4e2829b ### Additional Information When loaded an extension that malformed is some way Electron crashes. I first saw this when I was unable to zip an extension and some of the files were missing. I am able to recreate it by removed all the files in a extension directory but leaving all the directories. for example in this gist.. if you make a dir "fmkadmapgofadopljbjfkapdkoienihi" and add 3 directories "build", "icons", "popups" Electron will crash.
https://github.com/electron/electron/issues/34163
https://github.com/electron/electron/pull/34168
4f8a84360603230059ffc4ca5f90b60708cc4869
d67532ee9f836857bc43989fbb8376d1fe769a48
2022-05-10T21:15:23Z
c++
2022-05-11T20:41:06Z
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/content/app/resources/content_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", "//content/app/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/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/content/dev_ui_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", "$root_gen_dir/ui/resources/webui_resources.pak", "$target_gen_dir/electron_resources.pak", ] deps = [ "//chrome/browser:dev_ui_browser_resources", "//chrome/browser:resources", "//chrome/common:resources", "//components/resources", "//content:content_resources", "//content:dev_ui_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_generated_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/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}/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: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", "//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
34,163
[Bug]: When Attempting to load extension with missing files, Electron Crashes.
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 18.0.3 ### What operating system are you using? macOS ### Operating System Version macOS Monterey, Ubuntu ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior When loading an extension extension with missing files, Electron should not crash. ### Actual Behavior When loading an extension extension with missing files Electron crashes with "Electron exited with signal SIGTRAP." ### Testcase Gist URL https://gist.github.com/jzoss/7fd8ad289c4ebbefeb766ec4e4e2829b ### Additional Information When loaded an extension that malformed is some way Electron crashes. I first saw this when I was unable to zip an extension and some of the files were missing. I am able to recreate it by removed all the files in a extension directory but leaving all the directories. for example in this gist.. if you make a dir "fmkadmapgofadopljbjfkapdkoienihi" and add 3 directories "build", "icons", "popups" Electron will crash.
https://github.com/electron/electron/issues/34163
https://github.com/electron/electron/pull/34168
4f8a84360603230059ffc4ca5f90b60708cc4869
d67532ee9f836857bc43989fbb8376d1fe769a48
2022-05-10T21:15:23Z
c++
2022-05-11T20:41:06Z
spec-main/extensions-spec.ts
import { expect } from 'chai'; import { app, session, BrowserWindow, ipcMain, WebContents, Extension, Session } from 'electron/main'; import { closeAllWindows, closeWindow } from './window-helpers'; import * as http from 'http'; import { AddressInfo } from 'net'; import * as path from 'path'; import * as fs from 'fs'; import * as WebSocket from 'ws'; import { emittedOnce, emittedNTimes, emittedUntil } from './events-helpers'; import { ifit } from './spec-helpers'; 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: string; 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'); } }); }); await new Promise<void>(resolve => server.listen(0, '127.0.0.1', () => { port = String((server.address() as AddressInfo).port); url = `http://127.0.0.1:${port}`; resolve(); })); }); 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 = emittedOnce(app, 'web-contents-created'); 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 = emittedOnce(app, 'web-contents-created'); 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 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 = emittedOnce(customSession, 'extension-loaded'); const extension = await customSession.loadExtension(path.join(fixtures, 'extensions', 'red-bg')); const [, loadedExtension] = await loadedPromise; const [, readyExtension] = await emittedUntil(customSession, 'extension-ready', (event: Event, extension: Extension) => { return extension.name !== 'Chromium PDF Viewer' && extension.name !== 'CryptoTokenExtension'; }); expect(loadedExtension).to.deep.equal(extension); expect(readyExtension).to.deep.equal(extension); const unloadedPromise = emittedOnce(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 = emittedOnce(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 = emittedOnce(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 = emittedOnce(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 } }); 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 } }); 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 emittedOnce(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 emittedOnce(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 emittedOnce(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 = emittedOnce(w2.webContents, 'did-navigate'); const message = { method: 'update', args: [w2.webContents.id, { url }] }; w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`); const [,, responseString] = await emittedOnce(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 emittedOnce(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 = emittedOnce(app, 'web-contents-created'); const { id } = await customSession.loadExtension(path.join(fixtures, 'extensions', 'persistent-background-page')); const [, bgPageContents] = await promise; expect(bgPageContents.getType()).to.equal('backgroundPage'); await emittedOnce(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 = emittedOnce(app, 'web-contents-created'); 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 = emittedOnce(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(() => { removeAllExtensions(); return closeWindow(w).then(() => { 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); }); }); // TODO(nornagon): real extensions don't load on file: urls, so this // test needs to be updated to serve its content over http. describe.skip('supports "all_frames" option', () => { const contentScript = path.resolve(fixtures, 'extensions/content-script'); // 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)'; before(() => { 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.loadFile(path.join(contentScript, 'frame-with-frame.html')); 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); if (isMainFrame) { expect(result.disabledColor).to.equal(COLOR_BLUE); } else { expect(result.disabledColor).to.equal(COLOR_TRANSPARENT); // null color } }) ); }); }); }); }; 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,163
[Bug]: When Attempting to load extension with missing files, Electron Crashes.
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 18.0.3 ### What operating system are you using? macOS ### Operating System Version macOS Monterey, Ubuntu ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior When loading an extension extension with missing files, Electron should not crash. ### Actual Behavior When loading an extension extension with missing files Electron crashes with "Electron exited with signal SIGTRAP." ### Testcase Gist URL https://gist.github.com/jzoss/7fd8ad289c4ebbefeb766ec4e4e2829b ### Additional Information When loaded an extension that malformed is some way Electron crashes. I first saw this when I was unable to zip an extension and some of the files were missing. I am able to recreate it by removed all the files in a extension directory but leaving all the directories. for example in this gist.. if you make a dir "fmkadmapgofadopljbjfkapdkoienihi" and add 3 directories "build", "icons", "popups" Electron will crash.
https://github.com/electron/electron/issues/34163
https://github.com/electron/electron/pull/34168
4f8a84360603230059ffc4ca5f90b60708cc4869
d67532ee9f836857bc43989fbb8376d1fe769a48
2022-05-10T21:15:23Z
c++
2022-05-11T20:41:06Z
spec-main/fixtures/extensions/missing-manifest/main.js
closed
electron/electron
https://github.com/electron/electron
32,111
[Bug]: Menu.buildFromTemplate([]); click tray icon is not highlight
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Electron Version 16.0.1 ### What operating system are you using? macOS ### Operating System Version macOS 11.5.2 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior Menu.buildFromTemplate([]), click tray icon is hightlight ### Actual Behavior Menu.buildFromTemplate([]), click tray icon is not hightlight ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/32111
https://github.com/electron/electron/pull/34173
142e1f667bff0ae755406876295205708a4cd887
a8103691ac33b6a71e127532cdea26d2de12d708
2021-12-06T05:57:41Z
c++
2022-05-12T14:14:11Z
shell/browser/ui/tray_icon_cocoa.mm
// Copyright (c) 2014 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/ui/tray_icon_cocoa.h" #include <string> #include <vector> #include "base/message_loop/message_pump_mac.h" #include "base/strings/sys_string_conversions.h" #include "base/task/current_thread.h" #include "base/task/post_task.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "shell/browser/ui/cocoa/NSString+ANSI.h" #include "shell/browser/ui/cocoa/electron_menu_controller.h" #include "ui/events/cocoa/cocoa_event_utils.h" #include "ui/gfx/mac/coordinate_conversion.h" #include "ui/native_theme/native_theme.h" @interface StatusItemView : NSView { electron::TrayIconCocoa* trayIcon_; // weak ElectronMenuController* menuController_; // weak BOOL ignoreDoubleClickEvents_; base::scoped_nsobject<NSStatusItem> statusItem_; base::scoped_nsobject<NSTrackingArea> trackingArea_; } @end // @interface StatusItemView @implementation StatusItemView - (void)dealloc { trayIcon_ = nil; menuController_ = nil; [super dealloc]; } - (id)initWithIcon:(electron::TrayIconCocoa*)icon { trayIcon_ = icon; menuController_ = nil; ignoreDoubleClickEvents_ = NO; if ((self = [super initWithFrame:CGRectZero])) { [self registerForDraggedTypes:@[ NSFilenamesPboardType, NSStringPboardType, ]]; // Create the status item. NSStatusItem* item = [[NSStatusBar systemStatusBar] statusItemWithLength:NSVariableStatusItemLength]; statusItem_.reset([item retain]); [[statusItem_ button] addSubview:self]; // inject custom view [self updateDimensions]; } return self; } - (void)updateDimensions { [self setFrame:[statusItem_ button].frame]; } - (void)updateTrackingAreas { // Use NSTrackingArea for listening to mouseEnter, mouseExit, and mouseMove // events. [self removeTrackingArea:trackingArea_]; trackingArea_.reset([[NSTrackingArea alloc] initWithRect:[self bounds] options:NSTrackingMouseEnteredAndExited | NSTrackingMouseMoved | NSTrackingActiveAlways owner:self userInfo:nil]); [self addTrackingArea:trackingArea_]; } - (void)removeItem { // Turn off tracking events to prevent crash. if (trackingArea_) { [self removeTrackingArea:trackingArea_]; trackingArea_.reset(); } [[NSStatusBar systemStatusBar] removeStatusItem:statusItem_]; [self removeFromSuperview]; statusItem_.reset(); } - (void)setImage:(NSImage*)image { [[statusItem_ button] setImage:image]; [self updateDimensions]; } - (void)setAlternateImage:(NSImage*)image { [[statusItem_ button] setAlternateImage:image]; // 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"]) { if (@available(macOS 10.15, *)) { NSDictionary* attributes = @{ NSFontAttributeName : [NSFont monospacedSystemFontOfSize:existing_size weight:NSFontWeightRegular] }; [attributed_title addAttributes:attributes range:NSMakeRange(0, [attributed_title length])]; } } else if ([font_type isEqualToString:@"monospacedDigit"]) { NSDictionary* attributes = @{ NSFontAttributeName : [NSFont monospacedDigitSystemFontOfSize:existing_size weight:NSFontWeightRegular] }; [attributed_title addAttributes:attributes range:NSMakeRange(0, [attributed_title length])]; } // Set title [[statusItem_ button] setAttributedTitle:attributed_title]; // Fix icon margins. if (title.length > 0) { [[statusItem_ button] setImagePosition:NSImageLeft]; } else { [[statusItem_ button] setImagePosition:NSImageOnly]; } [self updateDimensions]; } - (NSString*)title { return [statusItem_ button].title; } - (void)setMenuController:(ElectronMenuController*)menu { menuController_ = menu; [statusItem_ setMenu:[menuController_ menu]]; } - (void)handleClickNotifications:(NSEvent*)event { // If we are ignoring double click events, we should ignore the `clickCount` // value and immediately emit a click event. BOOL shouldBeHandledAsASingleClick = (event.clickCount == 1) || ignoreDoubleClickEvents_; if (shouldBeHandledAsASingleClick) trayIcon_->NotifyClicked( gfx::ScreenRectFromNSRect(event.window.frame), gfx::ScreenPointFromNSPoint([event locationInWindow]), ui::EventFlagsFromModifiers([event modifierFlags])); // Double click event. BOOL shouldBeHandledAsADoubleClick = (event.clickCount == 2) && !ignoreDoubleClickEvents_; if (shouldBeHandledAsADoubleClick) trayIcon_->NotifyDoubleClicked( gfx::ScreenRectFromNSRect(event.window.frame), ui::EventFlagsFromModifiers([event modifierFlags])); } - (void)mouseDown:(NSEvent*)event { trayIcon_->NotifyMouseDown( gfx::ScreenPointFromNSPoint([event locationInWindow]), ui::EventFlagsFromModifiers([event modifierFlags])); // Pass click to superclass to show menu. Custom mouseUp handler won't be // invoked. if (menuController_) { [self handleClickNotifications:event]; [super mouseDown:event]; } else { [[statusItem_ button] highlight:YES]; } } - (void)mouseUp:(NSEvent*)event { [[statusItem_ button] highlight:NO]; trayIcon_->NotifyMouseUp( gfx::ScreenPointFromNSPoint([event locationInWindow]), ui::EventFlagsFromModifiers([event modifierFlags])); [self handleClickNotifications:event]; } - (void)popUpContextMenu:(electron::ElectronMenuModel*)menu_model { // Make sure events can be pumped while the menu is up. base::CurrentThread::ScopedNestableTaskAllower allow; // Show a custom menu. if (menu_model) { base::scoped_nsobject<ElectronMenuController> menuController( [[ElectronMenuController alloc] initWithModel:menu_model useDefaultAccelerator:NO]); // Hacky way to mimic design of ordinary tray menu. [statusItem_ setMenu:[menuController menu]]; // -performClick: is a blocking call, which will run the task loop inside // itself. This can potentially include running JS, which can result in // this object being released. We take a temporary reference here to make // sure we stay alive long enough to successfully return from this // function. // TODO(nornagon/codebytere): Avoid nesting task loops here. [self retain]; [[statusItem_ button] performClick:self]; [statusItem_ setMenu:[menuController_ menu]]; [self release]; return; } if (menuController_ && ![menuController_ isMenuOpen]) { // Ensure the UI can update while the menu is fading out. base::ScopedPumpMessagesInPrivateModes pump_private; [[statusItem_ button] performClick:self]; } } - (void)closeContextMenu { if (menuController_) { [menuController_ cancel]; } } - (void)rightMouseUp:(NSEvent*)event { trayIcon_->NotifyRightClicked( gfx::ScreenRectFromNSRect(event.window.frame), ui::EventFlagsFromModifiers([event modifierFlags])); } - (NSDragOperation)draggingEntered:(id<NSDraggingInfo>)sender { trayIcon_->NotifyDragEntered(); return NSDragOperationCopy; } - (void)mouseExited:(NSEvent*)event { trayIcon_->NotifyMouseExited( gfx::ScreenPointFromNSPoint([event locationInWindow]), ui::EventFlagsFromModifiers([event modifierFlags])); } - (void)mouseEntered:(NSEvent*)event { trayIcon_->NotifyMouseEntered( gfx::ScreenPointFromNSPoint([event locationInWindow]), ui::EventFlagsFromModifiers([event modifierFlags])); } - (void)mouseMoved:(NSEvent*)event { trayIcon_->NotifyMouseMoved( gfx::ScreenPointFromNSPoint([event locationInWindow]), ui::EventFlagsFromModifiers([event modifierFlags])); } - (void)draggingExited:(id<NSDraggingInfo>)sender { trayIcon_->NotifyDragExited(); } - (void)draggingEnded:(id<NSDraggingInfo>)sender { trayIcon_->NotifyDragEnded(); if (NSPointInRect([sender draggingLocation], self.frame)) { trayIcon_->NotifyDrop(); } } - (BOOL)handleDrop:(id<NSDraggingInfo>)sender { NSPasteboard* pboard = [sender draggingPasteboard]; if ([[pboard types] containsObject:NSFilenamesPboardType]) { std::vector<std::string> dropFiles; NSArray* files = [pboard propertyListForType:NSFilenamesPboardType]; for (NSString* file in files) dropFiles.push_back(base::SysNSStringToUTF8(file)); trayIcon_->NotifyDropFiles(dropFiles); return YES; } else if ([[pboard types] containsObject:NSStringPboardType]) { NSString* dropText = [pboard stringForType:NSStringPboardType]; trayIcon_->NotifyDropText(base::SysNSStringToUTF8(dropText)); return YES; } return NO; } - (BOOL)prepareForDragOperation:(id<NSDraggingInfo>)sender { return YES; } - (BOOL)performDragOperation:(id<NSDraggingInfo>)sender { [self handleDrop:sender]; return YES; } @end namespace electron { TrayIconCocoa::TrayIconCocoa() { status_item_view_.reset([[StatusItemView alloc] initWithIcon:this]); } TrayIconCocoa::~TrayIconCocoa() { [status_item_view_ removeItem]; } void TrayIconCocoa::SetImage(const gfx::Image& image) { [status_item_view_ setImage:image.AsNSImage()]; } void TrayIconCocoa::SetPressedImage(const gfx::Image& image) { [status_item_view_ setAlternateImage:image.AsNSImage()]; } void TrayIconCocoa::SetToolTip(const std::string& tool_tip) { [status_item_view_ setToolTip:base::SysUTF8ToNSString(tool_tip)]; } void TrayIconCocoa::SetTitle(const std::string& title, const TitleOptions& options) { [status_item_view_ setTitle:base::SysUTF8ToNSString(title) font_type:base::SysUTF8ToNSString(options.font_type)]; } std::string TrayIconCocoa::GetTitle() { return base::SysNSStringToUTF8([status_item_view_ title]); } void TrayIconCocoa::SetIgnoreDoubleClickEvents(bool ignore) { [status_item_view_ setIgnoreDoubleClickEvents:ignore]; } bool TrayIconCocoa::GetIgnoreDoubleClickEvents() { return [status_item_view_ getIgnoreDoubleClickEvents]; } void TrayIconCocoa::PopUpOnUI(ElectronMenuModel* menu_model) { [status_item_view_ popUpContextMenu:menu_model]; } void TrayIconCocoa::PopUpContextMenu(const gfx::Point& pos, ElectronMenuModel* menu_model) { base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&TrayIconCocoa::PopUpOnUI, weak_factory_.GetWeakPtr(), base::Unretained(menu_model))); } void TrayIconCocoa::CloseContextMenu() { [status_item_view_ closeContextMenu]; } void TrayIconCocoa::SetContextMenu(ElectronMenuModel* menu_model) { if (menu_model) { // Create native menu. menu_.reset([[ElectronMenuController alloc] initWithModel:menu_model useDefaultAccelerator:NO]); } else { menu_.reset(); } [status_item_view_ setMenuController:menu_.get()]; } gfx::Rect TrayIconCocoa::GetBounds() { return gfx::ScreenRectFromNSRect([status_item_view_ window].frame); } // static TrayIcon* TrayIcon::Create(absl::optional<UUID> guid) { return new TrayIconCocoa; } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
32,111
[Bug]: Menu.buildFromTemplate([]); click tray icon is not highlight
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Electron Version 16.0.1 ### What operating system are you using? macOS ### Operating System Version macOS 11.5.2 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior Menu.buildFromTemplate([]), click tray icon is hightlight ### Actual Behavior Menu.buildFromTemplate([]), click tray icon is not hightlight ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/32111
https://github.com/electron/electron/pull/34173
142e1f667bff0ae755406876295205708a4cd887
a8103691ac33b6a71e127532cdea26d2de12d708
2021-12-06T05:57:41Z
c++
2022-05-12T14:14:11Z
shell/browser/ui/tray_icon_cocoa.mm
// Copyright (c) 2014 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/ui/tray_icon_cocoa.h" #include <string> #include <vector> #include "base/message_loop/message_pump_mac.h" #include "base/strings/sys_string_conversions.h" #include "base/task/current_thread.h" #include "base/task/post_task.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "shell/browser/ui/cocoa/NSString+ANSI.h" #include "shell/browser/ui/cocoa/electron_menu_controller.h" #include "ui/events/cocoa/cocoa_event_utils.h" #include "ui/gfx/mac/coordinate_conversion.h" #include "ui/native_theme/native_theme.h" @interface StatusItemView : NSView { electron::TrayIconCocoa* trayIcon_; // weak ElectronMenuController* menuController_; // weak BOOL ignoreDoubleClickEvents_; base::scoped_nsobject<NSStatusItem> statusItem_; base::scoped_nsobject<NSTrackingArea> trackingArea_; } @end // @interface StatusItemView @implementation StatusItemView - (void)dealloc { trayIcon_ = nil; menuController_ = nil; [super dealloc]; } - (id)initWithIcon:(electron::TrayIconCocoa*)icon { trayIcon_ = icon; menuController_ = nil; ignoreDoubleClickEvents_ = NO; if ((self = [super initWithFrame:CGRectZero])) { [self registerForDraggedTypes:@[ NSFilenamesPboardType, NSStringPboardType, ]]; // Create the status item. NSStatusItem* item = [[NSStatusBar systemStatusBar] statusItemWithLength:NSVariableStatusItemLength]; statusItem_.reset([item retain]); [[statusItem_ button] addSubview:self]; // inject custom view [self updateDimensions]; } return self; } - (void)updateDimensions { [self setFrame:[statusItem_ button].frame]; } - (void)updateTrackingAreas { // Use NSTrackingArea for listening to mouseEnter, mouseExit, and mouseMove // events. [self removeTrackingArea:trackingArea_]; trackingArea_.reset([[NSTrackingArea alloc] initWithRect:[self bounds] options:NSTrackingMouseEnteredAndExited | NSTrackingMouseMoved | NSTrackingActiveAlways owner:self userInfo:nil]); [self addTrackingArea:trackingArea_]; } - (void)removeItem { // Turn off tracking events to prevent crash. if (trackingArea_) { [self removeTrackingArea:trackingArea_]; trackingArea_.reset(); } [[NSStatusBar systemStatusBar] removeStatusItem:statusItem_]; [self removeFromSuperview]; statusItem_.reset(); } - (void)setImage:(NSImage*)image { [[statusItem_ button] setImage:image]; [self updateDimensions]; } - (void)setAlternateImage:(NSImage*)image { [[statusItem_ button] setAlternateImage:image]; // 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"]) { if (@available(macOS 10.15, *)) { NSDictionary* attributes = @{ NSFontAttributeName : [NSFont monospacedSystemFontOfSize:existing_size weight:NSFontWeightRegular] }; [attributed_title addAttributes:attributes range:NSMakeRange(0, [attributed_title length])]; } } else if ([font_type isEqualToString:@"monospacedDigit"]) { NSDictionary* attributes = @{ NSFontAttributeName : [NSFont monospacedDigitSystemFontOfSize:existing_size weight:NSFontWeightRegular] }; [attributed_title addAttributes:attributes range:NSMakeRange(0, [attributed_title length])]; } // Set title [[statusItem_ button] setAttributedTitle:attributed_title]; // Fix icon margins. if (title.length > 0) { [[statusItem_ button] setImagePosition:NSImageLeft]; } else { [[statusItem_ button] setImagePosition:NSImageOnly]; } [self updateDimensions]; } - (NSString*)title { return [statusItem_ button].title; } - (void)setMenuController:(ElectronMenuController*)menu { menuController_ = menu; [statusItem_ setMenu:[menuController_ menu]]; } - (void)handleClickNotifications:(NSEvent*)event { // If we are ignoring double click events, we should ignore the `clickCount` // value and immediately emit a click event. BOOL shouldBeHandledAsASingleClick = (event.clickCount == 1) || ignoreDoubleClickEvents_; if (shouldBeHandledAsASingleClick) trayIcon_->NotifyClicked( gfx::ScreenRectFromNSRect(event.window.frame), gfx::ScreenPointFromNSPoint([event locationInWindow]), ui::EventFlagsFromModifiers([event modifierFlags])); // Double click event. BOOL shouldBeHandledAsADoubleClick = (event.clickCount == 2) && !ignoreDoubleClickEvents_; if (shouldBeHandledAsADoubleClick) trayIcon_->NotifyDoubleClicked( gfx::ScreenRectFromNSRect(event.window.frame), ui::EventFlagsFromModifiers([event modifierFlags])); } - (void)mouseDown:(NSEvent*)event { trayIcon_->NotifyMouseDown( gfx::ScreenPointFromNSPoint([event locationInWindow]), ui::EventFlagsFromModifiers([event modifierFlags])); // Pass click to superclass to show menu. Custom mouseUp handler won't be // invoked. if (menuController_) { [self handleClickNotifications:event]; [super mouseDown:event]; } else { [[statusItem_ button] highlight:YES]; } } - (void)mouseUp:(NSEvent*)event { [[statusItem_ button] highlight:NO]; trayIcon_->NotifyMouseUp( gfx::ScreenPointFromNSPoint([event locationInWindow]), ui::EventFlagsFromModifiers([event modifierFlags])); [self handleClickNotifications:event]; } - (void)popUpContextMenu:(electron::ElectronMenuModel*)menu_model { // Make sure events can be pumped while the menu is up. base::CurrentThread::ScopedNestableTaskAllower allow; // Show a custom menu. if (menu_model) { base::scoped_nsobject<ElectronMenuController> menuController( [[ElectronMenuController alloc] initWithModel:menu_model useDefaultAccelerator:NO]); // Hacky way to mimic design of ordinary tray menu. [statusItem_ setMenu:[menuController menu]]; // -performClick: is a blocking call, which will run the task loop inside // itself. This can potentially include running JS, which can result in // this object being released. We take a temporary reference here to make // sure we stay alive long enough to successfully return from this // function. // TODO(nornagon/codebytere): Avoid nesting task loops here. [self retain]; [[statusItem_ button] performClick:self]; [statusItem_ setMenu:[menuController_ menu]]; [self release]; return; } if (menuController_ && ![menuController_ isMenuOpen]) { // Ensure the UI can update while the menu is fading out. base::ScopedPumpMessagesInPrivateModes pump_private; [[statusItem_ button] performClick:self]; } } - (void)closeContextMenu { if (menuController_) { [menuController_ cancel]; } } - (void)rightMouseUp:(NSEvent*)event { trayIcon_->NotifyRightClicked( gfx::ScreenRectFromNSRect(event.window.frame), ui::EventFlagsFromModifiers([event modifierFlags])); } - (NSDragOperation)draggingEntered:(id<NSDraggingInfo>)sender { trayIcon_->NotifyDragEntered(); return NSDragOperationCopy; } - (void)mouseExited:(NSEvent*)event { trayIcon_->NotifyMouseExited( gfx::ScreenPointFromNSPoint([event locationInWindow]), ui::EventFlagsFromModifiers([event modifierFlags])); } - (void)mouseEntered:(NSEvent*)event { trayIcon_->NotifyMouseEntered( gfx::ScreenPointFromNSPoint([event locationInWindow]), ui::EventFlagsFromModifiers([event modifierFlags])); } - (void)mouseMoved:(NSEvent*)event { trayIcon_->NotifyMouseMoved( gfx::ScreenPointFromNSPoint([event locationInWindow]), ui::EventFlagsFromModifiers([event modifierFlags])); } - (void)draggingExited:(id<NSDraggingInfo>)sender { trayIcon_->NotifyDragExited(); } - (void)draggingEnded:(id<NSDraggingInfo>)sender { trayIcon_->NotifyDragEnded(); if (NSPointInRect([sender draggingLocation], self.frame)) { trayIcon_->NotifyDrop(); } } - (BOOL)handleDrop:(id<NSDraggingInfo>)sender { NSPasteboard* pboard = [sender draggingPasteboard]; if ([[pboard types] containsObject:NSFilenamesPboardType]) { std::vector<std::string> dropFiles; NSArray* files = [pboard propertyListForType:NSFilenamesPboardType]; for (NSString* file in files) dropFiles.push_back(base::SysNSStringToUTF8(file)); trayIcon_->NotifyDropFiles(dropFiles); return YES; } else if ([[pboard types] containsObject:NSStringPboardType]) { NSString* dropText = [pboard stringForType:NSStringPboardType]; trayIcon_->NotifyDropText(base::SysNSStringToUTF8(dropText)); return YES; } return NO; } - (BOOL)prepareForDragOperation:(id<NSDraggingInfo>)sender { return YES; } - (BOOL)performDragOperation:(id<NSDraggingInfo>)sender { [self handleDrop:sender]; return YES; } @end namespace electron { TrayIconCocoa::TrayIconCocoa() { status_item_view_.reset([[StatusItemView alloc] initWithIcon:this]); } TrayIconCocoa::~TrayIconCocoa() { [status_item_view_ removeItem]; } void TrayIconCocoa::SetImage(const gfx::Image& image) { [status_item_view_ setImage:image.AsNSImage()]; } void TrayIconCocoa::SetPressedImage(const gfx::Image& image) { [status_item_view_ setAlternateImage:image.AsNSImage()]; } void TrayIconCocoa::SetToolTip(const std::string& tool_tip) { [status_item_view_ setToolTip:base::SysUTF8ToNSString(tool_tip)]; } void TrayIconCocoa::SetTitle(const std::string& title, const TitleOptions& options) { [status_item_view_ setTitle:base::SysUTF8ToNSString(title) font_type:base::SysUTF8ToNSString(options.font_type)]; } std::string TrayIconCocoa::GetTitle() { return base::SysNSStringToUTF8([status_item_view_ title]); } void TrayIconCocoa::SetIgnoreDoubleClickEvents(bool ignore) { [status_item_view_ setIgnoreDoubleClickEvents:ignore]; } bool TrayIconCocoa::GetIgnoreDoubleClickEvents() { return [status_item_view_ getIgnoreDoubleClickEvents]; } void TrayIconCocoa::PopUpOnUI(ElectronMenuModel* menu_model) { [status_item_view_ popUpContextMenu:menu_model]; } void TrayIconCocoa::PopUpContextMenu(const gfx::Point& pos, ElectronMenuModel* menu_model) { base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&TrayIconCocoa::PopUpOnUI, weak_factory_.GetWeakPtr(), base::Unretained(menu_model))); } void TrayIconCocoa::CloseContextMenu() { [status_item_view_ closeContextMenu]; } void TrayIconCocoa::SetContextMenu(ElectronMenuModel* menu_model) { if (menu_model) { // Create native menu. menu_.reset([[ElectronMenuController alloc] initWithModel:menu_model useDefaultAccelerator:NO]); } else { menu_.reset(); } [status_item_view_ setMenuController:menu_.get()]; } gfx::Rect TrayIconCocoa::GetBounds() { return gfx::ScreenRectFromNSRect([status_item_view_ window].frame); } // static TrayIcon* TrayIcon::Create(absl::optional<UUID> guid) { return new TrayIconCocoa; } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
34,137
[Bug]: Crash on Windows when calling `win.setTitleBarOverlay` on a window that has `titleBarStyle != 'hidden'`
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 18.2.0 ### What operating system are you using? Windows ### Operating System Version Windows 10 version 20H2, build 19042 ### What arch are you using? x64 ### Last Known Working Electron version 18.1.0 ### Expected Behavior When `win.setTitleBarOverlay` is called, apparently the only valid option for `titleBarStyle` is `'hidden'`. So when `win` was created with `titleBarStyle` different from `'hidden'`, Electron should throw an error. ### Actual Behavior Electron crashes unexpectedly. ### Testcase Gist URL https://gist.github.com/wheezard/207499979a7fda8cc7d874fdb87886fc ### Additional Information This might work on older versions, but I haven't tested it in them.
https://github.com/electron/electron/issues/34137
https://github.com/electron/electron/pull/34140
4e3587c7c6e051193c6bbe346192ff08d2b594c1
97c9451efc3035a1072b1ff87aee125f7a9fa053
2022-05-08T18:34:46Z
c++
2022-05-17T15:50:27Z
shell/browser/ui/views/win_frame_view.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. // // Portions of this file are sourced from // chrome/browser/ui/views/frame/glass_browser_frame_view.cc, // Copyright (c) 2012 The Chromium Authors, // which is governed by a BSD-style license #include "shell/browser/ui/views/win_frame_view.h" #include <dwmapi.h> #include <memory> #include "base/win/windows_version.h" #include "shell/browser/native_window_views.h" #include "shell/browser/ui/views/win_caption_button_container.h" #include "ui/base/win/hwnd_metrics.h" #include "ui/display/win/dpi.h" #include "ui/display/win/screen_win.h" #include "ui/gfx/geometry/dip_util.h" #include "ui/views/widget/widget.h" #include "ui/views/win/hwnd_util.h" namespace electron { const char WinFrameView::kViewClassName[] = "WinFrameView"; WinFrameView::WinFrameView() = default; WinFrameView::~WinFrameView() = default; void WinFrameView::Init(NativeWindowViews* window, views::Widget* frame) { window_ = window; frame_ = frame; if (window->IsWindowControlsOverlayEnabled()) { caption_button_container_ = AddChildView(std::make_unique<WinCaptionButtonContainer>(this)); } else { caption_button_container_ = nullptr; } } SkColor WinFrameView::GetReadableFeatureColor(SkColor background_color) { // color_utils::GetColorWithMaxContrast()/IsDark() aren't used here because // they switch based on the Chrome light/dark endpoints, while we want to use // the system native behavior below. const auto windows_luma = [](SkColor c) { return 0.25f * SkColorGetR(c) + 0.625f * SkColorGetG(c) + 0.125f * SkColorGetB(c); }; return windows_luma(background_color) <= 128.0f ? SK_ColorWHITE : SK_ColorBLACK; } void WinFrameView::InvalidateCaptionButtons() { // Ensure that the caption buttons container exists DCHECK(caption_button_container_); caption_button_container_->InvalidateLayout(); caption_button_container_->SchedulePaint(); } gfx::Rect WinFrameView::GetWindowBoundsForClientBounds( const gfx::Rect& client_bounds) const { return views::GetWindowBoundsForClientBounds( static_cast<views::View*>(const_cast<WinFrameView*>(this)), client_bounds); } int WinFrameView::FrameBorderThickness() const { return (IsMaximized() || frame()->IsFullscreen()) ? 0 : display::win::ScreenWin::GetSystemMetricsInDIP(SM_CXSIZEFRAME); } views::View* WinFrameView::TargetForRect(views::View* root, const gfx::Rect& rect) { if (NonClientHitTest(rect.origin()) != HTCLIENT) { // Custom system titlebar returns non HTCLIENT value, however event should // be handled by the view, not by the system, because there are no system // buttons underneath. if (!ShouldCustomDrawSystemTitlebar()) { return this; } auto local_point = rect.origin(); ConvertPointToTarget(parent(), caption_button_container_, &local_point); if (!caption_button_container_->HitTestPoint(local_point)) { return this; } } return NonClientFrameView::TargetForRect(root, rect); } int WinFrameView::NonClientHitTest(const gfx::Point& point) { if (window_->has_frame()) return frame_->client_view()->NonClientHitTest(point); if (ShouldCustomDrawSystemTitlebar()) { // See if the point is within any of the window controls. if (caption_button_container_) { gfx::Point local_point = point; ConvertPointToTarget(parent(), caption_button_container_, &local_point); if (caption_button_container_->HitTestPoint(local_point)) { const int hit_test_result = caption_button_container_->NonClientHitTest(local_point); if (hit_test_result != HTNOWHERE) return hit_test_result; } } // On Windows 8+, the caption buttons are almost butted up to the top right // corner of the window. This code ensures the mouse isn't set to a size // cursor while hovering over the caption buttons, thus giving the incorrect // impression that the user can resize the window. if (base::win::GetVersion() >= base::win::Version::WIN8) { RECT button_bounds = {0}; if (SUCCEEDED(DwmGetWindowAttribute( views::HWNDForWidget(frame()), DWMWA_CAPTION_BUTTON_BOUNDS, &button_bounds, sizeof(button_bounds)))) { gfx::RectF button_bounds_in_dips = gfx::ConvertRectToDips( gfx::Rect(button_bounds), display::win::GetDPIScale()); // TODO(crbug.com/1131681): GetMirroredRect() requires an integer rect, // but the size in DIPs may not be an integer with a fractional device // scale factor. If we want to keep using integers, the choice to use // ToFlooredRectDeprecated() seems to be doing the wrong thing given the // comment below about insetting 1 DIP instead of 1 physical pixel. We // should probably use ToEnclosedRect() and then we could have inset 1 // physical pixel here. gfx::Rect buttons = GetMirroredRect( gfx::ToFlooredRectDeprecated(button_bounds_in_dips)); // There is a small one-pixel strip right above the caption buttons in // which the resize border "peeks" through. constexpr int kCaptionButtonTopInset = 1; // The sizing region at the window edge above the caption buttons is // 1 px regardless of scale factor. If we inset by 1 before converting // to DIPs, the precision loss might eliminate this region entirely. The // best we can do is to inset after conversion. This guarantees we'll // show the resize cursor when resizing is possible. The cost of which // is also maybe showing it over the portion of the DIP that isn't the // outermost pixel. buttons.Inset(gfx::Insets::TLBR(0, kCaptionButtonTopInset, 0, 0)); if (buttons.Contains(point)) return HTNOWHERE; } } int top_border_thickness = FrameTopBorderThickness(false); // At the window corners the resize area is not actually bigger, but the 16 // pixels at the end of the top and bottom edges trigger diagonal resizing. constexpr int kResizeCornerWidth = 16; int window_component = GetHTComponentForFrame( point, gfx::Insets::TLBR(top_border_thickness, 0, 0, 0), top_border_thickness, kResizeCornerWidth - FrameBorderThickness(), frame()->widget_delegate()->CanResize()); if (window_component != HTNOWHERE) return window_component; } // Use the parent class's hittest last return FramelessView::NonClientHitTest(point); } const char* WinFrameView::GetClassName() const { return kViewClassName; } bool WinFrameView::IsMaximized() const { return frame()->IsMaximized(); } bool WinFrameView::ShouldCustomDrawSystemTitlebar() const { return window()->IsWindowControlsOverlayEnabled(); } void WinFrameView::Layout() { LayoutCaptionButtons(); if (window()->IsWindowControlsOverlayEnabled()) { LayoutWindowControlsOverlay(); } NonClientFrameView::Layout(); } int WinFrameView::FrameTopBorderThickness(bool restored) const { // Mouse and touch locations are floored but GetSystemMetricsInDIP is rounded, // so we need to floor instead or else the difference will cause the hittest // to fail when it ought to succeed. return std::floor( FrameTopBorderThicknessPx(restored) / display::win::ScreenWin::GetScaleFactorForHWND(HWNDForView(this))); } int WinFrameView::FrameTopBorderThicknessPx(bool restored) const { // Distinct from FrameBorderThickness() because we can't inset the top // border, otherwise Windows will give us a standard titlebar. // For maximized windows this is not true, and the top border must be // inset in order to avoid overlapping the monitor above. // See comments in BrowserDesktopWindowTreeHostWin::GetClientAreaInsets(). const bool needs_no_border = (ShouldCustomDrawSystemTitlebar() && frame()->IsMaximized()) || frame()->IsFullscreen(); if (needs_no_border && !restored) return 0; // Note that this method assumes an equal resize handle thickness on all // sides of the window. // TODO(dfried): Consider having it return a gfx::Insets object instead. return ui::GetFrameThickness( MonitorFromWindow(HWNDForView(this), MONITOR_DEFAULTTONEAREST)); } int WinFrameView::TitlebarMaximizedVisualHeight() const { int maximized_height = display::win::ScreenWin::GetSystemMetricsInDIP(SM_CYCAPTION); return maximized_height; } // NOTE(@mlaurencin): Usage of IsWebUITabStrip simplified out from Chromium int WinFrameView::TitlebarHeight(int custom_height) const { if (frame()->IsFullscreen() && !IsMaximized()) return 0; int height = TitlebarMaximizedVisualHeight() + FrameTopBorderThickness(false) - WindowTopY(); if (custom_height > TitlebarMaximizedVisualHeight()) height = custom_height - WindowTopY(); return height; } // NOTE(@mlaurencin): Usage of IsWebUITabStrip simplified out from Chromium int WinFrameView::WindowTopY() const { // The window top is SM_CYSIZEFRAME pixels when maximized (see the comment in // FrameTopBorderThickness()) and floor(system dsf) pixels when restored. // Unfortunately we can't represent either of those at hidpi without using // non-integral dips, so we return the closest reasonable values instead. if (IsMaximized()) return FrameTopBorderThickness(false); return 1; } void WinFrameView::LayoutCaptionButtons() { if (!caption_button_container_) return; // Non-custom system titlebar already contains caption buttons. if (!ShouldCustomDrawSystemTitlebar()) { caption_button_container_->SetVisible(false); return; } caption_button_container_->SetVisible(true); const gfx::Size preferred_size = caption_button_container_->GetPreferredSize(); int custom_height = window()->titlebar_overlay_height(); int height = TitlebarHeight(custom_height); // TODO(mlaurencin): This -1 creates a 1 pixel margin between the right // edge of the button container and the edge of the window, allowing for this // edge portion to return the correct hit test and be manually resized // properly. Alternatives can be explored, but the differences in view // structures between Electron and Chromium may result in this as the best // option. int variable_width = IsMaximized() ? preferred_size.width() : preferred_size.width() - 1; caption_button_container_->SetBounds(width() - preferred_size.width(), WindowTopY(), variable_width, height); // Needed for heights larger than default caption_button_container_->SetButtonSize(gfx::Size(0, height)); } void WinFrameView::LayoutWindowControlsOverlay() { int overlay_height = window()->titlebar_overlay_height(); if (overlay_height == 0) { // Accounting for the 1 pixel margin at the top of the button container overlay_height = IsMaximized() ? caption_button_container_->size().height() : caption_button_container_->size().height() + 1; } int overlay_width = caption_button_container_->size().width(); int bounding_rect_width = width() - overlay_width; auto bounding_rect = GetMirroredRect(gfx::Rect(0, 0, bounding_rect_width, overlay_height)); window()->SetWindowControlsOverlayRect(bounding_rect); window()->NotifyLayoutWindowControlsOverlay(); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
34,137
[Bug]: Crash on Windows when calling `win.setTitleBarOverlay` on a window that has `titleBarStyle != 'hidden'`
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 18.2.0 ### What operating system are you using? Windows ### Operating System Version Windows 10 version 20H2, build 19042 ### What arch are you using? x64 ### Last Known Working Electron version 18.1.0 ### Expected Behavior When `win.setTitleBarOverlay` is called, apparently the only valid option for `titleBarStyle` is `'hidden'`. So when `win` was created with `titleBarStyle` different from `'hidden'`, Electron should throw an error. ### Actual Behavior Electron crashes unexpectedly. ### Testcase Gist URL https://gist.github.com/wheezard/207499979a7fda8cc7d874fdb87886fc ### Additional Information This might work on older versions, but I haven't tested it in them.
https://github.com/electron/electron/issues/34137
https://github.com/electron/electron/pull/34140
4e3587c7c6e051193c6bbe346192ff08d2b594c1
97c9451efc3035a1072b1ff87aee125f7a9fa053
2022-05-08T18:34:46Z
c++
2022-05-17T15:50:27Z
spec-main/api-browser-window-spec.ts
import { expect } from 'chai'; import * as childProcess from 'child_process'; import * as path from 'path'; import * as fs from 'fs'; import * as os from 'os'; import * as qs from 'querystring'; import * as http from 'http'; import * as semver from 'semver'; import { AddressInfo } from 'net'; import { app, BrowserWindow, BrowserView, dialog, ipcMain, OnBeforeSendHeadersListenerDetails, protocol, screen, webContents, session, WebContents, BrowserWindowConstructorOptions } from 'electron/main'; import { emittedOnce, emittedUntil, emittedNTimes } from './events-helpers'; import { ifit, ifdescribe, defer, delay } from './spec-helpers'; import { closeWindow, closeAllWindows } from './window-helpers'; import { areColorsSimilar, captureScreen, CHROMA_COLOR_HEX, getPixelColor } from './screen-helpers'; const features = process._linkedBinding('electron_common_features'); const fixtures = path.resolve(__dirname, '..', 'spec', 'fixtures'); const mainFixtures = path.resolve(__dirname, 'fixtures'); // Is the display's scale factor possibly causing rounding of pixel coordinate // values? const isScaleFactorRounding = () => { const { scaleFactor } = screen.getPrimaryDisplay(); // Return true if scale factor is non-integer value if (Math.round(scaleFactor) !== scaleFactor) return true; // Return true if scale factor is odd number above 2 return scaleFactor > 2 && scaleFactor % 2 === 1; }; const expectBoundsEqual = (actual: any, expected: any) => { if (!isScaleFactorRounding()) { expect(expected).to.deep.equal(actual); } else if (Array.isArray(actual)) { expect(actual[0]).to.be.closeTo(expected[0], 1); expect(actual[1]).to.be.closeTo(expected[1], 1); } else { expect(actual.x).to.be.closeTo(expected.x, 1); expect(actual.y).to.be.closeTo(expected.y, 1); expect(actual.width).to.be.closeTo(expected.width, 1); expect(actual.height).to.be.closeTo(expected.height, 1); } }; const isBeforeUnload = (event: Event, level: number, message: string) => { return (message === 'beforeunload'); }; describe('BrowserWindow module', () => { describe('BrowserWindow constructor', () => { it('allows passing void 0 as the webContents', async () => { expect(() => { const w = new BrowserWindow({ show: false, // apparently void 0 had different behaviour from undefined in the // issue that this test is supposed to catch. webContents: void 0 // eslint-disable-line no-void } as any); w.destroy(); }).not.to.throw(); }); ifit(process.platform === 'linux')('does not crash when setting large window icons', async () => { const appPath = path.join(__dirname, 'spec-main', 'fixtures', 'apps', 'xwindow-icon'); const appProcess = childProcess.spawn(process.execPath, [appPath]); await new Promise((resolve) => { appProcess.once('exit', resolve); }); }); it('does not crash or throw when passed an invalid icon', async () => { expect(() => { const w = new BrowserWindow({ icon: undefined } as any); w.destroy(); }).not.to.throw(); }); }); describe('garbage collection', () => { const v8Util = process._linkedBinding('electron_common_v8_util'); afterEach(closeAllWindows); it('window does not get garbage collected when opened', async () => { const w = new BrowserWindow({ show: false }); // Keep a weak reference to the window. // eslint-disable-next-line no-undef const wr = new WeakRef(w); await delay(); // Do garbage collection, since |w| is not referenced in this closure // it would be gone after next call if there is no other reference. v8Util.requestGarbageCollectionForTesting(); await delay(); expect(wr.deref()).to.not.be.undefined(); }); }); describe('BrowserWindow.close()', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('should work if called when a messageBox is showing', async () => { const closed = emittedOnce(w, 'closed'); dialog.showMessageBox(w, { message: 'Hello Error' }); w.close(); await closed; }); it('closes window without rounded corners', async () => { await closeWindow(w); w = new BrowserWindow({ show: false, frame: false, roundedCorners: false }); const closed = emittedOnce(w, 'closed'); w.close(); await closed; }); it('should not crash if called after webContents is destroyed', () => { w.webContents.destroy(); w.webContents.on('destroyed', () => w.close()); }); it('should emit unload handler', async () => { await w.loadFile(path.join(fixtures, 'api', 'unload.html')); const closed = emittedOnce(w, 'closed'); w.close(); await closed; const test = path.join(fixtures, 'api', 'unload'); const content = fs.readFileSync(test); fs.unlinkSync(test); expect(String(content)).to.equal('unload'); }); it('should emit beforeunload handler', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); await emittedOnce(w.webContents, 'before-unload-fired'); }); it('should not crash when keyboard event is sent before closing', async () => { await w.loadURL('data:text/html,pls no crash'); const closed = emittedOnce(w, 'closed'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' }); w.close(); await closed; }); describe('when invoked synchronously inside navigation observer', () => { let server: http.Server = null as unknown as http.Server; let url: string = null as unknown as string; before((done) => { server = http.createServer((request, response) => { switch (request.url) { case '/net-error': response.destroy(); break; case '/301': response.statusCode = 301; response.setHeader('Location', '/200'); response.end(); break; case '/200': response.statusCode = 200; response.end('hello'); break; case '/title': response.statusCode = 200; response.end('<title>Hello</title>'); break; default: throw new Error(`unsupported endpoint: ${request.url}`); } }).listen(0, '127.0.0.1', () => { url = 'http://127.0.0.1:' + (server.address() as AddressInfo).port; done(); }); }); after(() => { server.close(); }); const events = [ { name: 'did-start-loading', path: '/200' }, { name: 'dom-ready', path: '/200' }, { name: 'page-title-updated', path: '/title' }, { name: 'did-stop-loading', path: '/200' }, { name: 'did-finish-load', path: '/200' }, { name: 'did-frame-finish-load', path: '/200' }, { name: 'did-fail-load', path: '/net-error' } ]; for (const { name, path } of events) { it(`should not crash when closed during ${name}`, async () => { const w = new BrowserWindow({ show: false }); w.webContents.once((name as any), () => { w.close(); }); const destroyed = emittedOnce(w.webContents, 'destroyed'); w.webContents.loadURL(url + path); await destroyed; }); } }); }); describe('window.close()', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('should emit unload event', async () => { w.loadFile(path.join(fixtures, 'api', 'close.html')); await emittedOnce(w, 'closed'); const test = path.join(fixtures, 'api', 'close'); const content = fs.readFileSync(test).toString(); fs.unlinkSync(test); expect(content).to.equal('close'); }); it('should emit beforeunload event', async function () { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.webContents.executeJavaScript('window.close()', true); await emittedOnce(w.webContents, 'before-unload-fired'); }); }); describe('BrowserWindow.destroy()', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('prevents users to access methods of webContents', async () => { const contents = w.webContents; w.destroy(); await new Promise(setImmediate); expect(() => { contents.getProcessId(); }).to.throw('Object has been destroyed'); }); it('should not crash when destroying windows with pending events', () => { const focusListener = () => { }; app.on('browser-window-focus', focusListener); const windowCount = 3; const windowOptions = { show: false, width: 400, height: 400, webPreferences: { backgroundThrottling: false } }; const windows = Array.from(Array(windowCount)).map(() => new BrowserWindow(windowOptions)); windows.forEach(win => win.show()); windows.forEach(win => win.focus()); windows.forEach(win => win.destroy()); app.removeListener('browser-window-focus', focusListener); }); }); describe('BrowserWindow.loadURL(url)', () => { let w = null as unknown as BrowserWindow; const scheme = 'other'; const srcPath = path.join(fixtures, 'api', 'loaded-from-dataurl.js'); before(() => { protocol.registerFileProtocol(scheme, (request, callback) => { callback(srcPath); }); }); after(() => { protocol.unregisterProtocol(scheme); }); beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); let server = null as unknown as http.Server; let url = null as unknown as string; let postData = null as any; before((done) => { const filePath = path.join(fixtures, 'pages', 'a.html'); const fileStats = fs.statSync(filePath); postData = [ { type: 'rawData', bytes: Buffer.from('username=test&file=') }, { type: 'file', filePath: filePath, offset: 0, length: fileStats.size, modificationTime: fileStats.mtime.getTime() / 1000 } ]; server = http.createServer((req, res) => { function respond () { if (req.method === 'POST') { let body = ''; req.on('data', (data) => { if (data) body += data; }); req.on('end', () => { const parsedData = qs.parse(body); fs.readFile(filePath, (err, data) => { if (err) return; if (parsedData.username === 'test' && parsedData.file === data.toString()) { res.end(); } }); }); } else if (req.url === '/302') { res.setHeader('Location', '/200'); res.statusCode = 302; res.end(); } else { res.end(); } } setTimeout(respond, req.url && req.url.includes('slow') ? 200 : 0); }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; done(); }); }); after(() => { server.close(); }); it('should emit did-start-loading event', async () => { const didStartLoading = emittedOnce(w.webContents, 'did-start-loading'); w.loadURL('about:blank'); await didStartLoading; }); it('should emit ready-to-show event', async () => { const readyToShow = emittedOnce(w, 'ready-to-show'); w.loadURL('about:blank'); await readyToShow; }); // TODO(deepak1556): The error code now seems to be `ERR_FAILED`, verify what // changed and adjust the test. it.skip('should emit did-fail-load event for files that do not exist', async () => { const didFailLoad = emittedOnce(w.webContents, 'did-fail-load'); w.loadURL('file://a.txt'); const [, code, desc,, isMainFrame] = await didFailLoad; expect(code).to.equal(-6); expect(desc).to.equal('ERR_FILE_NOT_FOUND'); expect(isMainFrame).to.equal(true); }); it('should emit did-fail-load event for invalid URL', async () => { const didFailLoad = emittedOnce(w.webContents, 'did-fail-load'); w.loadURL('http://example:port'); const [, code, desc,, isMainFrame] = await didFailLoad; expect(desc).to.equal('ERR_INVALID_URL'); expect(code).to.equal(-300); expect(isMainFrame).to.equal(true); }); it('should set `mainFrame = false` on did-fail-load events in iframes', async () => { const didFailLoad = emittedOnce(w.webContents, 'did-fail-load'); w.loadFile(path.join(fixtures, 'api', 'did-fail-load-iframe.html')); const [,,,, isMainFrame] = await didFailLoad; expect(isMainFrame).to.equal(false); }); it('does not crash in did-fail-provisional-load handler', (done) => { w.webContents.once('did-fail-provisional-load', () => { w.loadURL('http://127.0.0.1:11111'); done(); }); w.loadURL('http://127.0.0.1:11111'); }); it('should emit did-fail-load event for URL exceeding character limit', async () => { const data = Buffer.alloc(2 * 1024 * 1024).toString('base64'); const didFailLoad = emittedOnce(w.webContents, 'did-fail-load'); w.loadURL(`data:image/png;base64,${data}`); const [, code, desc,, isMainFrame] = await didFailLoad; expect(desc).to.equal('ERR_INVALID_URL'); expect(code).to.equal(-300); expect(isMainFrame).to.equal(true); }); it('should return a promise', () => { const p = w.loadURL('about:blank'); expect(p).to.have.property('then'); }); it('should return a promise that resolves', async () => { await expect(w.loadURL('about:blank')).to.eventually.be.fulfilled(); }); it('should return a promise that rejects on a load failure', async () => { const data = Buffer.alloc(2 * 1024 * 1024).toString('base64'); const p = w.loadURL(`data:image/png;base64,${data}`); await expect(p).to.eventually.be.rejected; }); it('should return a promise that resolves even if pushState occurs during navigation', async () => { const p = w.loadURL('data:text/html,<script>window.history.pushState({}, "/foo")</script>'); await expect(p).to.eventually.be.fulfilled; }); describe('POST navigations', () => { afterEach(() => { w.webContents.session.webRequest.onBeforeSendHeaders(null); }); it('supports specifying POST data', async () => { await w.loadURL(url, { postData }); }); it('sets the content type header on URL encoded forms', async () => { await w.loadURL(url); const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => { w.webContents.session.webRequest.onBeforeSendHeaders((details) => { resolve(details); }); }); w.webContents.executeJavaScript(` form = document.createElement('form') document.body.appendChild(form) form.method = 'POST' form.submit() `); const details = await requestDetails; expect(details.requestHeaders['Content-Type']).to.equal('application/x-www-form-urlencoded'); }); it('sets the content type header on multi part forms', async () => { await w.loadURL(url); const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => { w.webContents.session.webRequest.onBeforeSendHeaders((details) => { resolve(details); }); }); w.webContents.executeJavaScript(` form = document.createElement('form') document.body.appendChild(form) form.method = 'POST' form.enctype = 'multipart/form-data' file = document.createElement('input') file.type = 'file' file.name = 'file' form.appendChild(file) form.submit() `); const details = await requestDetails; expect(details.requestHeaders['Content-Type'].startsWith('multipart/form-data; boundary=----WebKitFormBoundary')).to.equal(true); }); }); it('should support base url for data urls', async () => { await w.loadURL('data:text/html,<script src="loaded-from-dataurl.js"></script>', { baseURLForDataURL: `other://${path.join(fixtures, 'api')}${path.sep}` }); expect(await w.webContents.executeJavaScript('window.ping')).to.equal('pong'); }); }); for (const sandbox of [false, true]) { describe(`navigation events${sandbox ? ' with sandbox' : ''}`, () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: false, sandbox } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('will-navigate event', () => { let server = null as unknown as http.Server; let url = null as unknown as string; before((done) => { server = http.createServer((req, res) => { if (req.url === '/navigate-top') { res.end('<a target=_top href="/">navigate _top</a>'); } else { res.end(''); } }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/`; done(); }); }); after(() => { server.close(); }); it('allows the window to be closed from the event listener', (done) => { w.webContents.once('will-navigate', () => { w.close(); done(); }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('can be prevented', (done) => { let willNavigate = false; w.webContents.once('will-navigate', (e) => { willNavigate = true; e.preventDefault(); }); w.webContents.on('did-stop-loading', () => { if (willNavigate) { // i.e. it shouldn't have had '?navigated' appended to it. try { expect(w.webContents.getURL().endsWith('will-navigate.html')).to.be.true(); done(); } catch (e) { done(e); } } }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('is triggered when navigating from file: to http:', async () => { await w.loadFile(path.join(fixtures, 'api', 'blank.html')); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-navigate', (e, url) => { e.preventDefault(); resolve(url); }); }); expect(navigatedTo).to.equal(url); expect(w.webContents.getURL()).to.match(/^file:/); }); it('is triggered when navigating from about:blank to http:', async () => { await w.loadURL('about:blank'); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-navigate', (e, url) => { e.preventDefault(); resolve(url); }); }); expect(navigatedTo).to.equal(url); expect(w.webContents.getURL()).to.equal('about:blank'); }); it('is triggered when a cross-origin iframe navigates _top', async () => { await w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-top"></iframe>`); await delay(1000); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const iframeTarget = targets.targetInfos.find((t: any) => t.type === 'iframe'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: iframeTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); let willNavigateEmitted = false; w.webContents.on('will-navigate', () => { willNavigateEmitted = true; }); await emittedOnce(w.webContents, 'did-navigate'); expect(willNavigateEmitted).to.be.true(); }); }); describe('will-redirect event', () => { let server = null as unknown as http.Server; let url = null as unknown as string; before((done) => { server = http.createServer((req, res) => { if (req.url === '/302') { res.setHeader('Location', '/200'); res.statusCode = 302; res.end(); } else if (req.url === '/navigate-302') { res.end(`<html><body><script>window.location='${url}/302'</script></body></html>`); } else { res.end(); } }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; done(); }); }); after(() => { server.close(); }); it('is emitted on redirects', async () => { const willRedirect = emittedOnce(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await willRedirect; }); it('is emitted after will-navigate on redirects', async () => { let navigateCalled = false; w.webContents.on('will-navigate', () => { navigateCalled = true; }); const willRedirect = emittedOnce(w.webContents, 'will-redirect'); w.loadURL(`${url}/navigate-302`); await willRedirect; expect(navigateCalled).to.equal(true, 'should have called will-navigate first'); }); it('is emitted before did-stop-loading on redirects', async () => { let stopCalled = false; w.webContents.on('did-stop-loading', () => { stopCalled = true; }); const willRedirect = emittedOnce(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await willRedirect; expect(stopCalled).to.equal(false, 'should not have called did-stop-loading first'); }); it('allows the window to be closed from the event listener', (done) => { w.webContents.once('will-redirect', () => { w.close(); done(); }); w.loadURL(`${url}/302`); }); it('can be prevented', (done) => { w.webContents.once('will-redirect', (event) => { event.preventDefault(); }); w.webContents.on('will-navigate', (e, u) => { expect(u).to.equal(`${url}/302`); }); w.webContents.on('did-stop-loading', () => { try { expect(w.webContents.getURL()).to.equal( `${url}/navigate-302`, 'url should not have changed after navigation event' ); done(); } catch (e) { done(e); } }); w.webContents.on('will-redirect', (e, u) => { try { expect(u).to.equal(`${url}/200`); } catch (e) { done(e); } }); w.loadURL(`${url}/navigate-302`); }); }); }); } describe('focus and visibility', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.show()', () => { it('should focus on window', async () => { await emittedOnce(w, 'focus', () => w.show()); expect(w.isFocused()).to.equal(true); }); it('should make the window visible', async () => { await emittedOnce(w, 'focus', () => w.show()); expect(w.isVisible()).to.equal(true); }); it('emits when window is shown', async () => { const show = emittedOnce(w, 'show'); w.show(); await show; expect(w.isVisible()).to.equal(true); }); }); describe('BrowserWindow.hide()', () => { it('should defocus on window', () => { w.hide(); expect(w.isFocused()).to.equal(false); }); it('should make the window not visible', () => { w.show(); w.hide(); expect(w.isVisible()).to.equal(false); }); it('emits when window is hidden', async () => { const shown = emittedOnce(w, 'show'); w.show(); await shown; const hidden = emittedOnce(w, 'hide'); w.hide(); await hidden; expect(w.isVisible()).to.equal(false); }); }); describe('BrowserWindow.showInactive()', () => { it('should not focus on window', () => { w.showInactive(); expect(w.isFocused()).to.equal(false); }); // TODO(dsanders11): Enable for Linux once CI plays nice with these kinds of tests ifit(process.platform !== 'linux')('should not restore maximized windows', async () => { const maximize = emittedOnce(w, 'maximize'); const shown = emittedOnce(w, 'show'); w.maximize(); // TODO(dsanders11): The maximize event isn't firing on macOS for a window initially hidden if (process.platform !== 'darwin') { await maximize; } else { await delay(1000); } w.showInactive(); await shown; expect(w.isMaximized()).to.equal(true); }); }); describe('BrowserWindow.focus()', () => { it('does not make the window become visible', () => { expect(w.isVisible()).to.equal(false); w.focus(); expect(w.isVisible()).to.equal(false); }); ifit(process.platform !== 'win32')('focuses a blurred window', async () => { { const isBlurred = emittedOnce(w, 'blur'); const isShown = emittedOnce(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 = emittedOnce(w3, 'focus'); const isShown1 = emittedOnce(w1, 'show'); const isShown2 = emittedOnce(w2, 'show'); const isShown3 = emittedOnce(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 = emittedOnce(w1, 'closed'); const isClosed2 = emittedOnce(w2, 'closed'); const isClosed3 = emittedOnce(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 = emittedOnce(w, 'focus'); const isShown = emittedOnce(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 = emittedOnce(w3, 'focus'); const isShown1 = emittedOnce(w1, 'show'); const isShown2 = emittedOnce(w2, 'show'); const isShown3 = emittedOnce(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 = emittedOnce(w1, 'closed'); const isClosed2 = emittedOnce(w2, 'closed'); const isClosed3 = emittedOnce(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 () => { await emittedOnce(w, 'focus', () => w.show()); w.webContents.openDevTools({ mode: 'undocked' }); await emittedOnce(w.webContents, 'devtools-focused'); expect(BrowserWindow.getFocusedWindow()).to.equal(w); }); }); describe('BrowserWindow.moveTop()', () => { it('should not steal focus', async () => { const posDelta = 50; const wShownInactive = emittedOnce(w, 'show'); w.showInactive(); await wShownInactive; expect(w.isFocused()).to.equal(false); const otherWindow = new BrowserWindow({ show: false, title: 'otherWindow' }); const otherWindowShown = emittedOnce(otherWindow, 'show'); const otherWindowFocused = emittedOnce(otherWindow, 'focus'); otherWindow.show(); await otherWindowShown; await otherWindowFocused; expect(otherWindow.isFocused()).to.equal(true); w.moveTop(); const wPos = w.getPosition(); const wMoving = emittedOnce(w, 'move'); w.setPosition(wPos[0] + posDelta, wPos[1] + posDelta); await wMoving; expect(w.isFocused()).to.equal(false); expect(otherWindow.isFocused()).to.equal(true); const wFocused = emittedOnce(w, 'focus'); const otherWindowBlurred = emittedOnce(otherWindow, 'blur'); w.focus(); await wFocused; await otherWindowBlurred; expect(w.isFocused()).to.equal(true); otherWindow.moveTop(); const otherWindowPos = otherWindow.getPosition(); const otherWindowMoving = emittedOnce(otherWindow, 'move'); otherWindow.setPosition(otherWindowPos[0] + posDelta, otherWindowPos[1] + posDelta); await otherWindowMoving; expect(otherWindow.isFocused()).to.equal(false); expect(w.isFocused()).to.equal(true); await closeWindow(otherWindow, { assertNotWindows: false }); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1); }); }); ifdescribe(features.isDesktopCapturerEnabled())('BrowserWindow.moveAbove(mediaSourceId)', () => { it('should throw an exception if wrong formatting', async () => { const fakeSourceIds = [ 'none', 'screen:0', 'window:fake', 'window:1234', 'foobar:1:2' ]; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Invalid media source id/); }); }); it('should throw an exception if wrong type', async () => { const fakeSourceIds = [null as any, 123 as any]; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Error processing argument at index 0 */); }); }); it('should throw an exception if invalid window', async () => { // It is very unlikely that these window id exist. const fakeSourceIds = ['window:99999999:0', 'window:123456:1', 'window:123456:9']; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Invalid media source id/); }); }); it('should not throw an exception', async () => { const w2 = new BrowserWindow({ show: false, title: 'window2' }); const w2Shown = emittedOnce(w2, 'show'); w2.show(); await w2Shown; expect(() => { w.moveAbove(w2.getMediaSourceId()); }).to.not.throw(); await closeWindow(w2, { assertNotWindows: false }); }); }); describe('BrowserWindow.setFocusable()', () => { it('can set unfocusable window to focusable', async () => { const w2 = new BrowserWindow({ focusable: false }); const w2Focused = emittedOnce(w2, 'focus'); w2.setFocusable(true); w2.focus(); await w2Focused; await closeWindow(w2, { assertNotWindows: false }); }); }); describe('BrowserWindow.isFocusable()', () => { it('correctly returns whether a window is focusable', async () => { const w2 = new BrowserWindow({ focusable: false }); expect(w2.isFocusable()).to.be.false(); w2.setFocusable(true); expect(w2.isFocusable()).to.be.true(); await closeWindow(w2, { assertNotWindows: false }); }); }); }); describe('sizing', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, width: 400, height: 400 }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.setBounds(bounds[, animate])', () => { it('sets the window bounds with full bounds', () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds); expectBoundsEqual(w.getBounds(), fullBounds); }); it('sets the window bounds with partial bounds', () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds); const boundsUpdate = { width: 200 }; w.setBounds(boundsUpdate as any); const expectedBounds = Object.assign(fullBounds, boundsUpdate); expectBoundsEqual(w.getBounds(), expectedBounds); }); ifit(process.platform === 'darwin')('on macOS', () => { it('emits \'resized\' event after animating', async () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds, true); await expect(emittedOnce(w, 'resized')).to.eventually.be.fulfilled(); }); }); }); describe('BrowserWindow.setSize(width, height)', () => { it('sets the window size', async () => { const size = [300, 400]; const resized = emittedOnce(w, 'resize'); w.setSize(size[0], size[1]); await resized; expectBoundsEqual(w.getSize(), size); }); ifit(process.platform === 'darwin')('on macOS', () => { it('emits \'resized\' event after animating', async () => { const size = [300, 400]; w.setSize(size[0], size[1], true); await expect(emittedOnce(w, 'resized')).to.eventually.be.fulfilled(); }); }); }); describe('BrowserWindow.setMinimum/MaximumSize(width, height)', () => { it('sets the maximum and minimum size of the window', () => { expect(w.getMinimumSize()).to.deep.equal([0, 0]); expect(w.getMaximumSize()).to.deep.equal([0, 0]); w.setMinimumSize(100, 100); expectBoundsEqual(w.getMinimumSize(), [100, 100]); expectBoundsEqual(w.getMaximumSize(), [0, 0]); w.setMaximumSize(900, 600); expectBoundsEqual(w.getMinimumSize(), [100, 100]); expectBoundsEqual(w.getMaximumSize(), [900, 600]); }); }); describe('BrowserWindow.setAspectRatio(ratio)', () => { it('resets the behaviour when passing in 0', async () => { const size = [300, 400]; w.setAspectRatio(1 / 2); w.setAspectRatio(0); const resize = emittedOnce(w, 'resize'); w.setSize(size[0], size[1]); await resize; expectBoundsEqual(w.getSize(), size); }); it('doesn\'t change bounds when maximum size is set', () => { w.setMenu(null); w.setMaximumSize(400, 400); // Without https://github.com/electron/electron/pull/29101 // following call would shrink the window to 384x361. // There would be also DCHECK in resize_utils.cc on // debug build. w.setAspectRatio(1.0); expectBoundsEqual(w.getSize(), [400, 400]); }); }); describe('BrowserWindow.setPosition(x, y)', () => { it('sets the window position', async () => { const pos = [10, 10]; const move = emittedOnce(w, 'move'); w.setPosition(pos[0], pos[1]); await move; expect(w.getPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setContentSize(width, height)', () => { it('sets the content size', async () => { // NB. The CI server has a very small screen. Attempting to size the window // larger than the screen will limit the window's size to the screen and // cause the test to fail. const size = [456, 567]; w.setContentSize(size[0], size[1]); await new Promise(setImmediate); const after = w.getContentSize(); expect(after).to.deep.equal(size); }); it('works for a frameless window', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 400, height: 400 }); const size = [456, 567]; w.setContentSize(size[0], size[1]); await new Promise(setImmediate); const after = w.getContentSize(); expect(after).to.deep.equal(size); }); }); describe('BrowserWindow.setContentBounds(bounds)', () => { it('sets the content size and position', async () => { const bounds = { x: 10, y: 10, width: 250, height: 250 }; const resize = emittedOnce(w, 'resize'); w.setContentBounds(bounds); await resize; await delay(); expectBoundsEqual(w.getContentBounds(), bounds); }); it('works for a frameless window', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300 }); const bounds = { x: 10, y: 10, width: 250, height: 250 }; const resize = emittedOnce(w, 'resize'); w.setContentBounds(bounds); await resize; await delay(); expectBoundsEqual(w.getContentBounds(), bounds); }); }); describe('BrowserWindow.getBackgroundColor()', () => { it('returns default value if no backgroundColor is set', () => { w.destroy(); w = new BrowserWindow({}); expect(w.getBackgroundColor()).to.equal('#FFFFFF'); }); it('returns correct value if backgroundColor is set', () => { const backgroundColor = '#BBAAFF'; w.destroy(); w = new BrowserWindow({ backgroundColor: backgroundColor }); expect(w.getBackgroundColor()).to.equal(backgroundColor); }); it('returns correct value from setBackgroundColor()', () => { const backgroundColor = '#AABBFF'; w.destroy(); w = new BrowserWindow({}); w.setBackgroundColor(backgroundColor); expect(w.getBackgroundColor()).to.equal(backgroundColor); }); 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 = emittedOnce(w, 'resize'); w.setSize(size[0], size[1]); await resize; expectBoundsEqual(w.getNormalBounds(), w.getBounds()); }); it('checks normal bounds after move', async () => { const pos = [10, 10]; const move = emittedOnce(w, 'move'); w.setPosition(pos[0], pos[1]); await move; expectBoundsEqual(w.getNormalBounds(), w.getBounds()); }); }); ifdescribe(process.platform !== 'linux')('Maximized state', () => { it('checks normal bounds when maximized', async () => { const bounds = w.getBounds(); const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('checks normal bounds when unmaximized', async () => { const bounds = w.getBounds(); w.once('maximize', () => { w.unmaximize(); }); const unmaximize = emittedOnce(w, 'unmaximize'); w.show(); w.maximize(); await unmaximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('does not change size for a frameless window with min size', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300, minWidth: 300, minHeight: 300 }); const bounds = w.getBounds(); w.once('maximize', () => { w.unmaximize(); }); const unmaximize = emittedOnce(w, 'unmaximize'); w.show(); w.maximize(); await unmaximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('correctly checks transparent window maximization state', async () => { w.destroy(); w = new BrowserWindow({ show: false, width: 300, height: 300, transparent: true }); const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; expect(w.isMaximized()).to.equal(true); const unmaximize = emittedOnce(w, 'unmaximize'); w.unmaximize(); await unmaximize; expect(w.isMaximized()).to.equal(false); }); it('returns the correct value for windows with an aspect ratio', async () => { w.destroy(); w = new BrowserWindow({ show: false, fullscreenable: false }); w.setAspectRatio(16 / 11); const maximize = emittedOnce(w, 'resize'); w.show(); w.maximize(); await maximize; expect(w.isMaximized()).to.equal(true); w.resizable = false; expect(w.isMaximized()).to.equal(true); }); }); ifdescribe(process.platform !== 'linux')('Minimized state', () => { it('checks normal bounds when minimized', async () => { const bounds = w.getBounds(); const minimize = emittedOnce(w, 'minimize'); w.show(); w.minimize(); await minimize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('checks normal bounds when restored', async () => { const bounds = w.getBounds(); w.once('minimize', () => { w.restore(); }); const restore = emittedOnce(w, 'restore'); w.show(); w.minimize(); await restore; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('does not change size for a frameless window with min size', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300, minWidth: 300, minHeight: 300 }); const bounds = w.getBounds(); w.once('minimize', () => { w.restore(); }); const restore = emittedOnce(w, 'restore'); w.show(); w.minimize(); await restore; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); ifdescribe(process.platform === 'win32')('Fullscreen state', () => { it('with properties', () => { it('can be set with the fullscreen constructor option', () => { w = new BrowserWindow({ fullscreen: true }); expect(w.fullScreen).to.be.true(); }); it('can be changed', () => { w.fullScreen = false; expect(w.fullScreen).to.be.false(); w.fullScreen = true; expect(w.fullScreen).to.be.true(); }); it('checks normal bounds when fullscreen\'ed', async () => { const bounds = w.getBounds(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.show(); w.fullScreen = true; await enterFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('checks normal bounds when unfullscreen\'ed', async () => { const bounds = w.getBounds(); w.once('enter-full-screen', () => { w.fullScreen = false; }); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.show(); w.fullScreen = true; await leaveFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); it('with functions', () => { it('can be set with the fullscreen constructor option', () => { w = new BrowserWindow({ fullscreen: true }); expect(w.isFullScreen()).to.be.true(); }); it('can be changed', () => { w.setFullScreen(false); expect(w.isFullScreen()).to.be.false(); w.setFullScreen(true); expect(w.isFullScreen()).to.be.true(); }); it('checks normal bounds when fullscreen\'ed', async () => { const bounds = w.getBounds(); w.show(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('checks normal bounds when unfullscreen\'ed', async () => { const bounds = w.getBounds(); w.show(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); }); }); }); ifdescribe(process.platform === 'darwin')('tabbed windows', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.selectPreviousTab()', () => { it('does not throw', () => { expect(() => { w.selectPreviousTab(); }).to.not.throw(); }); }); describe('BrowserWindow.selectNextTab()', () => { it('does not throw', () => { expect(() => { w.selectNextTab(); }).to.not.throw(); }); }); describe('BrowserWindow.mergeAllWindows()', () => { it('does not throw', () => { expect(() => { w.mergeAllWindows(); }).to.not.throw(); }); }); describe('BrowserWindow.moveTabToNewWindow()', () => { it('does not throw', () => { expect(() => { w.moveTabToNewWindow(); }).to.not.throw(); }); }); describe('BrowserWindow.toggleTabBar()', () => { it('does not throw', () => { expect(() => { w.toggleTabBar(); }).to.not.throw(); }); }); describe('BrowserWindow.addTabbedWindow()', () => { it('does not throw', async () => { const tabbedWindow = new BrowserWindow({}); expect(() => { w.addTabbedWindow(tabbedWindow); }).to.not.throw(); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(2); // w + tabbedWindow await closeWindow(tabbedWindow, { assertNotWindows: false }); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1); // w }); it('throws when called on itself', () => { expect(() => { w.addTabbedWindow(w); }).to.throw('AddTabbedWindow cannot be called by a window on itself.'); }); }); }); describe('autoHideMenuBar state', () => { afterEach(closeAllWindows); it('for properties', () => { it('can be set with autoHideMenuBar constructor option', () => { const w = new BrowserWindow({ show: false, autoHideMenuBar: true }); expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); w.autoHideMenuBar = true; expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); w.autoHideMenuBar = false; expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); }); }); it('for functions', () => { it('can be set with autoHideMenuBar constructor option', () => { const w = new BrowserWindow({ show: false, autoHideMenuBar: true }); expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar'); w.setAutoHideMenuBar(true); expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar'); w.setAutoHideMenuBar(false); expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar'); }); }); }); describe('BrowserWindow.capturePage(rect)', () => { afterEach(closeAllWindows); it('returns a Promise with a Buffer', async () => { const w = new BrowserWindow({ show: false }); const image = await w.capturePage({ x: 0, y: 0, width: 100, height: 100 }); expect(image.isEmpty()).to.equal(true); }); it('resolves after the window is hidden', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixtures, 'pages', 'a.html')); await emittedOnce(w, 'ready-to-show'); w.show(); const visibleImage = await w.capturePage(); expect(visibleImage.isEmpty()).to.equal(false); w.hide(); const hiddenImage = await w.capturePage(); const isEmpty = process.platform !== 'darwin'; expect(hiddenImage.isEmpty()).to.equal(isEmpty); }); it('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 emittedOnce(w, 'ready-to-show'); w.webContents.incrementCapturerCount(); 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 emittedOnce(w, 'ready-to-show'); w.show(); const image = await w.capturePage(); const imgBuffer = image.toPNG(); // Check the 25th byte in the PNG. // Values can be 0,2,3,4, or 6. We want 6, which is RGB + Alpha expect(imgBuffer[25]).to.equal(6); }); it('should increase the capturer count', () => { const w = new BrowserWindow({ show: false }); w.webContents.incrementCapturerCount(); expect(w.webContents.isBeingCaptured()).to.be.true(); w.webContents.decrementCapturerCount(); expect(w.webContents.isBeingCaptured()).to.be.false(); }); }); describe('BrowserWindow.setProgressBar(progress)', () => { let w = null as unknown as BrowserWindow; before(() => { w = new BrowserWindow({ show: false }); }); after(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('sets the progress', () => { expect(() => { if (process.platform === 'darwin') { app.dock.setIcon(path.join(fixtures, 'assets', 'logo.png')); } w.setProgressBar(0.5); if (process.platform === 'darwin') { app.dock.setIcon(null as any); } w.setProgressBar(-1); }).to.not.throw(); }); it('sets the progress using "paused" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'paused' }); }).to.not.throw(); }); it('sets the progress using "error" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'error' }); }).to.not.throw(); }); it('sets the progress using "normal" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'normal' }); }).to.not.throw(); }); }); describe('BrowserWindow.setAlwaysOnTop(flag, level)', () => { let w = null as unknown as BrowserWindow; afterEach(closeAllWindows); beforeEach(() => { w = new BrowserWindow({ show: true }); }); it('sets the window as always on top', () => { expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); w.setAlwaysOnTop(false); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); }); ifit(process.platform === 'darwin')('resets the windows level on minimize', () => { expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); w.minimize(); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.restore(); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); }); it('causes the right value to be emitted on `always-on-top-changed`', async () => { const alwaysOnTopChanged = emittedOnce(w, 'always-on-top-changed'); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true); const [, alwaysOnTop] = await alwaysOnTopChanged; expect(alwaysOnTop).to.be.true('is not alwaysOnTop'); }); ifit(process.platform === 'darwin')('honors the alwaysOnTop level of a child window', () => { w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ parent: w }); c.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.false(); expect(c.isAlwaysOnTop()).to.be.true('child is not always on top'); expect((c as any)._getAlwaysOnTopLevel()).to.equal('screen-saver'); }); }); describe('preconnect feature', () => { let w = null as unknown as BrowserWindow; let server = null as unknown as http.Server; let url = null as unknown as string; let connections = 0; beforeEach(async () => { connections = 0; server = http.createServer((req, res) => { if (req.url === '/link') { res.setHeader('Content-type', 'text/html'); res.end('<head><link rel="preconnect" href="//example.com" /></head><body>foo</body>'); return; } res.end(); }); server.on('connection', () => { connections++; }); await new Promise<void>(resolve => server.listen(0, '127.0.0.1', () => resolve())); url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; }); afterEach(async () => { server.close(); await closeWindow(w); w = null as unknown as BrowserWindow; server = null as unknown as http.Server; }); it('calling preconnect() connects to the server', async () => { w = new BrowserWindow({ show: false }); w.webContents.on('did-start-navigation', (event, url) => { w.webContents.session.preconnect({ url, numSockets: 4 }); }); await w.loadURL(url); expect(connections).to.equal(4); }); it('does not preconnect unless requested', async () => { w = new BrowserWindow({ show: false }); await w.loadURL(url); expect(connections).to.equal(1); }); it('parses <link rel=preconnect>', async () => { w = new BrowserWindow({ show: true }); const p = emittedOnce(w.webContents.session, 'preconnect'); w.loadURL(url + '/link'); const [, preconnectUrl, allowCredentials] = await p; expect(preconnectUrl).to.equal('http://example.com/'); expect(allowCredentials).to.be.true('allowCredentials'); }); }); describe('BrowserWindow.setAutoHideCursor(autoHide)', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); ifit(process.platform === 'darwin')('on macOS', () => { it('allows changing cursor auto-hiding', () => { expect(() => { w.setAutoHideCursor(false); w.setAutoHideCursor(true); }).to.not.throw(); }); }); ifit(process.platform !== 'darwin')('on non-macOS platforms', () => { it('is not available', () => { expect(w.setAutoHideCursor).to.be.undefined('setAutoHideCursor function'); }); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setWindowButtonVisibility()', () => { afterEach(closeAllWindows); it('does not throw', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setWindowButtonVisibility(true); w.setWindowButtonVisibility(false); }).to.not.throw(); }); it('changes window button visibility for normal window', () => { const w = new BrowserWindow({ show: false }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); it('changes window button visibility for frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); }); it('changes window button visibility for hiddenInset window', () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hiddenInset' }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); // Buttons of customButtonsOnHover are always hidden unless hovered. it('does not change window button visibility for customButtonsOnHover window', () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'customButtonsOnHover' }); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setVibrancy(type)', () => { let appProcess: childProcess.ChildProcessWithoutNullStreams | childProcess.ChildProcess | undefined; afterEach(() => { if (appProcess && !appProcess.killed) { appProcess.kill(); appProcess = undefined; } closeAllWindows(); }); it('allows setting, changing, and removing the vibrancy', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setVibrancy('light'); w.setVibrancy('dark'); w.setVibrancy(null); w.setVibrancy('ultra-dark'); w.setVibrancy('' as any); }).to.not.throw(); }); it('does not crash if vibrancy is set to an invalid value', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setVibrancy('i-am-not-a-valid-vibrancy-type' as any); }).to.not.throw(); }); it('Allows setting a transparent window via CSS', async () => { const appPath = path.join(__dirname, 'fixtures', 'apps', 'background-color-transparent'); appProcess = childProcess.spawn(process.execPath, [appPath], { stdio: 'inherit' }); const [code] = await emittedOnce(appProcess, 'exit'); expect(code).to.equal(0); }); }); ifdescribe(process.platform === 'darwin')('trafficLightPosition', () => { const pos = { x: 10, y: 10 }; afterEach(closeAllWindows); describe('BrowserWindow.getTrafficLightPosition(pos)', () => { it('gets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); expect(w.getTrafficLightPosition()).to.deep.equal(pos); }); it('gets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); expect(w.getTrafficLightPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setTrafficLightPosition(pos)', () => { it('sets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setTrafficLightPosition(newPos); expect(w.getTrafficLightPosition()).to.deep.equal(newPos); }); it('sets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setTrafficLightPosition(newPos); expect(w.getTrafficLightPosition()).to.deep.equal(newPos); }); }); }); ifdescribe(process.platform === 'win32')('BrowserWindow.setAppDetails(options)', () => { afterEach(closeAllWindows); it('supports setting the app details', () => { const w = new BrowserWindow({ show: false }); const iconPath = path.join(fixtures, 'assets', 'icon.ico'); expect(() => { w.setAppDetails({ appId: 'my.app.id' }); w.setAppDetails({ appIconPath: iconPath, appIconIndex: 0 }); w.setAppDetails({ appIconPath: iconPath }); w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name' }); w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2' }); w.setAppDetails({ relaunchDisplayName: 'My app name' }); w.setAppDetails({ appId: 'my.app.id', appIconPath: iconPath, appIconIndex: 0, relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name' }); w.setAppDetails({}); }).to.not.throw(); expect(() => { (w.setAppDetails as any)(); }).to.throw('Insufficient number of arguments.'); }); }); describe('BrowserWindow.fromId(id)', () => { afterEach(closeAllWindows); it('returns the window with id', () => { const w = new BrowserWindow({ show: false }); expect(BrowserWindow.fromId(w.id)!.id).to.equal(w.id); }); }); describe('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 emittedOnce(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 any).create({}); try { expect(BrowserWindow.fromWebContents(contents)).to.be.null('BrowserWindow.fromWebContents(contents)'); } finally { contents.destroy(); } }); it('returns the correct window for a BrowserView webcontents', async () => { const w = new BrowserWindow({ show: false }); const bv = new BrowserView(); w.setBrowserView(bv); defer(() => { w.removeBrowserView(bv); (bv.webContents as any).destroy(); }); await bv.webContents.loadURL('about:blank'); expect(BrowserWindow.fromWebContents(bv.webContents)!.id).to.equal(w.id); }); it('returns the correct window for a WebView webcontents', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } }); w.loadURL('data:text/html,<webview src="data:text/html,hi"></webview>'); // NOTE(nornagon): Waiting for 'did-attach-webview' is a workaround for // https://github.com/electron/electron/issues/25413, and is not integral // to the test. const p = emittedOnce(w.webContents, 'did-attach-webview'); const [, webviewContents] = await emittedOnce(app, 'web-contents-created'); expect(BrowserWindow.fromWebContents(webviewContents)!.id).to.equal(w.id); await p; }); 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((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 as any).destroy(); }); expect(BrowserWindow.fromBrowserView(bv)!.id).to.equal(w.id); }); it('returns the window when there are multiple BrowserViews', () => { const w = new BrowserWindow({ show: false }); const bv1 = new BrowserView(); w.addBrowserView(bv1); const bv2 = new BrowserView(); w.addBrowserView(bv2); defer(() => { w.removeBrowserView(bv1); w.removeBrowserView(bv2); (bv1.webContents as any).destroy(); (bv2.webContents as any).destroy(); }); expect(BrowserWindow.fromBrowserView(bv1)!.id).to.equal(w.id); expect(BrowserWindow.fromBrowserView(bv2)!.id).to.equal(w.id); }); it('returns undefined if not attached', () => { const bv = new BrowserView(); defer(() => { (bv.webContents as any).destroy(); }); expect(BrowserWindow.fromBrowserView(bv)).to.be.null('BrowserWindow associated with bv'); }); }); describe('BrowserWindow.setOpacity(opacity)', () => { afterEach(closeAllWindows); ifdescribe(process.platform !== 'linux')(('Windows and Mac'), () => { it('make window with initial opacity', () => { const w = new BrowserWindow({ show: false, opacity: 0.5 }); expect(w.getOpacity()).to.equal(0.5); }); it('allows setting the opacity', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setOpacity(0.0); expect(w.getOpacity()).to.equal(0.0); w.setOpacity(0.5); expect(w.getOpacity()).to.equal(0.5); w.setOpacity(1.0); expect(w.getOpacity()).to.equal(1.0); }).to.not.throw(); }); it('clamps opacity to [0.0...1.0]', () => { const w = new BrowserWindow({ show: false, opacity: 0.5 }); w.setOpacity(100); expect(w.getOpacity()).to.equal(1.0); w.setOpacity(-100); expect(w.getOpacity()).to.equal(0.0); }); }); ifdescribe(process.platform === 'linux')(('Linux'), () => { it('sets 1 regardless of parameter', () => { const w = new BrowserWindow({ show: false }); w.setOpacity(0); expect(w.getOpacity()).to.equal(1.0); w.setOpacity(0.5); expect(w.getOpacity()).to.equal(1.0); }); }); }); describe('BrowserWindow.setShape(rects)', () => { afterEach(closeAllWindows); it('allows setting shape', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setShape([]); w.setShape([{ x: 0, y: 0, width: 100, height: 100 }]); w.setShape([{ x: 0, y: 0, width: 100, height: 100 }, { x: 0, y: 200, width: 1000, height: 100 }]); w.setShape([]); }).to.not.throw(); }); }); describe('"useContentSize" option', () => { afterEach(closeAllWindows); it('make window created with content size when used', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, useContentSize: true }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); it('make window created with window size when not used', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400 }); const size = w.getSize(); expect(size).to.deep.equal([400, 400]); }); it('works for a frameless window', () => { const w = new BrowserWindow({ show: false, frame: false, width: 400, height: 400, useContentSize: true }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); const size = w.getSize(); expect(size).to.deep.equal([400, 400]); }); }); ifdescribe(process.platform === 'win32' || (process.platform === 'darwin' && semver.gte(os.release(), '14.0.0')))('"titleBarStyle" option', () => { const testWindowsOverlay = async (style: any) => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: style, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: true }); const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); if (process.platform === 'darwin') { await w.loadFile(overlayHTML); } else { const overlayReady = emittedOnce(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const overlayRect = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(overlayRect.y).to.equal(0); if (process.platform === 'darwin') { expect(overlayRect.x).to.be.greaterThan(0); } else { expect(overlayRect.x).to.equal(0); } expect(overlayRect.width).to.be.greaterThan(0); expect(overlayRect.height).to.be.greaterThan(0); const cssOverlayRect = await w.webContents.executeJavaScript('getCssOverlayProperties();'); expect(cssOverlayRect).to.deep.equal(overlayRect); const geometryChange = emittedOnce(ipcMain, 'geometrychange'); w.setBounds({ width: 800 }); const [, newOverlayRect] = await geometryChange; expect(newOverlayRect.width).to.equal(overlayRect.width + 400); }; afterEach(closeAllWindows); afterEach(() => { ipcMain.removeAllListeners('geometrychange'); }); it('creates browser window with hidden title bar', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden' }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); ifit(process.platform === 'darwin')('creates browser window with hidden inset title bar', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hiddenInset' }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); it('sets Window Control Overlay with hidden title bar', async () => { await testWindowsOverlay('hidden'); }); ifit(process.platform === 'darwin')('sets Window Control Overlay with hidden inset title bar', async () => { await testWindowsOverlay('hiddenInset'); }); }); ifdescribe(process.platform === 'win32' || (process.platform === 'darwin' && semver.gte(os.release(), '14.0.0')))('"titleBarOverlay" option', () => { const testWindowsOverlayHeight = async (size: any) => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden', webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { height: size } }); const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); if (process.platform === 'darwin') { await w.loadFile(overlayHTML); } else { const overlayReady = emittedOnce(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const overlayRectPreMax = await w.webContents.executeJavaScript('getJSOverlayProperties()'); if (!w.isMaximized()) { const maximize = emittedOnce(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(closeAllWindows); afterEach(() => { 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(closeAllWindows); afterEach(() => { ipcMain.removeAllListeners('geometrychange'); }); it('correctly updates the height of the overlay', async () => { const testOverlay = async (w: BrowserWindow, size: Number) => { const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); w.loadFile(overlayHTML); await emittedOnce(ipcMain, 'geometrychange'); 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 = emittedOnce(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); w.setTitleBarOverlay({ height: INITIAL_SIZE + 10 }); await testOverlay(w, INITIAL_SIZE + 10); }); }); ifdescribe(process.platform === 'darwin')('"enableLargerThanScreen" option', () => { afterEach(closeAllWindows); it('can move the window out of screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); w.setPosition(-10, 50); const after = w.getPosition(); expect(after).to.deep.equal([-10, 50]); }); it('cannot move the window behind menu bar', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[1]).to.be.at.least(0); }); it('can move the window behind menu bar if it has no frame', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true, frame: false }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[0]).to.be.equal(-10); expect(after[1]).to.be.equal(-10); }); it('without it, cannot move the window out of screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: false }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[1]).to.be.at.least(0); }); it('can set the window larger than screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); const size = screen.getPrimaryDisplay().size; size.width += 100; size.height += 100; w.setSize(size.width, size.height); expectBoundsEqual(w.getSize(), [size.width, size.height]); }); it('without it, cannot set the window larger than screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: false }); const size = screen.getPrimaryDisplay().size; size.width += 100; size.height += 100; w.setSize(size.width, size.height); expect(w.getSize()[1]).to.at.most(screen.getPrimaryDisplay().size.height); }); }); ifdescribe(process.platform === 'darwin')('"zoomToPageWidth" option', () => { afterEach(closeAllWindows); it('sets the window width to the page width when used', () => { const w = new BrowserWindow({ show: false, width: 500, height: 400, zoomToPageWidth: true }); w.maximize(); expect(w.getSize()[0]).to.equal(500); }); }); describe('"tabbingIdentifier" option', () => { afterEach(closeAllWindows); it('can be set on a window', () => { expect(() => { /* eslint-disable no-new */ new BrowserWindow({ tabbingIdentifier: 'group1' }); new BrowserWindow({ tabbingIdentifier: 'group2', frame: false }); /* eslint-enable no-new */ }).not.to.throw(); }); }); describe('"webPreferences" option', () => { afterEach(() => { ipcMain.removeAllListeners('answer'); }); afterEach(closeAllWindows); describe('"preload" option', () => { const doesNotLeakSpec = (name: string, webPrefs: { nodeIntegration: boolean, sandbox: boolean, contextIsolation: boolean }) => { it(name, async () => { const w = new BrowserWindow({ webPreferences: { ...webPrefs, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'no-leak.html')); const [, result] = await emittedOnce(ipcMain, 'leak-result'); expect(result).to.have.property('require', 'undefined'); expect(result).to.have.property('exports', 'undefined'); expect(result).to.have.property('windowExports', 'undefined'); expect(result).to.have.property('windowPreload', 'undefined'); expect(result).to.have.property('windowRequire', 'undefined'); }); }; doesNotLeakSpec('does not leak require', { nodeIntegration: false, sandbox: false, contextIsolation: false }); doesNotLeakSpec('does not leak require when sandbox is enabled', { nodeIntegration: false, sandbox: true, contextIsolation: false }); doesNotLeakSpec('does not leak require when context isolation is enabled', { nodeIntegration: false, sandbox: false, contextIsolation: true }); doesNotLeakSpec('does not leak require when context isolation and sandbox are enabled', { nodeIntegration: false, sandbox: true, contextIsolation: true }); it('does not leak any node globals on the window object with nodeIntegration is disabled', async () => { let w = new BrowserWindow({ webPreferences: { contextIsolation: false, nodeIntegration: false, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'globals.html')); const [, notIsolated] = await emittedOnce(ipcMain, 'leak-result'); expect(notIsolated).to.have.property('globals'); w.destroy(); w = new BrowserWindow({ webPreferences: { contextIsolation: true, nodeIntegration: false, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'globals.html')); const [, isolated] = await emittedOnce(ipcMain, 'leak-result'); expect(isolated).to.have.property('globals'); const notIsolatedGlobals = new Set(notIsolated.globals); for (const isolatedGlobal of isolated.globals) { notIsolatedGlobals.delete(isolatedGlobal); } expect([...notIsolatedGlobals]).to.deep.equal([], 'non-isoalted renderer should have no additional globals'); }); it('loads the script before other scripts in window', async () => { const preload = path.join(fixtures, 'module', 'set-global.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false, preload } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test).to.eql('preload'); }); it('has synchronous access to all eventual window APIs', async () => { const preload = path.join(fixtures, 'module', 'access-blink-apis.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false, preload } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test).to.be.an('object'); expect(test.atPreload).to.be.an('array'); expect(test.atLoad).to.be.an('array'); expect(test.atPreload).to.deep.equal(test.atLoad, 'should have access to the same window APIs'); }); }); describe('session preload scripts', function () { const preloads = [ path.join(fixtures, 'module', 'set-global-preload-1.js'), path.join(fixtures, 'module', 'set-global-preload-2.js'), path.relative(process.cwd(), path.join(fixtures, 'module', 'set-global-preload-3.js')) ]; const defaultSession = session.defaultSession; beforeEach(() => { expect(defaultSession.getPreloads()).to.deep.equal([]); defaultSession.setPreloads(preloads); }); afterEach(() => { defaultSession.setPreloads([]); }); it('can set multiple session preload script', () => { expect(defaultSession.getPreloads()).to.deep.equal(preloads); }); const generateSpecs = (description: string, sandbox: boolean) => { describe(description, () => { it('loads the script before other scripts in window including normal preloads', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox, preload: path.join(fixtures, 'module', 'get-global-preload.js'), contextIsolation: false } }); w.loadURL('about:blank'); const [, preload1, preload2, preload3] = await emittedOnce(ipcMain, 'vars'); expect(preload1).to.equal('preload-1'); expect(preload2).to.equal('preload-1-2'); expect(preload3).to.be.undefined('preload 3'); }); }); }; generateSpecs('without sandbox', false); generateSpecs('with sandbox', true); }); describe('"additionalArguments" option', () => { it('adds extra args to process.argv in the renderer process', async () => { const preload = path.join(fixtures, 'module', 'check-arguments.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, preload, additionalArguments: ['--my-magic-arg'] } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, argv] = await emittedOnce(ipcMain, 'answer'); expect(argv).to.include('--my-magic-arg'); }); it('adds extra value args to process.argv in the renderer process', async () => { const preload = path.join(fixtures, 'module', 'check-arguments.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, preload, additionalArguments: ['--my-magic-arg=foo'] } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, argv] = await emittedOnce(ipcMain, 'answer'); expect(argv).to.include('--my-magic-arg=foo'); }); }); describe('"node-integration" option', () => { it('disables node integration by default', async () => { const preload = path.join(fixtures, 'module', 'send-later.js'); const w = new BrowserWindow({ show: false, webPreferences: { preload, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, typeofProcess, typeofBuffer] = await emittedOnce(ipcMain, 'answer'); expect(typeofProcess).to.equal('undefined'); expect(typeofBuffer).to.equal('undefined'); }); }); describe('"sandbox" option', () => { const preload = path.join(path.resolve(__dirname, 'fixtures'), 'module', 'preload-sandbox.js'); let server: http.Server = null as unknown as http.Server; let serverUrl: string = null as unknown as string; before((done) => { server = http.createServer((request, response) => { switch (request.url) { case '/cross-site': response.end(`<html><body><h1>${request.url}</h1></body></html>`); break; default: throw new Error(`unsupported endpoint: ${request.url}`); } }).listen(0, '127.0.0.1', () => { serverUrl = 'http://127.0.0.1:' + (server.address() as AddressInfo).port; done(); }); }); after(() => { server.close(); }); it('exposes ipcRenderer to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test).to.equal('preload'); }); it('exposes ipcRenderer to preload script (path has special chars)', async () => { const preloadSpecialChars = path.join(fixtures, 'module', 'preload-sandboxæø åü.js'); const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload: preloadSpecialChars, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test).to.equal('preload'); }); it('exposes "loaded" event to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload } }); w.loadURL('about:blank'); await emittedOnce(ipcMain, 'process-loaded'); }); it('exposes "exit" event to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?exit-event'); const pageUrl = 'file://' + htmlPath; w.loadURL(pageUrl); const [, url] = await emittedOnce(ipcMain, 'answer'); const expectedUrl = process.platform === 'win32' ? 'file:///' + htmlPath.replace(/\\/g, '/') : pageUrl; expect(url).to.equal(expectedUrl); }); it('should open windows in same domain with cross-scripting enabled', async () => { const w = new BrowserWindow({ show: true, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload } } })); const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?window-open'); const pageUrl = 'file://' + htmlPath; const answer = emittedOnce(ipcMain, 'answer'); w.loadURL(pageUrl); const [, { url, frameName, options }] = await emittedOnce(w.webContents, 'did-create-window'); const expectedUrl = process.platform === 'win32' ? 'file:///' + htmlPath.replace(/\\/g, '/') : pageUrl; expect(url).to.equal(expectedUrl); expect(frameName).to.equal('popup!'); expect(options.width).to.equal(500); expect(options.height).to.equal(600); const [, html] = await answer; expect(html).to.equal('<h1>scripting from opener</h1>'); }); it('should open windows in another domain with cross-scripting disabled', async () => { const w = new BrowserWindow({ show: true, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload } } })); w.loadFile( path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'window-open-external' } ); // Wait for a message from the main window saying that it's ready. await emittedOnce(ipcMain, 'opener-loaded'); // Ask the opener to open a popup with window.opener. const expectedPopupUrl = `${serverUrl}/cross-site`; // Set in "sandbox.html". w.webContents.send('open-the-popup', expectedPopupUrl); // The page is going to open a popup that it won't be able to close. // We have to close it from here later. const [, popupWindow] = await emittedOnce(app, 'browser-window-created'); // Ask the popup window for details. const detailsAnswer = emittedOnce(ipcMain, 'child-loaded'); popupWindow.webContents.send('provide-details'); const [, openerIsNull, , locationHref] = await detailsAnswer; expect(openerIsNull).to.be.false('window.opener is null'); expect(locationHref).to.equal(expectedPopupUrl); // Ask the page to access the popup. const touchPopupResult = emittedOnce(ipcMain, 'answer'); w.webContents.send('touch-the-popup'); const [, popupAccessMessage] = await touchPopupResult; // Ask the popup to access the opener. const touchOpenerResult = emittedOnce(ipcMain, 'answer'); popupWindow.webContents.send('touch-the-opener'); const [, openerAccessMessage] = await touchOpenerResult; // We don't need the popup anymore, and its parent page can't close it, // so let's close it from here before we run any checks. await closeWindow(popupWindow, { assertNotWindows: false }); expect(popupAccessMessage).to.be.a('string', 'child\'s .document is accessible from its parent window'); expect(popupAccessMessage).to.match(/^Blocked a frame with origin/); expect(openerAccessMessage).to.be.a('string', 'opener .document is accessible from a popup window'); expect(openerAccessMessage).to.match(/^Blocked a frame with origin/); }); it('should inherit the sandbox setting in opened windows', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [, { argv }] = await emittedOnce(ipcMain, 'answer'); expect(argv).to.include('--enable-sandbox'); }); it('should open windows with the options configured via new-window event listeners', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath, contextIsolation: false } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [[, childWebContents]] = await Promise.all([ emittedOnce(app, 'web-contents-created'), emittedOnce(ipcMain, 'answer') ]); const webPreferences = childWebContents.getLastWebPreferences(); expect(webPreferences.contextIsolation).to.equal(false); }); it('should set ipc event sender correctly', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); let childWc: WebContents | null = null; w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload, contextIsolation: false } } })); w.webContents.on('did-create-window', (win) => { childWc = win.webContents; expect(w.webContents).to.not.equal(childWc); }); ipcMain.once('parent-ready', function (event) { expect(event.sender).to.equal(w.webContents, 'sender should be the parent'); event.sender.send('verified'); }); ipcMain.once('child-ready', function (event) { expect(childWc).to.not.be.null('child webcontents should be available'); expect(event.sender).to.equal(childWc, 'sender should be the child'); event.sender.send('verified'); }); const done = Promise.all([ 'parent-answer', 'child-answer' ].map(name => emittedOnce(ipcMain, name))); w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'verify-ipc-sender' }); await done; }); describe('event handling', () => { let w: BrowserWindow = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); }); it('works for window events', async () => { const pageTitleUpdated = emittedOnce(w, 'page-title-updated'); w.loadURL('data:text/html,<script>document.title = \'changed\'</script>'); await pageTitleUpdated; }); it('works for stop events', async () => { const done = Promise.all([ 'did-navigate', 'did-fail-load', 'did-stop-loading' ].map(name => emittedOnce(w.webContents, name))); w.loadURL('data:text/html,<script>stop()</script>'); await done; }); it('works for web contents events', async () => { const done = Promise.all([ 'did-finish-load', 'did-frame-finish-load', 'did-navigate-in-page', 'will-navigate', 'did-start-loading', 'did-stop-loading', 'did-frame-finish-load', 'dom-ready' ].map(name => emittedOnce(w.webContents, name))); w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'webcontents-events' }); await done; }); }); it('supports calling preventDefault on new-window events', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const initialWebContents = webContents.getAllWebContents().map((i) => i.id); w.webContents.once('new-window', (e) => { e.preventDefault(); // We need to give it some time so the windows get properly disposed (at least on OSX). setTimeout(() => { const currentWebContents = webContents.getAllWebContents().map((i) => i.id); try { expect(currentWebContents).to.deep.equal(initialWebContents); done(); } catch (error) { done(e); } }, 100); }); w.loadFile(path.join(fixtures, 'pages', 'window-open.html')); }); it('validates process APIs access in sandboxed renderer', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.once('preload-error', (event, preloadPath, error) => { throw error; }); process.env.sandboxmain = 'foo'; w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test.hasCrash).to.be.true('has crash'); expect(test.hasHang).to.be.true('has hang'); expect(test.heapStatistics).to.be.an('object'); expect(test.blinkMemoryInfo).to.be.an('object'); expect(test.processMemoryInfo).to.be.an('object'); expect(test.systemVersion).to.be.a('string'); expect(test.cpuUsage).to.be.an('object'); expect(test.ioCounters).to.be.an('object'); expect(test.uptime).to.be.a('number'); expect(test.arch).to.equal(process.arch); expect(test.platform).to.equal(process.platform); expect(test.env).to.deep.equal(process.env); expect(test.execPath).to.equal(process.helperExecPath); expect(test.sandboxed).to.be.true('sandboxed'); expect(test.contextIsolated).to.be.false('contextIsolated'); expect(test.type).to.equal('renderer'); expect(test.version).to.equal(process.version); expect(test.versions).to.deep.equal(process.versions); expect(test.contextId).to.be.a('string'); if (process.platform === 'linux' && test.osSandbox) { expect(test.creationTime).to.be.null('creation time'); expect(test.systemMemoryInfo).to.be.null('system memory info'); } else { expect(test.creationTime).to.be.a('number'); expect(test.systemMemoryInfo).to.be.an('object'); } }); it('webview in sandbox renderer', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, webviewTag: true, contextIsolation: false } }); const didAttachWebview = emittedOnce(w.webContents, 'did-attach-webview'); const webviewDomReady = emittedOnce(ipcMain, 'webview-dom-ready'); w.loadFile(path.join(fixtures, 'pages', 'webview-did-attach-event.html')); const [, webContents] = await didAttachWebview; const [, id] = await webviewDomReady; expect(webContents.id).to.equal(id); }); }); describe('child windows', () => { let w: BrowserWindow = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, // tests relies on preloads in opened windows nodeIntegrationInSubFrames: true, contextIsolation: false } }); }); it('opens window of about:blank with cross-scripting enabled', async () => { const answer = emittedOnce(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-blank.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('opens window of same domain with cross-scripting enabled', async () => { const answer = emittedOnce(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-file.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('blocks accessing cross-origin frames', async () => { const answer = emittedOnce(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-cross-origin.html')); const [, content] = await answer; expect(content).to.equal('Blocked a frame with origin "file://" from accessing a cross-origin frame.'); }); it('opens window from <iframe> tags', async () => { const answer = emittedOnce(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-iframe.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('opens window with cross-scripting enabled from isolated context', async () => { const w = new BrowserWindow({ show: false, webPreferences: { preload: path.join(fixtures, 'api', 'native-window-open-isolated-preload.js') } }); w.loadFile(path.join(fixtures, 'api', 'native-window-open-isolated.html')); const [, content] = await emittedOnce(ipcMain, 'answer'); expect(content).to.equal('Hello'); }); ifit(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('loads native addons correctly after reload', async () => { w.loadFile(path.join(__dirname, 'fixtures', 'api', 'native-window-open-native-addon.html')); { const [, content] = await emittedOnce(ipcMain, 'answer'); expect(content).to.equal('function'); } w.reload(); { const [, content] = await emittedOnce(ipcMain, 'answer'); expect(content).to.equal('function'); } }); it('<webview> works in a scriptable popup', async () => { const preload = path.join(fixtures, 'api', 'new-window-webview-preload.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegrationInSubFrames: true, webviewTag: true, contextIsolation: false, preload } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { show: false, webPreferences: { contextIsolation: false, webviewTag: true, nodeIntegrationInSubFrames: true } } })); w.webContents.once('new-window', (event, url, frameName, disposition, options) => { options.show = false; }); const webviewLoaded = emittedOnce(ipcMain, 'webview-loaded'); w.loadFile(path.join(fixtures, 'api', 'new-window-webview.html')); await webviewLoaded; }); it('should open windows with the options configured via new-window event listeners', async () => { const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath, contextIsolation: false } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [[, childWebContents]] = await Promise.all([ emittedOnce(app, 'web-contents-created'), emittedOnce(ipcMain, 'answer') ]); const webPreferences = childWebContents.getLastWebPreferences(); expect(webPreferences.contextIsolation).to.equal(false); }); describe('window.location', () => { const protocols = [ ['foo', path.join(fixtures, 'api', 'window-open-location-change.html')], ['bar', path.join(fixtures, 'api', 'window-open-location-final.html')] ]; beforeEach(() => { for (const [scheme, path] of protocols) { protocol.registerBufferProtocol(scheme, (request, callback) => { callback({ mimeType: 'text/html', data: fs.readFileSync(path) }); }); } }); afterEach(() => { for (const [scheme] of protocols) { protocol.unregisterProtocol(scheme); } }); it('retains the original web preferences when window.location is changed to a new origin', async () => { const w = new BrowserWindow({ show: false, webPreferences: { // test relies on preloads in opened window nodeIntegrationInSubFrames: true, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: path.join(mainFixtures, 'api', 'window-open-preload.js'), contextIsolation: false, nodeIntegrationInSubFrames: true } } })); w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html')); const [, { nodeIntegration, typeofProcess }] = await emittedOnce(ipcMain, 'answer'); expect(nodeIntegration).to.be.false(); expect(typeofProcess).to.eql('undefined'); }); it('window.opener is not null when window.location is changed to a new origin', async () => { const w = new BrowserWindow({ show: false, webPreferences: { // test relies on preloads in opened window nodeIntegrationInSubFrames: true } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: path.join(mainFixtures, 'api', 'window-open-preload.js') } } })); w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html')); const [, { windowOpenerIsNull }] = await emittedOnce(ipcMain, 'answer'); expect(windowOpenerIsNull).to.be.false('window.opener is null'); }); }); }); describe('"disableHtmlFullscreenWindowResize" option', () => { it('prevents window from resizing when set', async () => { const w = new BrowserWindow({ show: false, webPreferences: { disableHtmlFullscreenWindowResize: true } }); await w.loadURL('about:blank'); const size = w.getSize(); const enterHtmlFullScreen = emittedOnce(w.webContents, 'enter-html-full-screen'); w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true); await enterHtmlFullScreen; expect(w.getSize()).to.deep.equal(size); }); }); }); describe('beforeunload handler', function () { let w: BrowserWindow = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(closeAllWindows); it('returning undefined would not prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html')); const wait = emittedOnce(w, 'closed'); w.close(); await wait; }); it('returning false would prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); const [, proceed] = await emittedOnce(w.webContents, 'before-unload-fired'); expect(proceed).to.equal(false); }); it('returning empty string would prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-empty-string.html')); w.close(); const [, proceed] = await emittedOnce(w.webContents, 'before-unload-fired'); expect(proceed).to.equal(false); }); it('emits for each close attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const destroyListener = () => { expect.fail('Close was not prevented'); }; w.webContents.once('destroyed', destroyListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await emittedOnce(w.webContents, 'console-message'); w.close(); await emittedOnce(w.webContents, 'before-unload-fired'); w.close(); await emittedOnce(w.webContents, 'before-unload-fired'); w.webContents.removeListener('destroyed', destroyListener); const wait = emittedOnce(w, 'closed'); w.close(); await wait; }); it('emits for each reload attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const navigationListener = () => { expect.fail('Reload was not prevented'); }; w.webContents.once('did-start-navigation', navigationListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await emittedOnce(w.webContents, 'console-message'); w.reload(); // Chromium does not emit 'before-unload-fired' on WebContents for // navigations, so we have to use other ways to know if beforeunload // is fired. await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.reload(); await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.webContents.removeListener('did-start-navigation', navigationListener); w.reload(); await emittedOnce(w.webContents, 'did-finish-load'); }); it('emits for each navigation attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const navigationListener = () => { expect.fail('Reload was not prevented'); }; w.webContents.once('did-start-navigation', navigationListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await emittedOnce(w.webContents, 'console-message'); w.loadURL('about:blank'); // Chromium does not emit 'before-unload-fired' on WebContents for // navigations, so we have to use other ways to know if beforeunload // is fired. await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.loadURL('about:blank'); await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.webContents.removeListener('did-start-navigation', navigationListener); await w.loadURL('about:blank'); }); }); describe('document.visibilityState/hidden', () => { afterEach(closeAllWindows); it('visibilityState is initially visible despite window being hidden', async () => { const w = new BrowserWindow({ show: false, width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); let readyToShow = false; w.once('ready-to-show', () => { readyToShow = true; }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(readyToShow).to.be.false('ready to show'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform !== 'win32')('visibilityState changes when window is hidden', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.hide(); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform !== 'win32')('visibilityState changes when window is shown', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); if (process.platform === 'darwin') { // See https://github.com/electron/electron/issues/8664 await emittedOnce(w, 'show'); } w.hide(); w.show(); const [, visibilityState] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); }); ifit(process.platform !== 'win32')('visibilityState changes when window is shown inactive', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); if (process.platform === 'darwin') { // See https://github.com/electron/electron/issues/8664 await emittedOnce(w, 'show'); } w.hide(); w.showInactive(); const [, visibilityState] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform === 'darwin')('visibilityState changes when window is minimized', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.minimize(); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } }); // FIXME(MarshallOfSound): This test fails locally 100% of the time, on CI it started failing // when we introduced the compositor recycling patch. Should figure out how to fix this it.skip('visibilityState remains visible if backgroundThrottling is disabled', async () => { const w = new BrowserWindow({ show: false, width: 100, height: 100, webPreferences: { backgroundThrottling: false, nodeIntegration: true } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } ipcMain.once('pong', (event, visibilityState, hidden) => { throw new Error(`Unexpected visibility change event. visibilityState: ${visibilityState} hidden: ${hidden}`); }); try { const shown1 = emittedOnce(w, 'show'); w.show(); await shown1; const hidden = emittedOnce(w, 'hide'); w.hide(); await hidden; const shown2 = emittedOnce(w, 'show'); w.show(); await shown2; } finally { ipcMain.removeAllListeners('pong'); } }); }); describe('new-window event', () => { afterEach(closeAllWindows); it('emits when window.open is called', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); w.webContents.once('new-window', (e, url, frameName, disposition, options) => { e.preventDefault(); try { expect(url).to.equal('http://host/'); expect(frameName).to.equal('host'); expect((options as any)['this-is-not-a-standard-feature']).to.equal(true); done(); } catch (e) { done(e); } }); w.loadFile(path.join(fixtures, 'pages', 'window-open.html')); }); it('emits when window.open is called with no webPreferences', (done) => { const w = new BrowserWindow({ show: false }); w.webContents.once('new-window', function (e, url, frameName, disposition, options) { e.preventDefault(); try { expect(url).to.equal('http://host/'); expect(frameName).to.equal('host'); expect((options as any)['this-is-not-a-standard-feature']).to.equal(true); done(); } catch (e) { done(e); } }); w.loadFile(path.join(fixtures, 'pages', 'window-open.html')); }); it('emits when link with target is called', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); w.webContents.once('new-window', (e, url, frameName) => { e.preventDefault(); try { expect(url).to.equal('http://host/'); expect(frameName).to.equal('target'); done(); } catch (e) { done(e); } }); w.loadFile(path.join(fixtures, 'pages', 'target-name.html')); }); it('includes all properties', async () => { const w = new BrowserWindow({ show: false }); const p = new Promise<{ url: string, frameName: string, disposition: string, options: BrowserWindowConstructorOptions, additionalFeatures: string[], referrer: Electron.Referrer, postBody: Electron.PostBody }>((resolve) => { w.webContents.once('new-window', (e, url, frameName, disposition, options, additionalFeatures, referrer, postBody) => { e.preventDefault(); resolve({ url, frameName, disposition, options, additionalFeatures, referrer, postBody }); }); }); w.loadURL(`data:text/html,${encodeURIComponent(` <form target="_blank" method="POST" id="form" action="http://example.com/test"> <input type="text" name="post-test-key" value="post-test-value"></input> </form> <script>form.submit()</script> `)}`); const { url, frameName, disposition, options, additionalFeatures, referrer, postBody } = await p; expect(url).to.equal('http://example.com/test'); expect(frameName).to.equal(''); expect(disposition).to.equal('foreground-tab'); expect(options).to.be.an('object').not.null(); expect(referrer.policy).to.equal('strict-origin-when-cross-origin'); expect(referrer.url).to.equal(''); expect(additionalFeatures).to.deep.equal([]); expect(postBody.data).to.have.length(1); expect(postBody.data[0].type).to.equal('rawData'); expect((postBody.data[0] as any).bytes).to.deep.equal(Buffer.from('post-test-key=post-test-value')); expect(postBody.contentType).to.equal('application/x-www-form-urlencoded'); }); }); ifdescribe(process.platform !== 'linux')('max/minimize events', () => { afterEach(closeAllWindows); it('emits an event when window is maximized', async () => { const w = new BrowserWindow({ show: false }); const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; }); it('emits an event when a transparent window is maximized', async () => { const w = new BrowserWindow({ show: false, frame: false, transparent: true }); const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; }); it('emits only one event when frameless window is maximized', () => { const w = new BrowserWindow({ show: false, frame: false }); let emitted = 0; w.on('maximize', () => emitted++); w.show(); w.maximize(); expect(emitted).to.equal(1); }); it('emits an event when window is unmaximized', async () => { const w = new BrowserWindow({ show: false }); const unmaximize = emittedOnce(w, 'unmaximize'); w.show(); w.maximize(); w.unmaximize(); await unmaximize; }); it('emits an event when a transparent window is unmaximized', async () => { const w = new BrowserWindow({ show: false, frame: false, transparent: true }); const maximize = emittedOnce(w, 'maximize'); const unmaximize = emittedOnce(w, 'unmaximize'); w.show(); w.maximize(); await maximize; w.unmaximize(); await unmaximize; }); it('emits an event when window is minimized', async () => { const w = new BrowserWindow({ show: false }); const minimize = emittedOnce(w, 'minimize'); w.show(); w.minimize(); await minimize; }); }); describe('beginFrameSubscription method', () => { it('does not crash when callback returns nothing', (done) => { const w = new BrowserWindow({ show: false }); 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(() => { w.webContents.endFrameSubscription(); done(); }); }); }); }); it('subscribes to frame updates', (done) => { const w = new BrowserWindow({ show: false }); let called = false; w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); w.webContents.on('dom-ready', () => { w.webContents.beginFrameSubscription(function (data) { // This callback might be called twice. if (called) return; called = true; try { expect(data.constructor.name).to.equal('NativeImage'); expect(data.isEmpty()).to.be.false('data is empty'); done(); } catch (e) { done(e); } finally { w.webContents.endFrameSubscription(); } }); }); }); it('subscribes to frame updates (only dirty rectangle)', (done) => { const w = new BrowserWindow({ show: false }); let called = false; let gotInitialFullSizeFrame = false; const [contentWidth, contentHeight] = w.getContentSize(); w.webContents.on('did-finish-load', () => { w.webContents.beginFrameSubscription(true, (image, rect) => { if (image.isEmpty()) { // Chromium sometimes sends a 0x0 frame at the beginning of the // page load. return; } if (rect.height === contentHeight && rect.width === contentWidth && !gotInitialFullSizeFrame) { // The initial frame is full-size, but we're looking for a call // with just the dirty-rect. The next frame should be a smaller // rect. gotInitialFullSizeFrame = true; return; } // This callback might be called twice. if (called) return; // We asked for just the dirty rectangle, so we expect to receive a // rect smaller than the full size. // TODO(jeremy): this is failing on windows currently; investigate. // assert(rect.width < contentWidth || rect.height < contentHeight) called = true; try { const expectedSize = rect.width * rect.height * 4; expect(image.getBitmap()).to.be.an.instanceOf(Buffer).with.lengthOf(expectedSize); done(); } catch (e) { done(e); } finally { w.webContents.endFrameSubscription(); } }); }); w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); }); it('throws error when subscriber is not well defined', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.webContents.beginFrameSubscription(true, true as any); // TODO(zcbenz): gin is weak at guessing parameter types, we should // upstream native_mate's implementation to gin. }).to.throw('Error processing argument at index 1, conversion failure from '); }); }); describe('savePage method', () => { const savePageDir = path.join(fixtures, 'save_page'); const savePageHtmlPath = path.join(savePageDir, 'save_page.html'); const savePageJsPath = path.join(savePageDir, 'save_page_files', 'test.js'); const savePageCssPath = path.join(savePageDir, 'save_page_files', 'test.css'); afterEach(() => { closeAllWindows(); try { fs.unlinkSync(savePageCssPath); fs.unlinkSync(savePageJsPath); fs.unlinkSync(savePageHtmlPath); fs.rmdirSync(path.join(savePageDir, 'save_page_files')); fs.rmdirSync(savePageDir); } catch {} }); it('should throw when passing relative paths', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await expect( w.webContents.savePage('save_page.html', 'HTMLComplete') ).to.eventually.be.rejectedWith('Path must be absolute'); await expect( w.webContents.savePage('save_page.html', 'HTMLOnly') ).to.eventually.be.rejectedWith('Path must be absolute'); await expect( w.webContents.savePage('save_page.html', 'MHTML') ).to.eventually.be.rejectedWith('Path must be absolute'); }); it('should save page to disk with HTMLOnly', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'HTMLOnly'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.false('js path'); expect(fs.existsSync(savePageCssPath)).to.be.false('css path'); }); it('should save page to disk with MHTML', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'MHTML'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.false('js path'); expect(fs.existsSync(savePageCssPath)).to.be.false('css path'); }); it('should save page to disk with HTMLComplete', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'HTMLComplete'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.true('js path'); expect(fs.existsSync(savePageCssPath)).to.be.true('css path'); }); }); describe('BrowserWindow options argument is optional', () => { afterEach(closeAllWindows); it('should create a window with default size (800x600)', () => { const w = new BrowserWindow(); expect(w.getSize()).to.deep.equal([800, 600]); }); }); describe('BrowserWindow.restore()', () => { afterEach(closeAllWindows); it('should restore the previous window size', () => { const w = new BrowserWindow({ minWidth: 800, width: 800 }); const initialSize = w.getSize(); w.minimize(); w.restore(); expectBoundsEqual(w.getSize(), initialSize); }); it('does not crash when restoring hidden minimized window', () => { const w = new BrowserWindow({}); w.minimize(); w.hide(); w.show(); }); }); // 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 = emittedOnce(w, 'hide'); let shown = emittedOnce(w, 'show'); const maximize = emittedOnce(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 = emittedOnce(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 = emittedOnce(w, 'minimize'); w.minimize(); await minimize; w.unmaximize(); await delay(1000); expect(w.isMinimized()).to.be.true(); }); it('should not change the size or position of a normal window', async () => { const w = new BrowserWindow(); const initialSize = w.getSize(); const initialPosition = w.getPosition(); w.unmaximize(); await delay(1000); expectBoundsEqual(w.getSize(), initialSize); expectBoundsEqual(w.getPosition(), initialPosition); }); 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 delay(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 = emittedOnce(w, 'show'); // start fullscreen and hidden w.setFullScreen(true); w.show(); await shown; const leftFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leftFullScreen; expect(w.isVisible()).to.be.true('visible'); expect(w.isFullScreen()).to.be.false('fullscreen'); }); it('should keep window hidden if already in hidden state', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const leftFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leftFullScreen; expect(w.isVisible()).to.be.false('visible'); expect(w.isFullScreen()).to.be.false('fullscreen'); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setFullScreen(false) when HTML fullscreen', () => { it('exits HTML fullscreen when window leaves fullscreen', async () => { const w = new BrowserWindow(); await w.loadURL('about:blank'); await w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true); await emittedOnce(w, 'enter-full-screen'); // Wait a tick for the full-screen state to 'stick' await delay(); w.setFullScreen(false); await emittedOnce(w, 'leave-html-full-screen'); }); }); }); describe('parent window', () => { afterEach(closeAllWindows); ifit(process.platform === 'darwin')('sheet-begin event emits when window opens a sheet', async () => { const w = new BrowserWindow(); const sheetBegin = emittedOnce(w, 'sheet-begin'); // eslint-disable-next-line no-new new BrowserWindow({ modal: true, parent: w }); await sheetBegin; }); ifit(process.platform === 'darwin')('sheet-end event emits when window has closed a sheet', async () => { const w = new BrowserWindow(); const sheet = new BrowserWindow({ modal: true, parent: w }); const sheetEnd = emittedOnce(w, 'sheet-end'); sheet.close(); await sheetEnd; }); describe('parent option', () => { it('sets parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(c.getParentWindow()).to.equal(w); }); it('adds window to child windows of parent', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(w.getChildWindows()).to.deep.equal([c]); }); it('removes from child windows of parent when window is closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); const closed = emittedOnce(c, 'closed'); c.close(); await closed; // The child window list is not immediately cleared, so wait a tick until it's ready. await delay(); expect(w.getChildWindows().length).to.equal(0); }); it('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 delay(); 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 = emittedOnce(c, 'closed'); c.setParentWindow(w); c.close(); await closed; // The child window list is not immediately cleared, so wait a tick until it's ready. await delay(); expect(w.getChildWindows().length).to.equal(0); }); }); describe('modal option', () => { it('does not freeze or crash', async () => { const parentWindow = new BrowserWindow(); const createTwo = async () => { const two = new BrowserWindow({ width: 300, height: 200, parent: parentWindow, modal: true, show: false }); const twoShown = emittedOnce(two, 'show'); two.show(); await twoShown; setTimeout(() => two.close(), 500); await emittedOnce(two, 'closed'); }; const one = new BrowserWindow({ width: 600, height: 400, parent: parentWindow, modal: true, show: false }); const oneShown = emittedOnce(one, 'show'); one.show(); await oneShown; setTimeout(() => one.destroy(), 500); await emittedOnce(one, 'closed'); await createTwo(); }); ifit(process.platform !== 'darwin')('disables parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); expect(w.isEnabled()).to.be.true('w.isEnabled'); c.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); }); ifit(process.platform !== 'darwin')('re-enables an enabled parent window when closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const closed = emittedOnce(c, 'closed'); c.show(); c.close(); await closed; expect(w.isEnabled()).to.be.true('w.isEnabled'); }); ifit(process.platform !== 'darwin')('does not re-enable a disabled parent window when closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const closed = emittedOnce(c, 'closed'); w.setEnabled(false); c.show(); c.close(); await closed; expect(w.isEnabled()).to.be.false('w.isEnabled'); }); ifit(process.platform !== 'darwin')('disables parent window recursively', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const c2 = new BrowserWindow({ show: false, parent: w, modal: true }); c.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c2.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c.destroy(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c2.destroy(); expect(w.isEnabled()).to.be.true('w.isEnabled'); }); }); }); describe('window states', () => { afterEach(closeAllWindows); it('does not resize frameless windows when states change', () => { const w = new BrowserWindow({ frame: false, width: 300, height: 200, show: false }); w.minimizable = false; w.minimizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.resizable = false; w.resizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.maximizable = false; w.maximizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.fullScreenable = false; w.fullScreenable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.closable = false; w.closable = true; expect(w.getSize()).to.deep.equal([300, 200]); }); describe('resizable state', () => { it('with properties', () => { it('can be set with resizable constructor option', () => { const w = new BrowserWindow({ show: false, resizable: false }); expect(w.resizable).to.be.false('resizable'); if (process.platform === 'darwin') { expect(w.maximizable).to.to.true('maximizable'); } }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.resizable).to.be.true('resizable'); w.resizable = false; expect(w.resizable).to.be.false('resizable'); w.resizable = true; expect(w.resizable).to.be.true('resizable'); }); }); it('with functions', () => { it('can be set with resizable constructor option', () => { const w = new BrowserWindow({ show: false, resizable: false }); expect(w.isResizable()).to.be.false('resizable'); if (process.platform === 'darwin') { expect(w.isMaximizable()).to.to.true('maximizable'); } }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isResizable()).to.be.true('resizable'); w.setResizable(false); expect(w.isResizable()).to.be.false('resizable'); w.setResizable(true); expect(w.isResizable()).to.be.true('resizable'); }); }); it('works for a frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); expect(w.resizable).to.be.true('resizable'); if (process.platform === 'win32') { const w = new BrowserWindow({ show: false, thickFrame: false }); expect(w.resizable).to.be.false('resizable'); } }); // On Linux there is no "resizable" property of a window. ifit(process.platform !== 'linux')('does affect maximizability when disabled and enabled', () => { const w = new BrowserWindow({ show: false }); expect(w.resizable).to.be.true('resizable'); expect(w.maximizable).to.be.true('maximizable'); w.resizable = false; expect(w.maximizable).to.be.false('not maximizable'); w.resizable = true; expect(w.maximizable).to.be.true('maximizable'); }); ifit(process.platform === 'win32')('works for a window smaller than 64x64', () => { const w = new BrowserWindow({ show: false, frame: false, resizable: false, transparent: true }); w.setContentSize(60, 60); expectBoundsEqual(w.getContentSize(), [60, 60]); w.setContentSize(30, 30); expectBoundsEqual(w.getContentSize(), [30, 30]); w.setContentSize(10, 10); expectBoundsEqual(w.getContentSize(), [10, 10]); }); }); describe('loading main frame state', () => { let server: http.Server = null as unknown as http.Server; let serverUrl: string = null as unknown as string; before((done) => { server = http.createServer((request, response) => { response.end(); }).listen(0, '127.0.0.1', () => { serverUrl = 'http://127.0.0.1:' + (server.address() as AddressInfo).port; done(); }); }); after(() => { server.close(); }); it('is true when the main frame is loading', async () => { const w = new BrowserWindow({ show: false }); const didStartLoading = emittedOnce(w.webContents, 'did-start-loading'); w.webContents.loadURL(serverUrl); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame'); }); it('is false when only a subframe is loading', async () => { const w = new BrowserWindow({ show: false }); const didStopLoading = emittedOnce(w.webContents, 'did-stop-loading'); w.webContents.loadURL(serverUrl); await didStopLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); const didStartLoading = emittedOnce(w.webContents, 'did-start-loading'); w.webContents.executeJavaScript(` var iframe = document.createElement('iframe') iframe.src = '${serverUrl}/page2' document.body.appendChild(iframe) `); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); }); it('is true when navigating to pages from the same origin', async () => { const w = new BrowserWindow({ show: false }); const didStopLoading = emittedOnce(w.webContents, 'did-stop-loading'); w.webContents.loadURL(serverUrl); await didStopLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); const didStartLoading = emittedOnce(w.webContents, 'did-start-loading'); w.webContents.loadURL(`${serverUrl}/page2`); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame'); }); }); }); ifdescribe(process.platform !== 'linux')('window states (excluding Linux)', () => { // Not implemented on Linux. afterEach(closeAllWindows); describe('movable state', () => { it('with properties', () => { it('can be set with movable constructor option', () => { const w = new BrowserWindow({ show: false, movable: false }); expect(w.movable).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.movable).to.be.true('movable'); w.movable = false; expect(w.movable).to.be.false('movable'); w.movable = true; expect(w.movable).to.be.true('movable'); }); }); it('with functions', () => { it('can be set with movable constructor option', () => { const w = new BrowserWindow({ show: false, movable: false }); expect(w.isMovable()).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMovable()).to.be.true('movable'); w.setMovable(false); expect(w.isMovable()).to.be.false('movable'); w.setMovable(true); expect(w.isMovable()).to.be.true('movable'); }); }); }); describe('visibleOnAllWorkspaces state', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.visibleOnAllWorkspaces).to.be.false(); w.visibleOnAllWorkspaces = true; expect(w.visibleOnAllWorkspaces).to.be.true(); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isVisibleOnAllWorkspaces()).to.be.false(); w.setVisibleOnAllWorkspaces(true); expect(w.isVisibleOnAllWorkspaces()).to.be.true(); }); }); }); ifdescribe(process.platform === 'darwin')('documentEdited state', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.documentEdited).to.be.false(); w.documentEdited = true; expect(w.documentEdited).to.be.true(); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isDocumentEdited()).to.be.false(); w.setDocumentEdited(true); expect(w.isDocumentEdited()).to.be.true(); }); }); }); ifdescribe(process.platform === 'darwin')('representedFilename', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.representedFilename).to.eql(''); w.representedFilename = 'a name'; expect(w.representedFilename).to.eql('a name'); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.getRepresentedFilename()).to.eql(''); w.setRepresentedFilename('a name'); expect(w.getRepresentedFilename()).to.eql('a name'); }); }); }); describe('native window title', () => { it('with properties', () => { it('can be set with title constructor option', () => { const w = new BrowserWindow({ show: false, title: 'mYtItLe' }); expect(w.title).to.eql('mYtItLe'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.title).to.eql('Electron Test Main'); w.title = 'NEW TITLE'; expect(w.title).to.eql('NEW TITLE'); }); }); it('with functions', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, title: 'mYtItLe' }); expect(w.getTitle()).to.eql('mYtItLe'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.getTitle()).to.eql('Electron Test Main'); w.setTitle('NEW TITLE'); expect(w.getTitle()).to.eql('NEW TITLE'); }); }); }); describe('minimizable state', () => { it('with properties', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, minimizable: false }); expect(w.minimizable).to.be.false('minimizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.minimizable).to.be.true('minimizable'); w.minimizable = false; expect(w.minimizable).to.be.false('minimizable'); w.minimizable = true; expect(w.minimizable).to.be.true('minimizable'); }); }); it('with functions', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, minimizable: false }); expect(w.isMinimizable()).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMinimizable()).to.be.true('isMinimizable'); w.setMinimizable(false); expect(w.isMinimizable()).to.be.false('isMinimizable'); w.setMinimizable(true); expect(w.isMinimizable()).to.be.true('isMinimizable'); }); }); }); describe('maximizable state (property)', () => { it('with properties', () => { it('can be set with maximizable constructor option', () => { const w = new BrowserWindow({ show: false, maximizable: false }); expect(w.maximizable).to.be.false('maximizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.maximizable).to.be.true('maximizable'); w.maximizable = false; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; expect(w.maximizable).to.be.true('maximizable'); }); it('is not affected when changing other states', () => { const w = new BrowserWindow({ show: false }); w.maximizable = false; expect(w.maximizable).to.be.false('maximizable'); w.minimizable = false; expect(w.maximizable).to.be.false('maximizable'); w.closable = false; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; expect(w.maximizable).to.be.true('maximizable'); w.closable = true; expect(w.maximizable).to.be.true('maximizable'); w.fullScreenable = false; expect(w.maximizable).to.be.true('maximizable'); }); }); it('with functions', () => { it('can be set with maximizable constructor option', () => { const w = new BrowserWindow({ show: false, maximizable: false }); expect(w.isMaximizable()).to.be.false('isMaximizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setMaximizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); it('is not affected when changing other states', () => { const w = new BrowserWindow({ show: false }); w.setMaximizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMinimizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setClosable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setClosable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setFullScreenable(false); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); }); }); ifdescribe(process.platform === 'win32')('maximizable state', () => { it('with properties', () => { it('is reset to its former state', () => { const w = new BrowserWindow({ show: false }); w.maximizable = false; w.resizable = false; w.resizable = true; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; w.resizable = false; w.resizable = true; expect(w.maximizable).to.be.true('maximizable'); }); }); it('with functions', () => { it('is reset to its former state', () => { const w = new BrowserWindow({ show: false }); w.setMaximizable(false); w.setResizable(false); w.setResizable(true); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); w.setResizable(false); w.setResizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); }); }); ifdescribe(process.platform !== 'darwin')('menuBarVisible state', () => { describe('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.menuBarVisible).to.be.true(); w.menuBarVisible = false; expect(w.menuBarVisible).to.be.false(); w.menuBarVisible = true; expect(w.menuBarVisible).to.be.true(); }); }); describe('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); w.setMenuBarVisibility(false); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); w.setMenuBarVisibility(true); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); }); }); }); ifdescribe(process.platform === 'darwin')('fullscreenable state', () => { it('with functions', () => { it('can be set with fullscreenable constructor option', () => { const w = new BrowserWindow({ show: false, fullscreenable: false }); expect(w.isFullScreenable()).to.be.false('isFullScreenable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isFullScreenable()).to.be.true('isFullScreenable'); w.setFullScreenable(false); expect(w.isFullScreenable()).to.be.false('isFullScreenable'); w.setFullScreenable(true); expect(w.isFullScreenable()).to.be.true('isFullScreenable'); }); }); }); // fullscreen events are dispatched eagerly and twiddling things too fast can confuse poor Electron ifdescribe(process.platform === 'darwin')('kiosk state', () => { it('with properties', () => { it('can be set with a constructor property', () => { const w = new BrowserWindow({ kiosk: true }); expect(w.kiosk).to.be.true(); }); it('can be changed ', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.kiosk = true; expect(w.isKiosk()).to.be.true('isKiosk'); await enterFullScreen; await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.kiosk = false; expect(w.isKiosk()).to.be.false('isKiosk'); await leaveFullScreen; }); }); it('with functions', () => { it('can be set with a constructor property', () => { const w = new BrowserWindow({ kiosk: true }); expect(w.isKiosk()).to.be.true(); }); it('can be changed ', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setKiosk(true); expect(w.isKiosk()).to.be.true('isKiosk'); await enterFullScreen; await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setKiosk(false); expect(w.isKiosk()).to.be.false('isKiosk'); await leaveFullScreen; }); }); }); ifdescribe(process.platform === 'darwin')('fullscreen state with resizable set', () => { it('resizable flag should be set to true and restored', async () => { const w = new BrowserWindow({ resizable: false }); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.resizable).to.be.true('resizable'); await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.resizable).to.be.false('resizable'); }); }); ifdescribe(process.platform === 'darwin')('fullscreen state', () => { it('should not cause a crash if called when exiting fullscreen', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; }); it('can be changed with setFullScreen method', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('isFullScreen'); }); it('handles several transitions starting with fullscreen', async () => { const w = new BrowserWindow({ fullscreen: true, show: true }); expect(w.isFullScreen()).to.be.true('not fullscreen'); w.setFullScreen(false); w.setFullScreen(true); const enterFullScreen = emittedNTimes(w, 'enter-full-screen', 2); await enterFullScreen; expect(w.isFullScreen()).to.be.true('not fullscreen'); await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); }); it('handles several transitions in close proximity', async () => { const w = new BrowserWindow(); expect(w.isFullScreen()).to.be.false('is fullscreen'); w.setFullScreen(true); w.setFullScreen(false); w.setFullScreen(true); const enterFullScreen = emittedNTimes(w, 'enter-full-screen', 2); await enterFullScreen; expect(w.isFullScreen()).to.be.true('not fullscreen'); }); it('does not crash when exiting simpleFullScreen (properties)', async () => { const w = new BrowserWindow(); w.setSimpleFullScreen(true); await delay(1000); w.setFullScreen(!w.isFullScreen()); }); it('does not crash when exiting simpleFullScreen (functions)', async () => { const w = new BrowserWindow(); w.simpleFullScreen = true; await delay(1000); w.setFullScreen(!w.isFullScreen()); }); it('should not be changed by setKiosk method', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await delay(); w.setKiosk(true); await delay(); w.setKiosk(false); expect(w.isFullScreen()).to.be.true('isFullScreen'); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('isFullScreen'); }); // FIXME: https://github.com/electron/electron/issues/30140 xit('multiple windows inherit correct fullscreen state', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await delay(); const w2 = new BrowserWindow({ show: false }); const enterFullScreen2 = emittedOnce(w2, 'enter-full-screen'); w2.show(); await enterFullScreen2; expect(w2.isFullScreen()).to.be.true('isFullScreen'); }); }); describe('closable state', () => { it('with properties', () => { it('can be set with closable constructor option', () => { const w = new BrowserWindow({ show: false, closable: false }); expect(w.closable).to.be.false('closable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.closable).to.be.true('closable'); w.closable = false; expect(w.closable).to.be.false('closable'); w.closable = true; expect(w.closable).to.be.true('closable'); }); }); it('with functions', () => { it('can be set with closable constructor option', () => { const w = new BrowserWindow({ show: false, closable: false }); expect(w.isClosable()).to.be.false('isClosable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isClosable()).to.be.true('isClosable'); w.setClosable(false); expect(w.isClosable()).to.be.false('isClosable'); w.setClosable(true); expect(w.isClosable()).to.be.true('isClosable'); }); }); }); describe('hasShadow state', () => { it('with properties', () => { it('returns a boolean on all platforms', () => { const w = new BrowserWindow({ show: false }); expect(w.shadow).to.be.a('boolean'); }); // On Windows there's no shadow by default & it can't be changed dynamically. it('can be changed with hasShadow option', () => { const hasShadow = process.platform !== 'darwin'; const w = new BrowserWindow({ show: false, hasShadow }); expect(w.shadow).to.equal(hasShadow); }); it('can be changed with setHasShadow method', () => { const w = new BrowserWindow({ show: false }); w.shadow = false; expect(w.shadow).to.be.false('hasShadow'); w.shadow = true; expect(w.shadow).to.be.true('hasShadow'); w.shadow = false; expect(w.shadow).to.be.false('hasShadow'); }); }); describe('with functions', () => { it('returns a boolean on all platforms', () => { const w = new BrowserWindow({ show: false }); const hasShadow = w.hasShadow(); expect(hasShadow).to.be.a('boolean'); }); // On Windows there's no shadow by default & it can't be changed dynamically. it('can be changed with hasShadow option', () => { const hasShadow = process.platform !== 'darwin'; const w = new BrowserWindow({ show: false, hasShadow }); expect(w.hasShadow()).to.equal(hasShadow); }); it('can be changed with setHasShadow method', () => { const w = new BrowserWindow({ show: false }); w.setHasShadow(false); expect(w.hasShadow()).to.be.false('hasShadow'); w.setHasShadow(true); expect(w.hasShadow()).to.be.true('hasShadow'); w.setHasShadow(false); expect(w.hasShadow()).to.be.false('hasShadow'); }); }); }); }); describe('window.getMediaSourceId()', () => { afterEach(closeAllWindows); it('returns valid source id', async () => { const w = new BrowserWindow({ show: false }); const shown = emittedOnce(w, 'show'); w.show(); await shown; // Check format 'window:1234:0'. const sourceId = w.getMediaSourceId(); expect(sourceId).to.match(/^window:\d+:\d+$/); }); }); ifdescribe(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('window.getNativeWindowHandle()', () => { afterEach(closeAllWindows); it('returns valid handle', () => { const w = new BrowserWindow({ show: false }); // The module's source code is hosted at // https://github.com/electron/node-is-valid-window const isValidWindow = require('is-valid-window'); expect(isValidWindow(w.getNativeWindowHandle())).to.be.true('is valid window'); }); }); ifdescribe(process.platform === 'darwin')('previewFile', () => { afterEach(closeAllWindows); it('opens the path in Quick Look on macOS', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.previewFile(__filename); w.closeFilePreview(); }).to.not.throw(); }); }); describe('contextIsolation option with and without sandbox option', () => { const expectedContextData = { preloadContext: { preloadProperty: 'number', pageProperty: 'undefined', typeofRequire: 'function', typeofProcess: 'object', typeofArrayPush: 'function', typeofFunctionApply: 'function', typeofPreloadExecuteJavaScriptProperty: 'undefined' }, pageContext: { preloadProperty: 'undefined', pageProperty: 'string', typeofRequire: 'undefined', typeofProcess: 'undefined', typeofArrayPush: 'number', typeofFunctionApply: 'boolean', typeofPreloadExecuteJavaScriptProperty: 'number', typeofOpenedWindow: 'object' } }; afterEach(closeAllWindows); it('separates the page context from the Electron/preload context', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = emittedOnce(ipcMain, 'isolated-world'); iw.loadFile(path.join(fixtures, 'api', 'isolated.html')); const [, data] = await p; expect(data).to.deep.equal(expectedContextData); }); it('recreates the contexts on reload', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); await iw.loadFile(path.join(fixtures, 'api', 'isolated.html')); const isolatedWorld = emittedOnce(ipcMain, 'isolated-world'); iw.webContents.reload(); const [, data] = await isolatedWorld; expect(data).to.deep.equal(expectedContextData); }); it('enables context isolation on child windows', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const browserWindowCreated = emittedOnce(app, 'browser-window-created'); iw.loadFile(path.join(fixtures, 'pages', 'window-open.html')); const [, window] = await browserWindowCreated; expect(window.webContents.getLastWebPreferences().contextIsolation).to.be.true('contextIsolation'); }); it('separates the page context from the Electron/preload context with sandbox on', async () => { const ws = new BrowserWindow({ show: false, webPreferences: { sandbox: true, contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = emittedOnce(ipcMain, 'isolated-world'); ws.loadFile(path.join(fixtures, 'api', 'isolated.html')); const [, data] = await p; expect(data).to.deep.equal(expectedContextData); }); it('recreates the contexts on reload with sandbox on', async () => { const ws = new BrowserWindow({ show: false, webPreferences: { sandbox: true, contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); await ws.loadFile(path.join(fixtures, 'api', 'isolated.html')); const isolatedWorld = emittedOnce(ipcMain, 'isolated-world'); ws.webContents.reload(); const [, data] = await isolatedWorld; expect(data).to.deep.equal(expectedContextData); }); it('supports fetch api', async () => { const fetchWindow = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-fetch-preload.js') } }); const p = emittedOnce(ipcMain, 'isolated-fetch-error'); fetchWindow.loadURL('about:blank'); const [, error] = await p; expect(error).to.equal('Failed to fetch'); }); it('doesn\'t break ipc serialization', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = emittedOnce(ipcMain, 'isolated-world'); iw.loadURL('about:blank'); iw.webContents.executeJavaScript(` const opened = window.open() openedLocation = opened.location.href opened.close() window.postMessage({openedLocation}, '*') `); const [, data] = await p; expect(data.pageContext.openedLocation).to.equal('about:blank'); }); it('reports process.contextIsolated', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-process.js') } }); const p = emittedOnce(ipcMain, 'context-isolation'); iw.loadURL('about:blank'); const [, contextIsolation] = await p; expect(contextIsolation).to.be.true('contextIsolation'); }); }); it('reloading does not cause Node.js module API hangs after reload', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); let count = 0; ipcMain.on('async-node-api-done', () => { if (count === 3) { ipcMain.removeAllListeners('async-node-api-done'); done(); } else { count++; w.reload(); } }); w.loadFile(path.join(fixtures, 'pages', 'send-after-node.html')); }); describe('window.webContents.focus()', () => { afterEach(closeAllWindows); it('focuses window', async () => { const w1 = new BrowserWindow({ x: 100, y: 300, width: 300, height: 200 }); w1.loadURL('about:blank'); const w2 = new BrowserWindow({ x: 300, y: 300, width: 300, height: 200 }); w2.loadURL('about:blank'); const w1Focused = emittedOnce(w1, 'focus'); w1.webContents.focus(); await w1Focused; expect(w1.webContents.isFocused()).to.be.true('focuses window'); }); }); ifdescribe(features.isOffscreenRenderingEnabled())('offscreen rendering', () => { let w: BrowserWindow; beforeEach(function () { w = new BrowserWindow({ width: 100, height: 100, show: false, webPreferences: { backgroundThrottling: false, offscreen: true } }); }); afterEach(closeAllWindows); it('creates offscreen window with correct size', async () => { const paint = emittedOnce(w.webContents, 'paint'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); const [,, data] = await paint; expect(data.constructor.name).to.equal('NativeImage'); expect(data.isEmpty()).to.be.false('data is empty'); const size = data.getSize(); const { scaleFactor } = screen.getPrimaryDisplay(); expect(size.width).to.be.closeTo(100 * scaleFactor, 2); expect(size.height).to.be.closeTo(100 * scaleFactor, 2); }); it('does not crash after navigation', () => { w.webContents.loadURL('about:blank'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); }); describe('window.webContents.isOffscreen()', () => { it('is true for offscreen type', () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); expect(w.webContents.isOffscreen()).to.be.true('isOffscreen'); }); it('is false for regular window', () => { const c = new BrowserWindow({ show: false }); expect(c.webContents.isOffscreen()).to.be.false('isOffscreen'); c.destroy(); }); }); describe('window.webContents.isPainting()', () => { it('returns whether is currently painting', async () => { const paint = emittedOnce(w.webContents, 'paint'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await paint; expect(w.webContents.isPainting()).to.be.true('isPainting'); }); }); describe('window.webContents.stopPainting()', () => { it('stops painting', async () => { const domReady = emittedOnce(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.stopPainting(); expect(w.webContents.isPainting()).to.be.false('isPainting'); }); }); describe('window.webContents.startPainting()', () => { it('starts painting', async () => { const domReady = emittedOnce(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.stopPainting(); w.webContents.startPainting(); await emittedOnce(w.webContents, 'paint'); expect(w.webContents.isPainting()).to.be.true('isPainting'); }); }); describe('frameRate APIs', () => { it('has default frame rate (function)', async () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await emittedOnce(w.webContents, 'paint'); expect(w.webContents.getFrameRate()).to.equal(60); }); it('has default frame rate (property)', async () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await emittedOnce(w.webContents, 'paint'); expect(w.webContents.frameRate).to.equal(60); }); it('sets custom frame rate (function)', async () => { const domReady = emittedOnce(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.setFrameRate(30); await emittedOnce(w.webContents, 'paint'); expect(w.webContents.getFrameRate()).to.equal(30); }); it('sets custom frame rate (property)', async () => { const domReady = emittedOnce(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.frameRate = 30; await emittedOnce(w.webContents, 'paint'); expect(w.webContents.frameRate).to.equal(30); }); }); }); describe('"transparent" option', () => { afterEach(closeAllWindows); // Only applicable on Windows where transparent windows can't be maximized. ifit(process.platform === 'win32')('can show maximized frameless window', async () => { const display = screen.getPrimaryDisplay(); const w = new BrowserWindow({ ...display.bounds, frame: false, transparent: true, show: true }); w.loadURL('about:blank'); await emittedOnce(w, 'ready-to-show'); expect(w.isMaximized()).to.be.true(); // Fails when the transparent HWND is in an invalid maximized state. expect(w.getBounds()).to.deep.equal(display.workArea); const newBounds = { width: 256, height: 256, x: 0, y: 0 }; w.setBounds(newBounds); expect(w.getBounds()).to.deep.equal(newBounds); }); // Linux and arm64 platforms (WOA and macOS) do not return any capture sources ifit(process.platform !== 'linux' && process.arch !== 'arm64')('should not display a visible background', async () => { const display = screen.getPrimaryDisplay(); const backgroundWindow = new BrowserWindow({ ...display.bounds, frame: false, backgroundColor: CHROMA_COLOR_HEX, hasShadow: false }); await backgroundWindow.loadURL('about:blank'); const foregroundWindow = new BrowserWindow({ ...display.bounds, show: true, transparent: true, frame: false, hasShadow: false }); foregroundWindow.loadFile(path.join(__dirname, 'fixtures', 'pages', 'half-background-color.html')); await emittedOnce(foregroundWindow, 'ready-to-show'); const screenCapture = await captureScreen(); const leftHalfColor = getPixelColor(screenCapture, { x: display.size.width / 4, y: display.size.height / 2 }); const rightHalfColor = getPixelColor(screenCapture, { x: display.size.width - (display.size.width / 4), y: display.size.height / 2 }); expect(areColorsSimilar(leftHalfColor, CHROMA_COLOR_HEX)).to.be.true(); expect(areColorsSimilar(rightHalfColor, '#ff0000')).to.be.true(); }); }); describe('"backgroundColor" option', () => { afterEach(closeAllWindows); // Linux/WOA doesn't return any capture sources. ifit(process.platform !== 'linux' && (process.platform !== 'win32' || process.arch !== 'arm64'))('should display the set color', async () => { const display = screen.getPrimaryDisplay(); const w = new BrowserWindow({ ...display.bounds, show: true, backgroundColor: CHROMA_COLOR_HEX }); w.loadURL('about:blank'); await emittedOnce(w, 'ready-to-show'); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); expect(areColorsSimilar(centerColor, CHROMA_COLOR_HEX)).to.be.true(); }); }); });
closed
electron/electron
https://github.com/electron/electron
34,137
[Bug]: Crash on Windows when calling `win.setTitleBarOverlay` on a window that has `titleBarStyle != 'hidden'`
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 18.2.0 ### What operating system are you using? Windows ### Operating System Version Windows 10 version 20H2, build 19042 ### What arch are you using? x64 ### Last Known Working Electron version 18.1.0 ### Expected Behavior When `win.setTitleBarOverlay` is called, apparently the only valid option for `titleBarStyle` is `'hidden'`. So when `win` was created with `titleBarStyle` different from `'hidden'`, Electron should throw an error. ### Actual Behavior Electron crashes unexpectedly. ### Testcase Gist URL https://gist.github.com/wheezard/207499979a7fda8cc7d874fdb87886fc ### Additional Information This might work on older versions, but I haven't tested it in them.
https://github.com/electron/electron/issues/34137
https://github.com/electron/electron/pull/34140
4e3587c7c6e051193c6bbe346192ff08d2b594c1
97c9451efc3035a1072b1ff87aee125f7a9fa053
2022-05-08T18:34:46Z
c++
2022-05-17T15:50:27Z
shell/browser/ui/views/win_frame_view.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. // // Portions of this file are sourced from // chrome/browser/ui/views/frame/glass_browser_frame_view.cc, // Copyright (c) 2012 The Chromium Authors, // which is governed by a BSD-style license #include "shell/browser/ui/views/win_frame_view.h" #include <dwmapi.h> #include <memory> #include "base/win/windows_version.h" #include "shell/browser/native_window_views.h" #include "shell/browser/ui/views/win_caption_button_container.h" #include "ui/base/win/hwnd_metrics.h" #include "ui/display/win/dpi.h" #include "ui/display/win/screen_win.h" #include "ui/gfx/geometry/dip_util.h" #include "ui/views/widget/widget.h" #include "ui/views/win/hwnd_util.h" namespace electron { const char WinFrameView::kViewClassName[] = "WinFrameView"; WinFrameView::WinFrameView() = default; WinFrameView::~WinFrameView() = default; void WinFrameView::Init(NativeWindowViews* window, views::Widget* frame) { window_ = window; frame_ = frame; if (window->IsWindowControlsOverlayEnabled()) { caption_button_container_ = AddChildView(std::make_unique<WinCaptionButtonContainer>(this)); } else { caption_button_container_ = nullptr; } } SkColor WinFrameView::GetReadableFeatureColor(SkColor background_color) { // color_utils::GetColorWithMaxContrast()/IsDark() aren't used here because // they switch based on the Chrome light/dark endpoints, while we want to use // the system native behavior below. const auto windows_luma = [](SkColor c) { return 0.25f * SkColorGetR(c) + 0.625f * SkColorGetG(c) + 0.125f * SkColorGetB(c); }; return windows_luma(background_color) <= 128.0f ? SK_ColorWHITE : SK_ColorBLACK; } void WinFrameView::InvalidateCaptionButtons() { // Ensure that the caption buttons container exists DCHECK(caption_button_container_); caption_button_container_->InvalidateLayout(); caption_button_container_->SchedulePaint(); } gfx::Rect WinFrameView::GetWindowBoundsForClientBounds( const gfx::Rect& client_bounds) const { return views::GetWindowBoundsForClientBounds( static_cast<views::View*>(const_cast<WinFrameView*>(this)), client_bounds); } int WinFrameView::FrameBorderThickness() const { return (IsMaximized() || frame()->IsFullscreen()) ? 0 : display::win::ScreenWin::GetSystemMetricsInDIP(SM_CXSIZEFRAME); } views::View* WinFrameView::TargetForRect(views::View* root, const gfx::Rect& rect) { if (NonClientHitTest(rect.origin()) != HTCLIENT) { // Custom system titlebar returns non HTCLIENT value, however event should // be handled by the view, not by the system, because there are no system // buttons underneath. if (!ShouldCustomDrawSystemTitlebar()) { return this; } auto local_point = rect.origin(); ConvertPointToTarget(parent(), caption_button_container_, &local_point); if (!caption_button_container_->HitTestPoint(local_point)) { return this; } } return NonClientFrameView::TargetForRect(root, rect); } int WinFrameView::NonClientHitTest(const gfx::Point& point) { if (window_->has_frame()) return frame_->client_view()->NonClientHitTest(point); if (ShouldCustomDrawSystemTitlebar()) { // See if the point is within any of the window controls. if (caption_button_container_) { gfx::Point local_point = point; ConvertPointToTarget(parent(), caption_button_container_, &local_point); if (caption_button_container_->HitTestPoint(local_point)) { const int hit_test_result = caption_button_container_->NonClientHitTest(local_point); if (hit_test_result != HTNOWHERE) return hit_test_result; } } // On Windows 8+, the caption buttons are almost butted up to the top right // corner of the window. This code ensures the mouse isn't set to a size // cursor while hovering over the caption buttons, thus giving the incorrect // impression that the user can resize the window. if (base::win::GetVersion() >= base::win::Version::WIN8) { RECT button_bounds = {0}; if (SUCCEEDED(DwmGetWindowAttribute( views::HWNDForWidget(frame()), DWMWA_CAPTION_BUTTON_BOUNDS, &button_bounds, sizeof(button_bounds)))) { gfx::RectF button_bounds_in_dips = gfx::ConvertRectToDips( gfx::Rect(button_bounds), display::win::GetDPIScale()); // TODO(crbug.com/1131681): GetMirroredRect() requires an integer rect, // but the size in DIPs may not be an integer with a fractional device // scale factor. If we want to keep using integers, the choice to use // ToFlooredRectDeprecated() seems to be doing the wrong thing given the // comment below about insetting 1 DIP instead of 1 physical pixel. We // should probably use ToEnclosedRect() and then we could have inset 1 // physical pixel here. gfx::Rect buttons = GetMirroredRect( gfx::ToFlooredRectDeprecated(button_bounds_in_dips)); // There is a small one-pixel strip right above the caption buttons in // which the resize border "peeks" through. constexpr int kCaptionButtonTopInset = 1; // The sizing region at the window edge above the caption buttons is // 1 px regardless of scale factor. If we inset by 1 before converting // to DIPs, the precision loss might eliminate this region entirely. The // best we can do is to inset after conversion. This guarantees we'll // show the resize cursor when resizing is possible. The cost of which // is also maybe showing it over the portion of the DIP that isn't the // outermost pixel. buttons.Inset(gfx::Insets::TLBR(0, kCaptionButtonTopInset, 0, 0)); if (buttons.Contains(point)) return HTNOWHERE; } } int top_border_thickness = FrameTopBorderThickness(false); // At the window corners the resize area is not actually bigger, but the 16 // pixels at the end of the top and bottom edges trigger diagonal resizing. constexpr int kResizeCornerWidth = 16; int window_component = GetHTComponentForFrame( point, gfx::Insets::TLBR(top_border_thickness, 0, 0, 0), top_border_thickness, kResizeCornerWidth - FrameBorderThickness(), frame()->widget_delegate()->CanResize()); if (window_component != HTNOWHERE) return window_component; } // Use the parent class's hittest last return FramelessView::NonClientHitTest(point); } const char* WinFrameView::GetClassName() const { return kViewClassName; } bool WinFrameView::IsMaximized() const { return frame()->IsMaximized(); } bool WinFrameView::ShouldCustomDrawSystemTitlebar() const { return window()->IsWindowControlsOverlayEnabled(); } void WinFrameView::Layout() { LayoutCaptionButtons(); if (window()->IsWindowControlsOverlayEnabled()) { LayoutWindowControlsOverlay(); } NonClientFrameView::Layout(); } int WinFrameView::FrameTopBorderThickness(bool restored) const { // Mouse and touch locations are floored but GetSystemMetricsInDIP is rounded, // so we need to floor instead or else the difference will cause the hittest // to fail when it ought to succeed. return std::floor( FrameTopBorderThicknessPx(restored) / display::win::ScreenWin::GetScaleFactorForHWND(HWNDForView(this))); } int WinFrameView::FrameTopBorderThicknessPx(bool restored) const { // Distinct from FrameBorderThickness() because we can't inset the top // border, otherwise Windows will give us a standard titlebar. // For maximized windows this is not true, and the top border must be // inset in order to avoid overlapping the monitor above. // See comments in BrowserDesktopWindowTreeHostWin::GetClientAreaInsets(). const bool needs_no_border = (ShouldCustomDrawSystemTitlebar() && frame()->IsMaximized()) || frame()->IsFullscreen(); if (needs_no_border && !restored) return 0; // Note that this method assumes an equal resize handle thickness on all // sides of the window. // TODO(dfried): Consider having it return a gfx::Insets object instead. return ui::GetFrameThickness( MonitorFromWindow(HWNDForView(this), MONITOR_DEFAULTTONEAREST)); } int WinFrameView::TitlebarMaximizedVisualHeight() const { int maximized_height = display::win::ScreenWin::GetSystemMetricsInDIP(SM_CYCAPTION); return maximized_height; } // NOTE(@mlaurencin): Usage of IsWebUITabStrip simplified out from Chromium int WinFrameView::TitlebarHeight(int custom_height) const { if (frame()->IsFullscreen() && !IsMaximized()) return 0; int height = TitlebarMaximizedVisualHeight() + FrameTopBorderThickness(false) - WindowTopY(); if (custom_height > TitlebarMaximizedVisualHeight()) height = custom_height - WindowTopY(); return height; } // NOTE(@mlaurencin): Usage of IsWebUITabStrip simplified out from Chromium int WinFrameView::WindowTopY() const { // The window top is SM_CYSIZEFRAME pixels when maximized (see the comment in // FrameTopBorderThickness()) and floor(system dsf) pixels when restored. // Unfortunately we can't represent either of those at hidpi without using // non-integral dips, so we return the closest reasonable values instead. if (IsMaximized()) return FrameTopBorderThickness(false); return 1; } void WinFrameView::LayoutCaptionButtons() { if (!caption_button_container_) return; // Non-custom system titlebar already contains caption buttons. if (!ShouldCustomDrawSystemTitlebar()) { caption_button_container_->SetVisible(false); return; } caption_button_container_->SetVisible(true); const gfx::Size preferred_size = caption_button_container_->GetPreferredSize(); int custom_height = window()->titlebar_overlay_height(); int height = TitlebarHeight(custom_height); // TODO(mlaurencin): This -1 creates a 1 pixel margin between the right // edge of the button container and the edge of the window, allowing for this // edge portion to return the correct hit test and be manually resized // properly. Alternatives can be explored, but the differences in view // structures between Electron and Chromium may result in this as the best // option. int variable_width = IsMaximized() ? preferred_size.width() : preferred_size.width() - 1; caption_button_container_->SetBounds(width() - preferred_size.width(), WindowTopY(), variable_width, height); // Needed for heights larger than default caption_button_container_->SetButtonSize(gfx::Size(0, height)); } void WinFrameView::LayoutWindowControlsOverlay() { int overlay_height = window()->titlebar_overlay_height(); if (overlay_height == 0) { // Accounting for the 1 pixel margin at the top of the button container overlay_height = IsMaximized() ? caption_button_container_->size().height() : caption_button_container_->size().height() + 1; } int overlay_width = caption_button_container_->size().width(); int bounding_rect_width = width() - overlay_width; auto bounding_rect = GetMirroredRect(gfx::Rect(0, 0, bounding_rect_width, overlay_height)); window()->SetWindowControlsOverlayRect(bounding_rect); window()->NotifyLayoutWindowControlsOverlay(); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
34,137
[Bug]: Crash on Windows when calling `win.setTitleBarOverlay` on a window that has `titleBarStyle != 'hidden'`
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 18.2.0 ### What operating system are you using? Windows ### Operating System Version Windows 10 version 20H2, build 19042 ### What arch are you using? x64 ### Last Known Working Electron version 18.1.0 ### Expected Behavior When `win.setTitleBarOverlay` is called, apparently the only valid option for `titleBarStyle` is `'hidden'`. So when `win` was created with `titleBarStyle` different from `'hidden'`, Electron should throw an error. ### Actual Behavior Electron crashes unexpectedly. ### Testcase Gist URL https://gist.github.com/wheezard/207499979a7fda8cc7d874fdb87886fc ### Additional Information This might work on older versions, but I haven't tested it in them.
https://github.com/electron/electron/issues/34137
https://github.com/electron/electron/pull/34140
4e3587c7c6e051193c6bbe346192ff08d2b594c1
97c9451efc3035a1072b1ff87aee125f7a9fa053
2022-05-08T18:34:46Z
c++
2022-05-17T15:50:27Z
spec-main/api-browser-window-spec.ts
import { expect } from 'chai'; import * as childProcess from 'child_process'; import * as path from 'path'; import * as fs from 'fs'; import * as os from 'os'; import * as qs from 'querystring'; import * as http from 'http'; import * as semver from 'semver'; import { AddressInfo } from 'net'; import { app, BrowserWindow, BrowserView, dialog, ipcMain, OnBeforeSendHeadersListenerDetails, protocol, screen, webContents, session, WebContents, BrowserWindowConstructorOptions } from 'electron/main'; import { emittedOnce, emittedUntil, emittedNTimes } from './events-helpers'; import { ifit, ifdescribe, defer, delay } from './spec-helpers'; import { closeWindow, closeAllWindows } from './window-helpers'; import { areColorsSimilar, captureScreen, CHROMA_COLOR_HEX, getPixelColor } from './screen-helpers'; const features = process._linkedBinding('electron_common_features'); const fixtures = path.resolve(__dirname, '..', 'spec', 'fixtures'); const mainFixtures = path.resolve(__dirname, 'fixtures'); // Is the display's scale factor possibly causing rounding of pixel coordinate // values? const isScaleFactorRounding = () => { const { scaleFactor } = screen.getPrimaryDisplay(); // Return true if scale factor is non-integer value if (Math.round(scaleFactor) !== scaleFactor) return true; // Return true if scale factor is odd number above 2 return scaleFactor > 2 && scaleFactor % 2 === 1; }; const expectBoundsEqual = (actual: any, expected: any) => { if (!isScaleFactorRounding()) { expect(expected).to.deep.equal(actual); } else if (Array.isArray(actual)) { expect(actual[0]).to.be.closeTo(expected[0], 1); expect(actual[1]).to.be.closeTo(expected[1], 1); } else { expect(actual.x).to.be.closeTo(expected.x, 1); expect(actual.y).to.be.closeTo(expected.y, 1); expect(actual.width).to.be.closeTo(expected.width, 1); expect(actual.height).to.be.closeTo(expected.height, 1); } }; const isBeforeUnload = (event: Event, level: number, message: string) => { return (message === 'beforeunload'); }; describe('BrowserWindow module', () => { describe('BrowserWindow constructor', () => { it('allows passing void 0 as the webContents', async () => { expect(() => { const w = new BrowserWindow({ show: false, // apparently void 0 had different behaviour from undefined in the // issue that this test is supposed to catch. webContents: void 0 // eslint-disable-line no-void } as any); w.destroy(); }).not.to.throw(); }); ifit(process.platform === 'linux')('does not crash when setting large window icons', async () => { const appPath = path.join(__dirname, 'spec-main', 'fixtures', 'apps', 'xwindow-icon'); const appProcess = childProcess.spawn(process.execPath, [appPath]); await new Promise((resolve) => { appProcess.once('exit', resolve); }); }); it('does not crash or throw when passed an invalid icon', async () => { expect(() => { const w = new BrowserWindow({ icon: undefined } as any); w.destroy(); }).not.to.throw(); }); }); describe('garbage collection', () => { const v8Util = process._linkedBinding('electron_common_v8_util'); afterEach(closeAllWindows); it('window does not get garbage collected when opened', async () => { const w = new BrowserWindow({ show: false }); // Keep a weak reference to the window. // eslint-disable-next-line no-undef const wr = new WeakRef(w); await delay(); // Do garbage collection, since |w| is not referenced in this closure // it would be gone after next call if there is no other reference. v8Util.requestGarbageCollectionForTesting(); await delay(); expect(wr.deref()).to.not.be.undefined(); }); }); describe('BrowserWindow.close()', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('should work if called when a messageBox is showing', async () => { const closed = emittedOnce(w, 'closed'); dialog.showMessageBox(w, { message: 'Hello Error' }); w.close(); await closed; }); it('closes window without rounded corners', async () => { await closeWindow(w); w = new BrowserWindow({ show: false, frame: false, roundedCorners: false }); const closed = emittedOnce(w, 'closed'); w.close(); await closed; }); it('should not crash if called after webContents is destroyed', () => { w.webContents.destroy(); w.webContents.on('destroyed', () => w.close()); }); it('should emit unload handler', async () => { await w.loadFile(path.join(fixtures, 'api', 'unload.html')); const closed = emittedOnce(w, 'closed'); w.close(); await closed; const test = path.join(fixtures, 'api', 'unload'); const content = fs.readFileSync(test); fs.unlinkSync(test); expect(String(content)).to.equal('unload'); }); it('should emit beforeunload handler', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); await emittedOnce(w.webContents, 'before-unload-fired'); }); it('should not crash when keyboard event is sent before closing', async () => { await w.loadURL('data:text/html,pls no crash'); const closed = emittedOnce(w, 'closed'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' }); w.close(); await closed; }); describe('when invoked synchronously inside navigation observer', () => { let server: http.Server = null as unknown as http.Server; let url: string = null as unknown as string; before((done) => { server = http.createServer((request, response) => { switch (request.url) { case '/net-error': response.destroy(); break; case '/301': response.statusCode = 301; response.setHeader('Location', '/200'); response.end(); break; case '/200': response.statusCode = 200; response.end('hello'); break; case '/title': response.statusCode = 200; response.end('<title>Hello</title>'); break; default: throw new Error(`unsupported endpoint: ${request.url}`); } }).listen(0, '127.0.0.1', () => { url = 'http://127.0.0.1:' + (server.address() as AddressInfo).port; done(); }); }); after(() => { server.close(); }); const events = [ { name: 'did-start-loading', path: '/200' }, { name: 'dom-ready', path: '/200' }, { name: 'page-title-updated', path: '/title' }, { name: 'did-stop-loading', path: '/200' }, { name: 'did-finish-load', path: '/200' }, { name: 'did-frame-finish-load', path: '/200' }, { name: 'did-fail-load', path: '/net-error' } ]; for (const { name, path } of events) { it(`should not crash when closed during ${name}`, async () => { const w = new BrowserWindow({ show: false }); w.webContents.once((name as any), () => { w.close(); }); const destroyed = emittedOnce(w.webContents, 'destroyed'); w.webContents.loadURL(url + path); await destroyed; }); } }); }); describe('window.close()', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('should emit unload event', async () => { w.loadFile(path.join(fixtures, 'api', 'close.html')); await emittedOnce(w, 'closed'); const test = path.join(fixtures, 'api', 'close'); const content = fs.readFileSync(test).toString(); fs.unlinkSync(test); expect(content).to.equal('close'); }); it('should emit beforeunload event', async function () { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.webContents.executeJavaScript('window.close()', true); await emittedOnce(w.webContents, 'before-unload-fired'); }); }); describe('BrowserWindow.destroy()', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('prevents users to access methods of webContents', async () => { const contents = w.webContents; w.destroy(); await new Promise(setImmediate); expect(() => { contents.getProcessId(); }).to.throw('Object has been destroyed'); }); it('should not crash when destroying windows with pending events', () => { const focusListener = () => { }; app.on('browser-window-focus', focusListener); const windowCount = 3; const windowOptions = { show: false, width: 400, height: 400, webPreferences: { backgroundThrottling: false } }; const windows = Array.from(Array(windowCount)).map(() => new BrowserWindow(windowOptions)); windows.forEach(win => win.show()); windows.forEach(win => win.focus()); windows.forEach(win => win.destroy()); app.removeListener('browser-window-focus', focusListener); }); }); describe('BrowserWindow.loadURL(url)', () => { let w = null as unknown as BrowserWindow; const scheme = 'other'; const srcPath = path.join(fixtures, 'api', 'loaded-from-dataurl.js'); before(() => { protocol.registerFileProtocol(scheme, (request, callback) => { callback(srcPath); }); }); after(() => { protocol.unregisterProtocol(scheme); }); beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); let server = null as unknown as http.Server; let url = null as unknown as string; let postData = null as any; before((done) => { const filePath = path.join(fixtures, 'pages', 'a.html'); const fileStats = fs.statSync(filePath); postData = [ { type: 'rawData', bytes: Buffer.from('username=test&file=') }, { type: 'file', filePath: filePath, offset: 0, length: fileStats.size, modificationTime: fileStats.mtime.getTime() / 1000 } ]; server = http.createServer((req, res) => { function respond () { if (req.method === 'POST') { let body = ''; req.on('data', (data) => { if (data) body += data; }); req.on('end', () => { const parsedData = qs.parse(body); fs.readFile(filePath, (err, data) => { if (err) return; if (parsedData.username === 'test' && parsedData.file === data.toString()) { res.end(); } }); }); } else if (req.url === '/302') { res.setHeader('Location', '/200'); res.statusCode = 302; res.end(); } else { res.end(); } } setTimeout(respond, req.url && req.url.includes('slow') ? 200 : 0); }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; done(); }); }); after(() => { server.close(); }); it('should emit did-start-loading event', async () => { const didStartLoading = emittedOnce(w.webContents, 'did-start-loading'); w.loadURL('about:blank'); await didStartLoading; }); it('should emit ready-to-show event', async () => { const readyToShow = emittedOnce(w, 'ready-to-show'); w.loadURL('about:blank'); await readyToShow; }); // TODO(deepak1556): The error code now seems to be `ERR_FAILED`, verify what // changed and adjust the test. it.skip('should emit did-fail-load event for files that do not exist', async () => { const didFailLoad = emittedOnce(w.webContents, 'did-fail-load'); w.loadURL('file://a.txt'); const [, code, desc,, isMainFrame] = await didFailLoad; expect(code).to.equal(-6); expect(desc).to.equal('ERR_FILE_NOT_FOUND'); expect(isMainFrame).to.equal(true); }); it('should emit did-fail-load event for invalid URL', async () => { const didFailLoad = emittedOnce(w.webContents, 'did-fail-load'); w.loadURL('http://example:port'); const [, code, desc,, isMainFrame] = await didFailLoad; expect(desc).to.equal('ERR_INVALID_URL'); expect(code).to.equal(-300); expect(isMainFrame).to.equal(true); }); it('should set `mainFrame = false` on did-fail-load events in iframes', async () => { const didFailLoad = emittedOnce(w.webContents, 'did-fail-load'); w.loadFile(path.join(fixtures, 'api', 'did-fail-load-iframe.html')); const [,,,, isMainFrame] = await didFailLoad; expect(isMainFrame).to.equal(false); }); it('does not crash in did-fail-provisional-load handler', (done) => { w.webContents.once('did-fail-provisional-load', () => { w.loadURL('http://127.0.0.1:11111'); done(); }); w.loadURL('http://127.0.0.1:11111'); }); it('should emit did-fail-load event for URL exceeding character limit', async () => { const data = Buffer.alloc(2 * 1024 * 1024).toString('base64'); const didFailLoad = emittedOnce(w.webContents, 'did-fail-load'); w.loadURL(`data:image/png;base64,${data}`); const [, code, desc,, isMainFrame] = await didFailLoad; expect(desc).to.equal('ERR_INVALID_URL'); expect(code).to.equal(-300); expect(isMainFrame).to.equal(true); }); it('should return a promise', () => { const p = w.loadURL('about:blank'); expect(p).to.have.property('then'); }); it('should return a promise that resolves', async () => { await expect(w.loadURL('about:blank')).to.eventually.be.fulfilled(); }); it('should return a promise that rejects on a load failure', async () => { const data = Buffer.alloc(2 * 1024 * 1024).toString('base64'); const p = w.loadURL(`data:image/png;base64,${data}`); await expect(p).to.eventually.be.rejected; }); it('should return a promise that resolves even if pushState occurs during navigation', async () => { const p = w.loadURL('data:text/html,<script>window.history.pushState({}, "/foo")</script>'); await expect(p).to.eventually.be.fulfilled; }); describe('POST navigations', () => { afterEach(() => { w.webContents.session.webRequest.onBeforeSendHeaders(null); }); it('supports specifying POST data', async () => { await w.loadURL(url, { postData }); }); it('sets the content type header on URL encoded forms', async () => { await w.loadURL(url); const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => { w.webContents.session.webRequest.onBeforeSendHeaders((details) => { resolve(details); }); }); w.webContents.executeJavaScript(` form = document.createElement('form') document.body.appendChild(form) form.method = 'POST' form.submit() `); const details = await requestDetails; expect(details.requestHeaders['Content-Type']).to.equal('application/x-www-form-urlencoded'); }); it('sets the content type header on multi part forms', async () => { await w.loadURL(url); const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => { w.webContents.session.webRequest.onBeforeSendHeaders((details) => { resolve(details); }); }); w.webContents.executeJavaScript(` form = document.createElement('form') document.body.appendChild(form) form.method = 'POST' form.enctype = 'multipart/form-data' file = document.createElement('input') file.type = 'file' file.name = 'file' form.appendChild(file) form.submit() `); const details = await requestDetails; expect(details.requestHeaders['Content-Type'].startsWith('multipart/form-data; boundary=----WebKitFormBoundary')).to.equal(true); }); }); it('should support base url for data urls', async () => { await w.loadURL('data:text/html,<script src="loaded-from-dataurl.js"></script>', { baseURLForDataURL: `other://${path.join(fixtures, 'api')}${path.sep}` }); expect(await w.webContents.executeJavaScript('window.ping')).to.equal('pong'); }); }); for (const sandbox of [false, true]) { describe(`navigation events${sandbox ? ' with sandbox' : ''}`, () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: false, sandbox } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('will-navigate event', () => { let server = null as unknown as http.Server; let url = null as unknown as string; before((done) => { server = http.createServer((req, res) => { if (req.url === '/navigate-top') { res.end('<a target=_top href="/">navigate _top</a>'); } else { res.end(''); } }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/`; done(); }); }); after(() => { server.close(); }); it('allows the window to be closed from the event listener', (done) => { w.webContents.once('will-navigate', () => { w.close(); done(); }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('can be prevented', (done) => { let willNavigate = false; w.webContents.once('will-navigate', (e) => { willNavigate = true; e.preventDefault(); }); w.webContents.on('did-stop-loading', () => { if (willNavigate) { // i.e. it shouldn't have had '?navigated' appended to it. try { expect(w.webContents.getURL().endsWith('will-navigate.html')).to.be.true(); done(); } catch (e) { done(e); } } }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('is triggered when navigating from file: to http:', async () => { await w.loadFile(path.join(fixtures, 'api', 'blank.html')); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-navigate', (e, url) => { e.preventDefault(); resolve(url); }); }); expect(navigatedTo).to.equal(url); expect(w.webContents.getURL()).to.match(/^file:/); }); it('is triggered when navigating from about:blank to http:', async () => { await w.loadURL('about:blank'); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-navigate', (e, url) => { e.preventDefault(); resolve(url); }); }); expect(navigatedTo).to.equal(url); expect(w.webContents.getURL()).to.equal('about:blank'); }); it('is triggered when a cross-origin iframe navigates _top', async () => { await w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-top"></iframe>`); await delay(1000); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const iframeTarget = targets.targetInfos.find((t: any) => t.type === 'iframe'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: iframeTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); let willNavigateEmitted = false; w.webContents.on('will-navigate', () => { willNavigateEmitted = true; }); await emittedOnce(w.webContents, 'did-navigate'); expect(willNavigateEmitted).to.be.true(); }); }); describe('will-redirect event', () => { let server = null as unknown as http.Server; let url = null as unknown as string; before((done) => { server = http.createServer((req, res) => { if (req.url === '/302') { res.setHeader('Location', '/200'); res.statusCode = 302; res.end(); } else if (req.url === '/navigate-302') { res.end(`<html><body><script>window.location='${url}/302'</script></body></html>`); } else { res.end(); } }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; done(); }); }); after(() => { server.close(); }); it('is emitted on redirects', async () => { const willRedirect = emittedOnce(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await willRedirect; }); it('is emitted after will-navigate on redirects', async () => { let navigateCalled = false; w.webContents.on('will-navigate', () => { navigateCalled = true; }); const willRedirect = emittedOnce(w.webContents, 'will-redirect'); w.loadURL(`${url}/navigate-302`); await willRedirect; expect(navigateCalled).to.equal(true, 'should have called will-navigate first'); }); it('is emitted before did-stop-loading on redirects', async () => { let stopCalled = false; w.webContents.on('did-stop-loading', () => { stopCalled = true; }); const willRedirect = emittedOnce(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await willRedirect; expect(stopCalled).to.equal(false, 'should not have called did-stop-loading first'); }); it('allows the window to be closed from the event listener', (done) => { w.webContents.once('will-redirect', () => { w.close(); done(); }); w.loadURL(`${url}/302`); }); it('can be prevented', (done) => { w.webContents.once('will-redirect', (event) => { event.preventDefault(); }); w.webContents.on('will-navigate', (e, u) => { expect(u).to.equal(`${url}/302`); }); w.webContents.on('did-stop-loading', () => { try { expect(w.webContents.getURL()).to.equal( `${url}/navigate-302`, 'url should not have changed after navigation event' ); done(); } catch (e) { done(e); } }); w.webContents.on('will-redirect', (e, u) => { try { expect(u).to.equal(`${url}/200`); } catch (e) { done(e); } }); w.loadURL(`${url}/navigate-302`); }); }); }); } describe('focus and visibility', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.show()', () => { it('should focus on window', async () => { await emittedOnce(w, 'focus', () => w.show()); expect(w.isFocused()).to.equal(true); }); it('should make the window visible', async () => { await emittedOnce(w, 'focus', () => w.show()); expect(w.isVisible()).to.equal(true); }); it('emits when window is shown', async () => { const show = emittedOnce(w, 'show'); w.show(); await show; expect(w.isVisible()).to.equal(true); }); }); describe('BrowserWindow.hide()', () => { it('should defocus on window', () => { w.hide(); expect(w.isFocused()).to.equal(false); }); it('should make the window not visible', () => { w.show(); w.hide(); expect(w.isVisible()).to.equal(false); }); it('emits when window is hidden', async () => { const shown = emittedOnce(w, 'show'); w.show(); await shown; const hidden = emittedOnce(w, 'hide'); w.hide(); await hidden; expect(w.isVisible()).to.equal(false); }); }); describe('BrowserWindow.showInactive()', () => { it('should not focus on window', () => { w.showInactive(); expect(w.isFocused()).to.equal(false); }); // TODO(dsanders11): Enable for Linux once CI plays nice with these kinds of tests ifit(process.platform !== 'linux')('should not restore maximized windows', async () => { const maximize = emittedOnce(w, 'maximize'); const shown = emittedOnce(w, 'show'); w.maximize(); // TODO(dsanders11): The maximize event isn't firing on macOS for a window initially hidden if (process.platform !== 'darwin') { await maximize; } else { await delay(1000); } w.showInactive(); await shown; expect(w.isMaximized()).to.equal(true); }); }); describe('BrowserWindow.focus()', () => { it('does not make the window become visible', () => { expect(w.isVisible()).to.equal(false); w.focus(); expect(w.isVisible()).to.equal(false); }); ifit(process.platform !== 'win32')('focuses a blurred window', async () => { { const isBlurred = emittedOnce(w, 'blur'); const isShown = emittedOnce(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 = emittedOnce(w3, 'focus'); const isShown1 = emittedOnce(w1, 'show'); const isShown2 = emittedOnce(w2, 'show'); const isShown3 = emittedOnce(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 = emittedOnce(w1, 'closed'); const isClosed2 = emittedOnce(w2, 'closed'); const isClosed3 = emittedOnce(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 = emittedOnce(w, 'focus'); const isShown = emittedOnce(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 = emittedOnce(w3, 'focus'); const isShown1 = emittedOnce(w1, 'show'); const isShown2 = emittedOnce(w2, 'show'); const isShown3 = emittedOnce(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 = emittedOnce(w1, 'closed'); const isClosed2 = emittedOnce(w2, 'closed'); const isClosed3 = emittedOnce(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 () => { await emittedOnce(w, 'focus', () => w.show()); w.webContents.openDevTools({ mode: 'undocked' }); await emittedOnce(w.webContents, 'devtools-focused'); expect(BrowserWindow.getFocusedWindow()).to.equal(w); }); }); describe('BrowserWindow.moveTop()', () => { it('should not steal focus', async () => { const posDelta = 50; const wShownInactive = emittedOnce(w, 'show'); w.showInactive(); await wShownInactive; expect(w.isFocused()).to.equal(false); const otherWindow = new BrowserWindow({ show: false, title: 'otherWindow' }); const otherWindowShown = emittedOnce(otherWindow, 'show'); const otherWindowFocused = emittedOnce(otherWindow, 'focus'); otherWindow.show(); await otherWindowShown; await otherWindowFocused; expect(otherWindow.isFocused()).to.equal(true); w.moveTop(); const wPos = w.getPosition(); const wMoving = emittedOnce(w, 'move'); w.setPosition(wPos[0] + posDelta, wPos[1] + posDelta); await wMoving; expect(w.isFocused()).to.equal(false); expect(otherWindow.isFocused()).to.equal(true); const wFocused = emittedOnce(w, 'focus'); const otherWindowBlurred = emittedOnce(otherWindow, 'blur'); w.focus(); await wFocused; await otherWindowBlurred; expect(w.isFocused()).to.equal(true); otherWindow.moveTop(); const otherWindowPos = otherWindow.getPosition(); const otherWindowMoving = emittedOnce(otherWindow, 'move'); otherWindow.setPosition(otherWindowPos[0] + posDelta, otherWindowPos[1] + posDelta); await otherWindowMoving; expect(otherWindow.isFocused()).to.equal(false); expect(w.isFocused()).to.equal(true); await closeWindow(otherWindow, { assertNotWindows: false }); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1); }); }); ifdescribe(features.isDesktopCapturerEnabled())('BrowserWindow.moveAbove(mediaSourceId)', () => { it('should throw an exception if wrong formatting', async () => { const fakeSourceIds = [ 'none', 'screen:0', 'window:fake', 'window:1234', 'foobar:1:2' ]; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Invalid media source id/); }); }); it('should throw an exception if wrong type', async () => { const fakeSourceIds = [null as any, 123 as any]; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Error processing argument at index 0 */); }); }); it('should throw an exception if invalid window', async () => { // It is very unlikely that these window id exist. const fakeSourceIds = ['window:99999999:0', 'window:123456:1', 'window:123456:9']; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Invalid media source id/); }); }); it('should not throw an exception', async () => { const w2 = new BrowserWindow({ show: false, title: 'window2' }); const w2Shown = emittedOnce(w2, 'show'); w2.show(); await w2Shown; expect(() => { w.moveAbove(w2.getMediaSourceId()); }).to.not.throw(); await closeWindow(w2, { assertNotWindows: false }); }); }); describe('BrowserWindow.setFocusable()', () => { it('can set unfocusable window to focusable', async () => { const w2 = new BrowserWindow({ focusable: false }); const w2Focused = emittedOnce(w2, 'focus'); w2.setFocusable(true); w2.focus(); await w2Focused; await closeWindow(w2, { assertNotWindows: false }); }); }); describe('BrowserWindow.isFocusable()', () => { it('correctly returns whether a window is focusable', async () => { const w2 = new BrowserWindow({ focusable: false }); expect(w2.isFocusable()).to.be.false(); w2.setFocusable(true); expect(w2.isFocusable()).to.be.true(); await closeWindow(w2, { assertNotWindows: false }); }); }); }); describe('sizing', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, width: 400, height: 400 }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.setBounds(bounds[, animate])', () => { it('sets the window bounds with full bounds', () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds); expectBoundsEqual(w.getBounds(), fullBounds); }); it('sets the window bounds with partial bounds', () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds); const boundsUpdate = { width: 200 }; w.setBounds(boundsUpdate as any); const expectedBounds = Object.assign(fullBounds, boundsUpdate); expectBoundsEqual(w.getBounds(), expectedBounds); }); ifit(process.platform === 'darwin')('on macOS', () => { it('emits \'resized\' event after animating', async () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds, true); await expect(emittedOnce(w, 'resized')).to.eventually.be.fulfilled(); }); }); }); describe('BrowserWindow.setSize(width, height)', () => { it('sets the window size', async () => { const size = [300, 400]; const resized = emittedOnce(w, 'resize'); w.setSize(size[0], size[1]); await resized; expectBoundsEqual(w.getSize(), size); }); ifit(process.platform === 'darwin')('on macOS', () => { it('emits \'resized\' event after animating', async () => { const size = [300, 400]; w.setSize(size[0], size[1], true); await expect(emittedOnce(w, 'resized')).to.eventually.be.fulfilled(); }); }); }); describe('BrowserWindow.setMinimum/MaximumSize(width, height)', () => { it('sets the maximum and minimum size of the window', () => { expect(w.getMinimumSize()).to.deep.equal([0, 0]); expect(w.getMaximumSize()).to.deep.equal([0, 0]); w.setMinimumSize(100, 100); expectBoundsEqual(w.getMinimumSize(), [100, 100]); expectBoundsEqual(w.getMaximumSize(), [0, 0]); w.setMaximumSize(900, 600); expectBoundsEqual(w.getMinimumSize(), [100, 100]); expectBoundsEqual(w.getMaximumSize(), [900, 600]); }); }); describe('BrowserWindow.setAspectRatio(ratio)', () => { it('resets the behaviour when passing in 0', async () => { const size = [300, 400]; w.setAspectRatio(1 / 2); w.setAspectRatio(0); const resize = emittedOnce(w, 'resize'); w.setSize(size[0], size[1]); await resize; expectBoundsEqual(w.getSize(), size); }); it('doesn\'t change bounds when maximum size is set', () => { w.setMenu(null); w.setMaximumSize(400, 400); // Without https://github.com/electron/electron/pull/29101 // following call would shrink the window to 384x361. // There would be also DCHECK in resize_utils.cc on // debug build. w.setAspectRatio(1.0); expectBoundsEqual(w.getSize(), [400, 400]); }); }); describe('BrowserWindow.setPosition(x, y)', () => { it('sets the window position', async () => { const pos = [10, 10]; const move = emittedOnce(w, 'move'); w.setPosition(pos[0], pos[1]); await move; expect(w.getPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setContentSize(width, height)', () => { it('sets the content size', async () => { // NB. The CI server has a very small screen. Attempting to size the window // larger than the screen will limit the window's size to the screen and // cause the test to fail. const size = [456, 567]; w.setContentSize(size[0], size[1]); await new Promise(setImmediate); const after = w.getContentSize(); expect(after).to.deep.equal(size); }); it('works for a frameless window', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 400, height: 400 }); const size = [456, 567]; w.setContentSize(size[0], size[1]); await new Promise(setImmediate); const after = w.getContentSize(); expect(after).to.deep.equal(size); }); }); describe('BrowserWindow.setContentBounds(bounds)', () => { it('sets the content size and position', async () => { const bounds = { x: 10, y: 10, width: 250, height: 250 }; const resize = emittedOnce(w, 'resize'); w.setContentBounds(bounds); await resize; await delay(); expectBoundsEqual(w.getContentBounds(), bounds); }); it('works for a frameless window', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300 }); const bounds = { x: 10, y: 10, width: 250, height: 250 }; const resize = emittedOnce(w, 'resize'); w.setContentBounds(bounds); await resize; await delay(); expectBoundsEqual(w.getContentBounds(), bounds); }); }); describe('BrowserWindow.getBackgroundColor()', () => { it('returns default value if no backgroundColor is set', () => { w.destroy(); w = new BrowserWindow({}); expect(w.getBackgroundColor()).to.equal('#FFFFFF'); }); it('returns correct value if backgroundColor is set', () => { const backgroundColor = '#BBAAFF'; w.destroy(); w = new BrowserWindow({ backgroundColor: backgroundColor }); expect(w.getBackgroundColor()).to.equal(backgroundColor); }); it('returns correct value from setBackgroundColor()', () => { const backgroundColor = '#AABBFF'; w.destroy(); w = new BrowserWindow({}); w.setBackgroundColor(backgroundColor); expect(w.getBackgroundColor()).to.equal(backgroundColor); }); 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 = emittedOnce(w, 'resize'); w.setSize(size[0], size[1]); await resize; expectBoundsEqual(w.getNormalBounds(), w.getBounds()); }); it('checks normal bounds after move', async () => { const pos = [10, 10]; const move = emittedOnce(w, 'move'); w.setPosition(pos[0], pos[1]); await move; expectBoundsEqual(w.getNormalBounds(), w.getBounds()); }); }); ifdescribe(process.platform !== 'linux')('Maximized state', () => { it('checks normal bounds when maximized', async () => { const bounds = w.getBounds(); const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('checks normal bounds when unmaximized', async () => { const bounds = w.getBounds(); w.once('maximize', () => { w.unmaximize(); }); const unmaximize = emittedOnce(w, 'unmaximize'); w.show(); w.maximize(); await unmaximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('does not change size for a frameless window with min size', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300, minWidth: 300, minHeight: 300 }); const bounds = w.getBounds(); w.once('maximize', () => { w.unmaximize(); }); const unmaximize = emittedOnce(w, 'unmaximize'); w.show(); w.maximize(); await unmaximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('correctly checks transparent window maximization state', async () => { w.destroy(); w = new BrowserWindow({ show: false, width: 300, height: 300, transparent: true }); const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; expect(w.isMaximized()).to.equal(true); const unmaximize = emittedOnce(w, 'unmaximize'); w.unmaximize(); await unmaximize; expect(w.isMaximized()).to.equal(false); }); it('returns the correct value for windows with an aspect ratio', async () => { w.destroy(); w = new BrowserWindow({ show: false, fullscreenable: false }); w.setAspectRatio(16 / 11); const maximize = emittedOnce(w, 'resize'); w.show(); w.maximize(); await maximize; expect(w.isMaximized()).to.equal(true); w.resizable = false; expect(w.isMaximized()).to.equal(true); }); }); ifdescribe(process.platform !== 'linux')('Minimized state', () => { it('checks normal bounds when minimized', async () => { const bounds = w.getBounds(); const minimize = emittedOnce(w, 'minimize'); w.show(); w.minimize(); await minimize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('checks normal bounds when restored', async () => { const bounds = w.getBounds(); w.once('minimize', () => { w.restore(); }); const restore = emittedOnce(w, 'restore'); w.show(); w.minimize(); await restore; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('does not change size for a frameless window with min size', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300, minWidth: 300, minHeight: 300 }); const bounds = w.getBounds(); w.once('minimize', () => { w.restore(); }); const restore = emittedOnce(w, 'restore'); w.show(); w.minimize(); await restore; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); ifdescribe(process.platform === 'win32')('Fullscreen state', () => { it('with properties', () => { it('can be set with the fullscreen constructor option', () => { w = new BrowserWindow({ fullscreen: true }); expect(w.fullScreen).to.be.true(); }); it('can be changed', () => { w.fullScreen = false; expect(w.fullScreen).to.be.false(); w.fullScreen = true; expect(w.fullScreen).to.be.true(); }); it('checks normal bounds when fullscreen\'ed', async () => { const bounds = w.getBounds(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.show(); w.fullScreen = true; await enterFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('checks normal bounds when unfullscreen\'ed', async () => { const bounds = w.getBounds(); w.once('enter-full-screen', () => { w.fullScreen = false; }); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.show(); w.fullScreen = true; await leaveFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); it('with functions', () => { it('can be set with the fullscreen constructor option', () => { w = new BrowserWindow({ fullscreen: true }); expect(w.isFullScreen()).to.be.true(); }); it('can be changed', () => { w.setFullScreen(false); expect(w.isFullScreen()).to.be.false(); w.setFullScreen(true); expect(w.isFullScreen()).to.be.true(); }); it('checks normal bounds when fullscreen\'ed', async () => { const bounds = w.getBounds(); w.show(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('checks normal bounds when unfullscreen\'ed', async () => { const bounds = w.getBounds(); w.show(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); }); }); }); ifdescribe(process.platform === 'darwin')('tabbed windows', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.selectPreviousTab()', () => { it('does not throw', () => { expect(() => { w.selectPreviousTab(); }).to.not.throw(); }); }); describe('BrowserWindow.selectNextTab()', () => { it('does not throw', () => { expect(() => { w.selectNextTab(); }).to.not.throw(); }); }); describe('BrowserWindow.mergeAllWindows()', () => { it('does not throw', () => { expect(() => { w.mergeAllWindows(); }).to.not.throw(); }); }); describe('BrowserWindow.moveTabToNewWindow()', () => { it('does not throw', () => { expect(() => { w.moveTabToNewWindow(); }).to.not.throw(); }); }); describe('BrowserWindow.toggleTabBar()', () => { it('does not throw', () => { expect(() => { w.toggleTabBar(); }).to.not.throw(); }); }); describe('BrowserWindow.addTabbedWindow()', () => { it('does not throw', async () => { const tabbedWindow = new BrowserWindow({}); expect(() => { w.addTabbedWindow(tabbedWindow); }).to.not.throw(); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(2); // w + tabbedWindow await closeWindow(tabbedWindow, { assertNotWindows: false }); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1); // w }); it('throws when called on itself', () => { expect(() => { w.addTabbedWindow(w); }).to.throw('AddTabbedWindow cannot be called by a window on itself.'); }); }); }); describe('autoHideMenuBar state', () => { afterEach(closeAllWindows); it('for properties', () => { it('can be set with autoHideMenuBar constructor option', () => { const w = new BrowserWindow({ show: false, autoHideMenuBar: true }); expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); w.autoHideMenuBar = true; expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); w.autoHideMenuBar = false; expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); }); }); it('for functions', () => { it('can be set with autoHideMenuBar constructor option', () => { const w = new BrowserWindow({ show: false, autoHideMenuBar: true }); expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar'); w.setAutoHideMenuBar(true); expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar'); w.setAutoHideMenuBar(false); expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar'); }); }); }); describe('BrowserWindow.capturePage(rect)', () => { afterEach(closeAllWindows); it('returns a Promise with a Buffer', async () => { const w = new BrowserWindow({ show: false }); const image = await w.capturePage({ x: 0, y: 0, width: 100, height: 100 }); expect(image.isEmpty()).to.equal(true); }); it('resolves after the window is hidden', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixtures, 'pages', 'a.html')); await emittedOnce(w, 'ready-to-show'); w.show(); const visibleImage = await w.capturePage(); expect(visibleImage.isEmpty()).to.equal(false); w.hide(); const hiddenImage = await w.capturePage(); const isEmpty = process.platform !== 'darwin'; expect(hiddenImage.isEmpty()).to.equal(isEmpty); }); it('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 emittedOnce(w, 'ready-to-show'); w.webContents.incrementCapturerCount(); 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 emittedOnce(w, 'ready-to-show'); w.show(); const image = await w.capturePage(); const imgBuffer = image.toPNG(); // Check the 25th byte in the PNG. // Values can be 0,2,3,4, or 6. We want 6, which is RGB + Alpha expect(imgBuffer[25]).to.equal(6); }); it('should increase the capturer count', () => { const w = new BrowserWindow({ show: false }); w.webContents.incrementCapturerCount(); expect(w.webContents.isBeingCaptured()).to.be.true(); w.webContents.decrementCapturerCount(); expect(w.webContents.isBeingCaptured()).to.be.false(); }); }); describe('BrowserWindow.setProgressBar(progress)', () => { let w = null as unknown as BrowserWindow; before(() => { w = new BrowserWindow({ show: false }); }); after(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('sets the progress', () => { expect(() => { if (process.platform === 'darwin') { app.dock.setIcon(path.join(fixtures, 'assets', 'logo.png')); } w.setProgressBar(0.5); if (process.platform === 'darwin') { app.dock.setIcon(null as any); } w.setProgressBar(-1); }).to.not.throw(); }); it('sets the progress using "paused" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'paused' }); }).to.not.throw(); }); it('sets the progress using "error" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'error' }); }).to.not.throw(); }); it('sets the progress using "normal" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'normal' }); }).to.not.throw(); }); }); describe('BrowserWindow.setAlwaysOnTop(flag, level)', () => { let w = null as unknown as BrowserWindow; afterEach(closeAllWindows); beforeEach(() => { w = new BrowserWindow({ show: true }); }); it('sets the window as always on top', () => { expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); w.setAlwaysOnTop(false); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); }); ifit(process.platform === 'darwin')('resets the windows level on minimize', () => { expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); w.minimize(); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.restore(); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); }); it('causes the right value to be emitted on `always-on-top-changed`', async () => { const alwaysOnTopChanged = emittedOnce(w, 'always-on-top-changed'); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true); const [, alwaysOnTop] = await alwaysOnTopChanged; expect(alwaysOnTop).to.be.true('is not alwaysOnTop'); }); ifit(process.platform === 'darwin')('honors the alwaysOnTop level of a child window', () => { w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ parent: w }); c.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.false(); expect(c.isAlwaysOnTop()).to.be.true('child is not always on top'); expect((c as any)._getAlwaysOnTopLevel()).to.equal('screen-saver'); }); }); describe('preconnect feature', () => { let w = null as unknown as BrowserWindow; let server = null as unknown as http.Server; let url = null as unknown as string; let connections = 0; beforeEach(async () => { connections = 0; server = http.createServer((req, res) => { if (req.url === '/link') { res.setHeader('Content-type', 'text/html'); res.end('<head><link rel="preconnect" href="//example.com" /></head><body>foo</body>'); return; } res.end(); }); server.on('connection', () => { connections++; }); await new Promise<void>(resolve => server.listen(0, '127.0.0.1', () => resolve())); url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; }); afterEach(async () => { server.close(); await closeWindow(w); w = null as unknown as BrowserWindow; server = null as unknown as http.Server; }); it('calling preconnect() connects to the server', async () => { w = new BrowserWindow({ show: false }); w.webContents.on('did-start-navigation', (event, url) => { w.webContents.session.preconnect({ url, numSockets: 4 }); }); await w.loadURL(url); expect(connections).to.equal(4); }); it('does not preconnect unless requested', async () => { w = new BrowserWindow({ show: false }); await w.loadURL(url); expect(connections).to.equal(1); }); it('parses <link rel=preconnect>', async () => { w = new BrowserWindow({ show: true }); const p = emittedOnce(w.webContents.session, 'preconnect'); w.loadURL(url + '/link'); const [, preconnectUrl, allowCredentials] = await p; expect(preconnectUrl).to.equal('http://example.com/'); expect(allowCredentials).to.be.true('allowCredentials'); }); }); describe('BrowserWindow.setAutoHideCursor(autoHide)', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); ifit(process.platform === 'darwin')('on macOS', () => { it('allows changing cursor auto-hiding', () => { expect(() => { w.setAutoHideCursor(false); w.setAutoHideCursor(true); }).to.not.throw(); }); }); ifit(process.platform !== 'darwin')('on non-macOS platforms', () => { it('is not available', () => { expect(w.setAutoHideCursor).to.be.undefined('setAutoHideCursor function'); }); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setWindowButtonVisibility()', () => { afterEach(closeAllWindows); it('does not throw', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setWindowButtonVisibility(true); w.setWindowButtonVisibility(false); }).to.not.throw(); }); it('changes window button visibility for normal window', () => { const w = new BrowserWindow({ show: false }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); it('changes window button visibility for frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); }); it('changes window button visibility for hiddenInset window', () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hiddenInset' }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); // Buttons of customButtonsOnHover are always hidden unless hovered. it('does not change window button visibility for customButtonsOnHover window', () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'customButtonsOnHover' }); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setVibrancy(type)', () => { let appProcess: childProcess.ChildProcessWithoutNullStreams | childProcess.ChildProcess | undefined; afterEach(() => { if (appProcess && !appProcess.killed) { appProcess.kill(); appProcess = undefined; } closeAllWindows(); }); it('allows setting, changing, and removing the vibrancy', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setVibrancy('light'); w.setVibrancy('dark'); w.setVibrancy(null); w.setVibrancy('ultra-dark'); w.setVibrancy('' as any); }).to.not.throw(); }); it('does not crash if vibrancy is set to an invalid value', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setVibrancy('i-am-not-a-valid-vibrancy-type' as any); }).to.not.throw(); }); it('Allows setting a transparent window via CSS', async () => { const appPath = path.join(__dirname, 'fixtures', 'apps', 'background-color-transparent'); appProcess = childProcess.spawn(process.execPath, [appPath], { stdio: 'inherit' }); const [code] = await emittedOnce(appProcess, 'exit'); expect(code).to.equal(0); }); }); ifdescribe(process.platform === 'darwin')('trafficLightPosition', () => { const pos = { x: 10, y: 10 }; afterEach(closeAllWindows); describe('BrowserWindow.getTrafficLightPosition(pos)', () => { it('gets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); expect(w.getTrafficLightPosition()).to.deep.equal(pos); }); it('gets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); expect(w.getTrafficLightPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setTrafficLightPosition(pos)', () => { it('sets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setTrafficLightPosition(newPos); expect(w.getTrafficLightPosition()).to.deep.equal(newPos); }); it('sets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setTrafficLightPosition(newPos); expect(w.getTrafficLightPosition()).to.deep.equal(newPos); }); }); }); ifdescribe(process.platform === 'win32')('BrowserWindow.setAppDetails(options)', () => { afterEach(closeAllWindows); it('supports setting the app details', () => { const w = new BrowserWindow({ show: false }); const iconPath = path.join(fixtures, 'assets', 'icon.ico'); expect(() => { w.setAppDetails({ appId: 'my.app.id' }); w.setAppDetails({ appIconPath: iconPath, appIconIndex: 0 }); w.setAppDetails({ appIconPath: iconPath }); w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name' }); w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2' }); w.setAppDetails({ relaunchDisplayName: 'My app name' }); w.setAppDetails({ appId: 'my.app.id', appIconPath: iconPath, appIconIndex: 0, relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name' }); w.setAppDetails({}); }).to.not.throw(); expect(() => { (w.setAppDetails as any)(); }).to.throw('Insufficient number of arguments.'); }); }); describe('BrowserWindow.fromId(id)', () => { afterEach(closeAllWindows); it('returns the window with id', () => { const w = new BrowserWindow({ show: false }); expect(BrowserWindow.fromId(w.id)!.id).to.equal(w.id); }); }); describe('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 emittedOnce(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 any).create({}); try { expect(BrowserWindow.fromWebContents(contents)).to.be.null('BrowserWindow.fromWebContents(contents)'); } finally { contents.destroy(); } }); it('returns the correct window for a BrowserView webcontents', async () => { const w = new BrowserWindow({ show: false }); const bv = new BrowserView(); w.setBrowserView(bv); defer(() => { w.removeBrowserView(bv); (bv.webContents as any).destroy(); }); await bv.webContents.loadURL('about:blank'); expect(BrowserWindow.fromWebContents(bv.webContents)!.id).to.equal(w.id); }); it('returns the correct window for a WebView webcontents', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } }); w.loadURL('data:text/html,<webview src="data:text/html,hi"></webview>'); // NOTE(nornagon): Waiting for 'did-attach-webview' is a workaround for // https://github.com/electron/electron/issues/25413, and is not integral // to the test. const p = emittedOnce(w.webContents, 'did-attach-webview'); const [, webviewContents] = await emittedOnce(app, 'web-contents-created'); expect(BrowserWindow.fromWebContents(webviewContents)!.id).to.equal(w.id); await p; }); 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((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 as any).destroy(); }); expect(BrowserWindow.fromBrowserView(bv)!.id).to.equal(w.id); }); it('returns the window when there are multiple BrowserViews', () => { const w = new BrowserWindow({ show: false }); const bv1 = new BrowserView(); w.addBrowserView(bv1); const bv2 = new BrowserView(); w.addBrowserView(bv2); defer(() => { w.removeBrowserView(bv1); w.removeBrowserView(bv2); (bv1.webContents as any).destroy(); (bv2.webContents as any).destroy(); }); expect(BrowserWindow.fromBrowserView(bv1)!.id).to.equal(w.id); expect(BrowserWindow.fromBrowserView(bv2)!.id).to.equal(w.id); }); it('returns undefined if not attached', () => { const bv = new BrowserView(); defer(() => { (bv.webContents as any).destroy(); }); expect(BrowserWindow.fromBrowserView(bv)).to.be.null('BrowserWindow associated with bv'); }); }); describe('BrowserWindow.setOpacity(opacity)', () => { afterEach(closeAllWindows); ifdescribe(process.platform !== 'linux')(('Windows and Mac'), () => { it('make window with initial opacity', () => { const w = new BrowserWindow({ show: false, opacity: 0.5 }); expect(w.getOpacity()).to.equal(0.5); }); it('allows setting the opacity', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setOpacity(0.0); expect(w.getOpacity()).to.equal(0.0); w.setOpacity(0.5); expect(w.getOpacity()).to.equal(0.5); w.setOpacity(1.0); expect(w.getOpacity()).to.equal(1.0); }).to.not.throw(); }); it('clamps opacity to [0.0...1.0]', () => { const w = new BrowserWindow({ show: false, opacity: 0.5 }); w.setOpacity(100); expect(w.getOpacity()).to.equal(1.0); w.setOpacity(-100); expect(w.getOpacity()).to.equal(0.0); }); }); ifdescribe(process.platform === 'linux')(('Linux'), () => { it('sets 1 regardless of parameter', () => { const w = new BrowserWindow({ show: false }); w.setOpacity(0); expect(w.getOpacity()).to.equal(1.0); w.setOpacity(0.5); expect(w.getOpacity()).to.equal(1.0); }); }); }); describe('BrowserWindow.setShape(rects)', () => { afterEach(closeAllWindows); it('allows setting shape', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setShape([]); w.setShape([{ x: 0, y: 0, width: 100, height: 100 }]); w.setShape([{ x: 0, y: 0, width: 100, height: 100 }, { x: 0, y: 200, width: 1000, height: 100 }]); w.setShape([]); }).to.not.throw(); }); }); describe('"useContentSize" option', () => { afterEach(closeAllWindows); it('make window created with content size when used', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, useContentSize: true }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); it('make window created with window size when not used', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400 }); const size = w.getSize(); expect(size).to.deep.equal([400, 400]); }); it('works for a frameless window', () => { const w = new BrowserWindow({ show: false, frame: false, width: 400, height: 400, useContentSize: true }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); const size = w.getSize(); expect(size).to.deep.equal([400, 400]); }); }); ifdescribe(process.platform === 'win32' || (process.platform === 'darwin' && semver.gte(os.release(), '14.0.0')))('"titleBarStyle" option', () => { const testWindowsOverlay = async (style: any) => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: style, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: true }); const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); if (process.platform === 'darwin') { await w.loadFile(overlayHTML); } else { const overlayReady = emittedOnce(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const overlayRect = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(overlayRect.y).to.equal(0); if (process.platform === 'darwin') { expect(overlayRect.x).to.be.greaterThan(0); } else { expect(overlayRect.x).to.equal(0); } expect(overlayRect.width).to.be.greaterThan(0); expect(overlayRect.height).to.be.greaterThan(0); const cssOverlayRect = await w.webContents.executeJavaScript('getCssOverlayProperties();'); expect(cssOverlayRect).to.deep.equal(overlayRect); const geometryChange = emittedOnce(ipcMain, 'geometrychange'); w.setBounds({ width: 800 }); const [, newOverlayRect] = await geometryChange; expect(newOverlayRect.width).to.equal(overlayRect.width + 400); }; afterEach(closeAllWindows); afterEach(() => { ipcMain.removeAllListeners('geometrychange'); }); it('creates browser window with hidden title bar', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden' }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); ifit(process.platform === 'darwin')('creates browser window with hidden inset title bar', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hiddenInset' }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); it('sets Window Control Overlay with hidden title bar', async () => { await testWindowsOverlay('hidden'); }); ifit(process.platform === 'darwin')('sets Window Control Overlay with hidden inset title bar', async () => { await testWindowsOverlay('hiddenInset'); }); }); ifdescribe(process.platform === 'win32' || (process.platform === 'darwin' && semver.gte(os.release(), '14.0.0')))('"titleBarOverlay" option', () => { const testWindowsOverlayHeight = async (size: any) => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden', webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { height: size } }); const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); if (process.platform === 'darwin') { await w.loadFile(overlayHTML); } else { const overlayReady = emittedOnce(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const overlayRectPreMax = await w.webContents.executeJavaScript('getJSOverlayProperties()'); if (!w.isMaximized()) { const maximize = emittedOnce(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(closeAllWindows); afterEach(() => { 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(closeAllWindows); afterEach(() => { ipcMain.removeAllListeners('geometrychange'); }); it('correctly updates the height of the overlay', async () => { const testOverlay = async (w: BrowserWindow, size: Number) => { const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); w.loadFile(overlayHTML); await emittedOnce(ipcMain, 'geometrychange'); 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 = emittedOnce(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); w.setTitleBarOverlay({ height: INITIAL_SIZE + 10 }); await testOverlay(w, INITIAL_SIZE + 10); }); }); ifdescribe(process.platform === 'darwin')('"enableLargerThanScreen" option', () => { afterEach(closeAllWindows); it('can move the window out of screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); w.setPosition(-10, 50); const after = w.getPosition(); expect(after).to.deep.equal([-10, 50]); }); it('cannot move the window behind menu bar', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[1]).to.be.at.least(0); }); it('can move the window behind menu bar if it has no frame', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true, frame: false }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[0]).to.be.equal(-10); expect(after[1]).to.be.equal(-10); }); it('without it, cannot move the window out of screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: false }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[1]).to.be.at.least(0); }); it('can set the window larger than screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); const size = screen.getPrimaryDisplay().size; size.width += 100; size.height += 100; w.setSize(size.width, size.height); expectBoundsEqual(w.getSize(), [size.width, size.height]); }); it('without it, cannot set the window larger than screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: false }); const size = screen.getPrimaryDisplay().size; size.width += 100; size.height += 100; w.setSize(size.width, size.height); expect(w.getSize()[1]).to.at.most(screen.getPrimaryDisplay().size.height); }); }); ifdescribe(process.platform === 'darwin')('"zoomToPageWidth" option', () => { afterEach(closeAllWindows); it('sets the window width to the page width when used', () => { const w = new BrowserWindow({ show: false, width: 500, height: 400, zoomToPageWidth: true }); w.maximize(); expect(w.getSize()[0]).to.equal(500); }); }); describe('"tabbingIdentifier" option', () => { afterEach(closeAllWindows); it('can be set on a window', () => { expect(() => { /* eslint-disable no-new */ new BrowserWindow({ tabbingIdentifier: 'group1' }); new BrowserWindow({ tabbingIdentifier: 'group2', frame: false }); /* eslint-enable no-new */ }).not.to.throw(); }); }); describe('"webPreferences" option', () => { afterEach(() => { ipcMain.removeAllListeners('answer'); }); afterEach(closeAllWindows); describe('"preload" option', () => { const doesNotLeakSpec = (name: string, webPrefs: { nodeIntegration: boolean, sandbox: boolean, contextIsolation: boolean }) => { it(name, async () => { const w = new BrowserWindow({ webPreferences: { ...webPrefs, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'no-leak.html')); const [, result] = await emittedOnce(ipcMain, 'leak-result'); expect(result).to.have.property('require', 'undefined'); expect(result).to.have.property('exports', 'undefined'); expect(result).to.have.property('windowExports', 'undefined'); expect(result).to.have.property('windowPreload', 'undefined'); expect(result).to.have.property('windowRequire', 'undefined'); }); }; doesNotLeakSpec('does not leak require', { nodeIntegration: false, sandbox: false, contextIsolation: false }); doesNotLeakSpec('does not leak require when sandbox is enabled', { nodeIntegration: false, sandbox: true, contextIsolation: false }); doesNotLeakSpec('does not leak require when context isolation is enabled', { nodeIntegration: false, sandbox: false, contextIsolation: true }); doesNotLeakSpec('does not leak require when context isolation and sandbox are enabled', { nodeIntegration: false, sandbox: true, contextIsolation: true }); it('does not leak any node globals on the window object with nodeIntegration is disabled', async () => { let w = new BrowserWindow({ webPreferences: { contextIsolation: false, nodeIntegration: false, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'globals.html')); const [, notIsolated] = await emittedOnce(ipcMain, 'leak-result'); expect(notIsolated).to.have.property('globals'); w.destroy(); w = new BrowserWindow({ webPreferences: { contextIsolation: true, nodeIntegration: false, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'globals.html')); const [, isolated] = await emittedOnce(ipcMain, 'leak-result'); expect(isolated).to.have.property('globals'); const notIsolatedGlobals = new Set(notIsolated.globals); for (const isolatedGlobal of isolated.globals) { notIsolatedGlobals.delete(isolatedGlobal); } expect([...notIsolatedGlobals]).to.deep.equal([], 'non-isoalted renderer should have no additional globals'); }); it('loads the script before other scripts in window', async () => { const preload = path.join(fixtures, 'module', 'set-global.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false, preload } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test).to.eql('preload'); }); it('has synchronous access to all eventual window APIs', async () => { const preload = path.join(fixtures, 'module', 'access-blink-apis.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false, preload } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test).to.be.an('object'); expect(test.atPreload).to.be.an('array'); expect(test.atLoad).to.be.an('array'); expect(test.atPreload).to.deep.equal(test.atLoad, 'should have access to the same window APIs'); }); }); describe('session preload scripts', function () { const preloads = [ path.join(fixtures, 'module', 'set-global-preload-1.js'), path.join(fixtures, 'module', 'set-global-preload-2.js'), path.relative(process.cwd(), path.join(fixtures, 'module', 'set-global-preload-3.js')) ]; const defaultSession = session.defaultSession; beforeEach(() => { expect(defaultSession.getPreloads()).to.deep.equal([]); defaultSession.setPreloads(preloads); }); afterEach(() => { defaultSession.setPreloads([]); }); it('can set multiple session preload script', () => { expect(defaultSession.getPreloads()).to.deep.equal(preloads); }); const generateSpecs = (description: string, sandbox: boolean) => { describe(description, () => { it('loads the script before other scripts in window including normal preloads', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox, preload: path.join(fixtures, 'module', 'get-global-preload.js'), contextIsolation: false } }); w.loadURL('about:blank'); const [, preload1, preload2, preload3] = await emittedOnce(ipcMain, 'vars'); expect(preload1).to.equal('preload-1'); expect(preload2).to.equal('preload-1-2'); expect(preload3).to.be.undefined('preload 3'); }); }); }; generateSpecs('without sandbox', false); generateSpecs('with sandbox', true); }); describe('"additionalArguments" option', () => { it('adds extra args to process.argv in the renderer process', async () => { const preload = path.join(fixtures, 'module', 'check-arguments.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, preload, additionalArguments: ['--my-magic-arg'] } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, argv] = await emittedOnce(ipcMain, 'answer'); expect(argv).to.include('--my-magic-arg'); }); it('adds extra value args to process.argv in the renderer process', async () => { const preload = path.join(fixtures, 'module', 'check-arguments.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, preload, additionalArguments: ['--my-magic-arg=foo'] } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, argv] = await emittedOnce(ipcMain, 'answer'); expect(argv).to.include('--my-magic-arg=foo'); }); }); describe('"node-integration" option', () => { it('disables node integration by default', async () => { const preload = path.join(fixtures, 'module', 'send-later.js'); const w = new BrowserWindow({ show: false, webPreferences: { preload, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, typeofProcess, typeofBuffer] = await emittedOnce(ipcMain, 'answer'); expect(typeofProcess).to.equal('undefined'); expect(typeofBuffer).to.equal('undefined'); }); }); describe('"sandbox" option', () => { const preload = path.join(path.resolve(__dirname, 'fixtures'), 'module', 'preload-sandbox.js'); let server: http.Server = null as unknown as http.Server; let serverUrl: string = null as unknown as string; before((done) => { server = http.createServer((request, response) => { switch (request.url) { case '/cross-site': response.end(`<html><body><h1>${request.url}</h1></body></html>`); break; default: throw new Error(`unsupported endpoint: ${request.url}`); } }).listen(0, '127.0.0.1', () => { serverUrl = 'http://127.0.0.1:' + (server.address() as AddressInfo).port; done(); }); }); after(() => { server.close(); }); it('exposes ipcRenderer to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test).to.equal('preload'); }); it('exposes ipcRenderer to preload script (path has special chars)', async () => { const preloadSpecialChars = path.join(fixtures, 'module', 'preload-sandboxæø åü.js'); const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload: preloadSpecialChars, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test).to.equal('preload'); }); it('exposes "loaded" event to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload } }); w.loadURL('about:blank'); await emittedOnce(ipcMain, 'process-loaded'); }); it('exposes "exit" event to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?exit-event'); const pageUrl = 'file://' + htmlPath; w.loadURL(pageUrl); const [, url] = await emittedOnce(ipcMain, 'answer'); const expectedUrl = process.platform === 'win32' ? 'file:///' + htmlPath.replace(/\\/g, '/') : pageUrl; expect(url).to.equal(expectedUrl); }); it('should open windows in same domain with cross-scripting enabled', async () => { const w = new BrowserWindow({ show: true, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload } } })); const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?window-open'); const pageUrl = 'file://' + htmlPath; const answer = emittedOnce(ipcMain, 'answer'); w.loadURL(pageUrl); const [, { url, frameName, options }] = await emittedOnce(w.webContents, 'did-create-window'); const expectedUrl = process.platform === 'win32' ? 'file:///' + htmlPath.replace(/\\/g, '/') : pageUrl; expect(url).to.equal(expectedUrl); expect(frameName).to.equal('popup!'); expect(options.width).to.equal(500); expect(options.height).to.equal(600); const [, html] = await answer; expect(html).to.equal('<h1>scripting from opener</h1>'); }); it('should open windows in another domain with cross-scripting disabled', async () => { const w = new BrowserWindow({ show: true, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload } } })); w.loadFile( path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'window-open-external' } ); // Wait for a message from the main window saying that it's ready. await emittedOnce(ipcMain, 'opener-loaded'); // Ask the opener to open a popup with window.opener. const expectedPopupUrl = `${serverUrl}/cross-site`; // Set in "sandbox.html". w.webContents.send('open-the-popup', expectedPopupUrl); // The page is going to open a popup that it won't be able to close. // We have to close it from here later. const [, popupWindow] = await emittedOnce(app, 'browser-window-created'); // Ask the popup window for details. const detailsAnswer = emittedOnce(ipcMain, 'child-loaded'); popupWindow.webContents.send('provide-details'); const [, openerIsNull, , locationHref] = await detailsAnswer; expect(openerIsNull).to.be.false('window.opener is null'); expect(locationHref).to.equal(expectedPopupUrl); // Ask the page to access the popup. const touchPopupResult = emittedOnce(ipcMain, 'answer'); w.webContents.send('touch-the-popup'); const [, popupAccessMessage] = await touchPopupResult; // Ask the popup to access the opener. const touchOpenerResult = emittedOnce(ipcMain, 'answer'); popupWindow.webContents.send('touch-the-opener'); const [, openerAccessMessage] = await touchOpenerResult; // We don't need the popup anymore, and its parent page can't close it, // so let's close it from here before we run any checks. await closeWindow(popupWindow, { assertNotWindows: false }); expect(popupAccessMessage).to.be.a('string', 'child\'s .document is accessible from its parent window'); expect(popupAccessMessage).to.match(/^Blocked a frame with origin/); expect(openerAccessMessage).to.be.a('string', 'opener .document is accessible from a popup window'); expect(openerAccessMessage).to.match(/^Blocked a frame with origin/); }); it('should inherit the sandbox setting in opened windows', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [, { argv }] = await emittedOnce(ipcMain, 'answer'); expect(argv).to.include('--enable-sandbox'); }); it('should open windows with the options configured via new-window event listeners', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath, contextIsolation: false } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [[, childWebContents]] = await Promise.all([ emittedOnce(app, 'web-contents-created'), emittedOnce(ipcMain, 'answer') ]); const webPreferences = childWebContents.getLastWebPreferences(); expect(webPreferences.contextIsolation).to.equal(false); }); it('should set ipc event sender correctly', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); let childWc: WebContents | null = null; w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload, contextIsolation: false } } })); w.webContents.on('did-create-window', (win) => { childWc = win.webContents; expect(w.webContents).to.not.equal(childWc); }); ipcMain.once('parent-ready', function (event) { expect(event.sender).to.equal(w.webContents, 'sender should be the parent'); event.sender.send('verified'); }); ipcMain.once('child-ready', function (event) { expect(childWc).to.not.be.null('child webcontents should be available'); expect(event.sender).to.equal(childWc, 'sender should be the child'); event.sender.send('verified'); }); const done = Promise.all([ 'parent-answer', 'child-answer' ].map(name => emittedOnce(ipcMain, name))); w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'verify-ipc-sender' }); await done; }); describe('event handling', () => { let w: BrowserWindow = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); }); it('works for window events', async () => { const pageTitleUpdated = emittedOnce(w, 'page-title-updated'); w.loadURL('data:text/html,<script>document.title = \'changed\'</script>'); await pageTitleUpdated; }); it('works for stop events', async () => { const done = Promise.all([ 'did-navigate', 'did-fail-load', 'did-stop-loading' ].map(name => emittedOnce(w.webContents, name))); w.loadURL('data:text/html,<script>stop()</script>'); await done; }); it('works for web contents events', async () => { const done = Promise.all([ 'did-finish-load', 'did-frame-finish-load', 'did-navigate-in-page', 'will-navigate', 'did-start-loading', 'did-stop-loading', 'did-frame-finish-load', 'dom-ready' ].map(name => emittedOnce(w.webContents, name))); w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'webcontents-events' }); await done; }); }); it('supports calling preventDefault on new-window events', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const initialWebContents = webContents.getAllWebContents().map((i) => i.id); w.webContents.once('new-window', (e) => { e.preventDefault(); // We need to give it some time so the windows get properly disposed (at least on OSX). setTimeout(() => { const currentWebContents = webContents.getAllWebContents().map((i) => i.id); try { expect(currentWebContents).to.deep.equal(initialWebContents); done(); } catch (error) { done(e); } }, 100); }); w.loadFile(path.join(fixtures, 'pages', 'window-open.html')); }); it('validates process APIs access in sandboxed renderer', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.once('preload-error', (event, preloadPath, error) => { throw error; }); process.env.sandboxmain = 'foo'; w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test.hasCrash).to.be.true('has crash'); expect(test.hasHang).to.be.true('has hang'); expect(test.heapStatistics).to.be.an('object'); expect(test.blinkMemoryInfo).to.be.an('object'); expect(test.processMemoryInfo).to.be.an('object'); expect(test.systemVersion).to.be.a('string'); expect(test.cpuUsage).to.be.an('object'); expect(test.ioCounters).to.be.an('object'); expect(test.uptime).to.be.a('number'); expect(test.arch).to.equal(process.arch); expect(test.platform).to.equal(process.platform); expect(test.env).to.deep.equal(process.env); expect(test.execPath).to.equal(process.helperExecPath); expect(test.sandboxed).to.be.true('sandboxed'); expect(test.contextIsolated).to.be.false('contextIsolated'); expect(test.type).to.equal('renderer'); expect(test.version).to.equal(process.version); expect(test.versions).to.deep.equal(process.versions); expect(test.contextId).to.be.a('string'); if (process.platform === 'linux' && test.osSandbox) { expect(test.creationTime).to.be.null('creation time'); expect(test.systemMemoryInfo).to.be.null('system memory info'); } else { expect(test.creationTime).to.be.a('number'); expect(test.systemMemoryInfo).to.be.an('object'); } }); it('webview in sandbox renderer', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, webviewTag: true, contextIsolation: false } }); const didAttachWebview = emittedOnce(w.webContents, 'did-attach-webview'); const webviewDomReady = emittedOnce(ipcMain, 'webview-dom-ready'); w.loadFile(path.join(fixtures, 'pages', 'webview-did-attach-event.html')); const [, webContents] = await didAttachWebview; const [, id] = await webviewDomReady; expect(webContents.id).to.equal(id); }); }); describe('child windows', () => { let w: BrowserWindow = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, // tests relies on preloads in opened windows nodeIntegrationInSubFrames: true, contextIsolation: false } }); }); it('opens window of about:blank with cross-scripting enabled', async () => { const answer = emittedOnce(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-blank.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('opens window of same domain with cross-scripting enabled', async () => { const answer = emittedOnce(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-file.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('blocks accessing cross-origin frames', async () => { const answer = emittedOnce(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-cross-origin.html')); const [, content] = await answer; expect(content).to.equal('Blocked a frame with origin "file://" from accessing a cross-origin frame.'); }); it('opens window from <iframe> tags', async () => { const answer = emittedOnce(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-iframe.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('opens window with cross-scripting enabled from isolated context', async () => { const w = new BrowserWindow({ show: false, webPreferences: { preload: path.join(fixtures, 'api', 'native-window-open-isolated-preload.js') } }); w.loadFile(path.join(fixtures, 'api', 'native-window-open-isolated.html')); const [, content] = await emittedOnce(ipcMain, 'answer'); expect(content).to.equal('Hello'); }); ifit(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('loads native addons correctly after reload', async () => { w.loadFile(path.join(__dirname, 'fixtures', 'api', 'native-window-open-native-addon.html')); { const [, content] = await emittedOnce(ipcMain, 'answer'); expect(content).to.equal('function'); } w.reload(); { const [, content] = await emittedOnce(ipcMain, 'answer'); expect(content).to.equal('function'); } }); it('<webview> works in a scriptable popup', async () => { const preload = path.join(fixtures, 'api', 'new-window-webview-preload.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegrationInSubFrames: true, webviewTag: true, contextIsolation: false, preload } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { show: false, webPreferences: { contextIsolation: false, webviewTag: true, nodeIntegrationInSubFrames: true } } })); w.webContents.once('new-window', (event, url, frameName, disposition, options) => { options.show = false; }); const webviewLoaded = emittedOnce(ipcMain, 'webview-loaded'); w.loadFile(path.join(fixtures, 'api', 'new-window-webview.html')); await webviewLoaded; }); it('should open windows with the options configured via new-window event listeners', async () => { const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath, contextIsolation: false } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [[, childWebContents]] = await Promise.all([ emittedOnce(app, 'web-contents-created'), emittedOnce(ipcMain, 'answer') ]); const webPreferences = childWebContents.getLastWebPreferences(); expect(webPreferences.contextIsolation).to.equal(false); }); describe('window.location', () => { const protocols = [ ['foo', path.join(fixtures, 'api', 'window-open-location-change.html')], ['bar', path.join(fixtures, 'api', 'window-open-location-final.html')] ]; beforeEach(() => { for (const [scheme, path] of protocols) { protocol.registerBufferProtocol(scheme, (request, callback) => { callback({ mimeType: 'text/html', data: fs.readFileSync(path) }); }); } }); afterEach(() => { for (const [scheme] of protocols) { protocol.unregisterProtocol(scheme); } }); it('retains the original web preferences when window.location is changed to a new origin', async () => { const w = new BrowserWindow({ show: false, webPreferences: { // test relies on preloads in opened window nodeIntegrationInSubFrames: true, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: path.join(mainFixtures, 'api', 'window-open-preload.js'), contextIsolation: false, nodeIntegrationInSubFrames: true } } })); w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html')); const [, { nodeIntegration, typeofProcess }] = await emittedOnce(ipcMain, 'answer'); expect(nodeIntegration).to.be.false(); expect(typeofProcess).to.eql('undefined'); }); it('window.opener is not null when window.location is changed to a new origin', async () => { const w = new BrowserWindow({ show: false, webPreferences: { // test relies on preloads in opened window nodeIntegrationInSubFrames: true } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: path.join(mainFixtures, 'api', 'window-open-preload.js') } } })); w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html')); const [, { windowOpenerIsNull }] = await emittedOnce(ipcMain, 'answer'); expect(windowOpenerIsNull).to.be.false('window.opener is null'); }); }); }); describe('"disableHtmlFullscreenWindowResize" option', () => { it('prevents window from resizing when set', async () => { const w = new BrowserWindow({ show: false, webPreferences: { disableHtmlFullscreenWindowResize: true } }); await w.loadURL('about:blank'); const size = w.getSize(); const enterHtmlFullScreen = emittedOnce(w.webContents, 'enter-html-full-screen'); w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true); await enterHtmlFullScreen; expect(w.getSize()).to.deep.equal(size); }); }); }); describe('beforeunload handler', function () { let w: BrowserWindow = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(closeAllWindows); it('returning undefined would not prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html')); const wait = emittedOnce(w, 'closed'); w.close(); await wait; }); it('returning false would prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); const [, proceed] = await emittedOnce(w.webContents, 'before-unload-fired'); expect(proceed).to.equal(false); }); it('returning empty string would prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-empty-string.html')); w.close(); const [, proceed] = await emittedOnce(w.webContents, 'before-unload-fired'); expect(proceed).to.equal(false); }); it('emits for each close attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const destroyListener = () => { expect.fail('Close was not prevented'); }; w.webContents.once('destroyed', destroyListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await emittedOnce(w.webContents, 'console-message'); w.close(); await emittedOnce(w.webContents, 'before-unload-fired'); w.close(); await emittedOnce(w.webContents, 'before-unload-fired'); w.webContents.removeListener('destroyed', destroyListener); const wait = emittedOnce(w, 'closed'); w.close(); await wait; }); it('emits for each reload attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const navigationListener = () => { expect.fail('Reload was not prevented'); }; w.webContents.once('did-start-navigation', navigationListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await emittedOnce(w.webContents, 'console-message'); w.reload(); // Chromium does not emit 'before-unload-fired' on WebContents for // navigations, so we have to use other ways to know if beforeunload // is fired. await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.reload(); await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.webContents.removeListener('did-start-navigation', navigationListener); w.reload(); await emittedOnce(w.webContents, 'did-finish-load'); }); it('emits for each navigation attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const navigationListener = () => { expect.fail('Reload was not prevented'); }; w.webContents.once('did-start-navigation', navigationListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await emittedOnce(w.webContents, 'console-message'); w.loadURL('about:blank'); // Chromium does not emit 'before-unload-fired' on WebContents for // navigations, so we have to use other ways to know if beforeunload // is fired. await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.loadURL('about:blank'); await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.webContents.removeListener('did-start-navigation', navigationListener); await w.loadURL('about:blank'); }); }); describe('document.visibilityState/hidden', () => { afterEach(closeAllWindows); it('visibilityState is initially visible despite window being hidden', async () => { const w = new BrowserWindow({ show: false, width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); let readyToShow = false; w.once('ready-to-show', () => { readyToShow = true; }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(readyToShow).to.be.false('ready to show'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform !== 'win32')('visibilityState changes when window is hidden', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.hide(); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform !== 'win32')('visibilityState changes when window is shown', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); if (process.platform === 'darwin') { // See https://github.com/electron/electron/issues/8664 await emittedOnce(w, 'show'); } w.hide(); w.show(); const [, visibilityState] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); }); ifit(process.platform !== 'win32')('visibilityState changes when window is shown inactive', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); if (process.platform === 'darwin') { // See https://github.com/electron/electron/issues/8664 await emittedOnce(w, 'show'); } w.hide(); w.showInactive(); const [, visibilityState] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform === 'darwin')('visibilityState changes when window is minimized', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.minimize(); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } }); // FIXME(MarshallOfSound): This test fails locally 100% of the time, on CI it started failing // when we introduced the compositor recycling patch. Should figure out how to fix this it.skip('visibilityState remains visible if backgroundThrottling is disabled', async () => { const w = new BrowserWindow({ show: false, width: 100, height: 100, webPreferences: { backgroundThrottling: false, nodeIntegration: true } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } ipcMain.once('pong', (event, visibilityState, hidden) => { throw new Error(`Unexpected visibility change event. visibilityState: ${visibilityState} hidden: ${hidden}`); }); try { const shown1 = emittedOnce(w, 'show'); w.show(); await shown1; const hidden = emittedOnce(w, 'hide'); w.hide(); await hidden; const shown2 = emittedOnce(w, 'show'); w.show(); await shown2; } finally { ipcMain.removeAllListeners('pong'); } }); }); describe('new-window event', () => { afterEach(closeAllWindows); it('emits when window.open is called', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); w.webContents.once('new-window', (e, url, frameName, disposition, options) => { e.preventDefault(); try { expect(url).to.equal('http://host/'); expect(frameName).to.equal('host'); expect((options as any)['this-is-not-a-standard-feature']).to.equal(true); done(); } catch (e) { done(e); } }); w.loadFile(path.join(fixtures, 'pages', 'window-open.html')); }); it('emits when window.open is called with no webPreferences', (done) => { const w = new BrowserWindow({ show: false }); w.webContents.once('new-window', function (e, url, frameName, disposition, options) { e.preventDefault(); try { expect(url).to.equal('http://host/'); expect(frameName).to.equal('host'); expect((options as any)['this-is-not-a-standard-feature']).to.equal(true); done(); } catch (e) { done(e); } }); w.loadFile(path.join(fixtures, 'pages', 'window-open.html')); }); it('emits when link with target is called', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); w.webContents.once('new-window', (e, url, frameName) => { e.preventDefault(); try { expect(url).to.equal('http://host/'); expect(frameName).to.equal('target'); done(); } catch (e) { done(e); } }); w.loadFile(path.join(fixtures, 'pages', 'target-name.html')); }); it('includes all properties', async () => { const w = new BrowserWindow({ show: false }); const p = new Promise<{ url: string, frameName: string, disposition: string, options: BrowserWindowConstructorOptions, additionalFeatures: string[], referrer: Electron.Referrer, postBody: Electron.PostBody }>((resolve) => { w.webContents.once('new-window', (e, url, frameName, disposition, options, additionalFeatures, referrer, postBody) => { e.preventDefault(); resolve({ url, frameName, disposition, options, additionalFeatures, referrer, postBody }); }); }); w.loadURL(`data:text/html,${encodeURIComponent(` <form target="_blank" method="POST" id="form" action="http://example.com/test"> <input type="text" name="post-test-key" value="post-test-value"></input> </form> <script>form.submit()</script> `)}`); const { url, frameName, disposition, options, additionalFeatures, referrer, postBody } = await p; expect(url).to.equal('http://example.com/test'); expect(frameName).to.equal(''); expect(disposition).to.equal('foreground-tab'); expect(options).to.be.an('object').not.null(); expect(referrer.policy).to.equal('strict-origin-when-cross-origin'); expect(referrer.url).to.equal(''); expect(additionalFeatures).to.deep.equal([]); expect(postBody.data).to.have.length(1); expect(postBody.data[0].type).to.equal('rawData'); expect((postBody.data[0] as any).bytes).to.deep.equal(Buffer.from('post-test-key=post-test-value')); expect(postBody.contentType).to.equal('application/x-www-form-urlencoded'); }); }); ifdescribe(process.platform !== 'linux')('max/minimize events', () => { afterEach(closeAllWindows); it('emits an event when window is maximized', async () => { const w = new BrowserWindow({ show: false }); const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; }); it('emits an event when a transparent window is maximized', async () => { const w = new BrowserWindow({ show: false, frame: false, transparent: true }); const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; }); it('emits only one event when frameless window is maximized', () => { const w = new BrowserWindow({ show: false, frame: false }); let emitted = 0; w.on('maximize', () => emitted++); w.show(); w.maximize(); expect(emitted).to.equal(1); }); it('emits an event when window is unmaximized', async () => { const w = new BrowserWindow({ show: false }); const unmaximize = emittedOnce(w, 'unmaximize'); w.show(); w.maximize(); w.unmaximize(); await unmaximize; }); it('emits an event when a transparent window is unmaximized', async () => { const w = new BrowserWindow({ show: false, frame: false, transparent: true }); const maximize = emittedOnce(w, 'maximize'); const unmaximize = emittedOnce(w, 'unmaximize'); w.show(); w.maximize(); await maximize; w.unmaximize(); await unmaximize; }); it('emits an event when window is minimized', async () => { const w = new BrowserWindow({ show: false }); const minimize = emittedOnce(w, 'minimize'); w.show(); w.minimize(); await minimize; }); }); describe('beginFrameSubscription method', () => { it('does not crash when callback returns nothing', (done) => { const w = new BrowserWindow({ show: false }); 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(() => { w.webContents.endFrameSubscription(); done(); }); }); }); }); it('subscribes to frame updates', (done) => { const w = new BrowserWindow({ show: false }); let called = false; w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); w.webContents.on('dom-ready', () => { w.webContents.beginFrameSubscription(function (data) { // This callback might be called twice. if (called) return; called = true; try { expect(data.constructor.name).to.equal('NativeImage'); expect(data.isEmpty()).to.be.false('data is empty'); done(); } catch (e) { done(e); } finally { w.webContents.endFrameSubscription(); } }); }); }); it('subscribes to frame updates (only dirty rectangle)', (done) => { const w = new BrowserWindow({ show: false }); let called = false; let gotInitialFullSizeFrame = false; const [contentWidth, contentHeight] = w.getContentSize(); w.webContents.on('did-finish-load', () => { w.webContents.beginFrameSubscription(true, (image, rect) => { if (image.isEmpty()) { // Chromium sometimes sends a 0x0 frame at the beginning of the // page load. return; } if (rect.height === contentHeight && rect.width === contentWidth && !gotInitialFullSizeFrame) { // The initial frame is full-size, but we're looking for a call // with just the dirty-rect. The next frame should be a smaller // rect. gotInitialFullSizeFrame = true; return; } // This callback might be called twice. if (called) return; // We asked for just the dirty rectangle, so we expect to receive a // rect smaller than the full size. // TODO(jeremy): this is failing on windows currently; investigate. // assert(rect.width < contentWidth || rect.height < contentHeight) called = true; try { const expectedSize = rect.width * rect.height * 4; expect(image.getBitmap()).to.be.an.instanceOf(Buffer).with.lengthOf(expectedSize); done(); } catch (e) { done(e); } finally { w.webContents.endFrameSubscription(); } }); }); w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); }); it('throws error when subscriber is not well defined', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.webContents.beginFrameSubscription(true, true as any); // TODO(zcbenz): gin is weak at guessing parameter types, we should // upstream native_mate's implementation to gin. }).to.throw('Error processing argument at index 1, conversion failure from '); }); }); describe('savePage method', () => { const savePageDir = path.join(fixtures, 'save_page'); const savePageHtmlPath = path.join(savePageDir, 'save_page.html'); const savePageJsPath = path.join(savePageDir, 'save_page_files', 'test.js'); const savePageCssPath = path.join(savePageDir, 'save_page_files', 'test.css'); afterEach(() => { closeAllWindows(); try { fs.unlinkSync(savePageCssPath); fs.unlinkSync(savePageJsPath); fs.unlinkSync(savePageHtmlPath); fs.rmdirSync(path.join(savePageDir, 'save_page_files')); fs.rmdirSync(savePageDir); } catch {} }); it('should throw when passing relative paths', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await expect( w.webContents.savePage('save_page.html', 'HTMLComplete') ).to.eventually.be.rejectedWith('Path must be absolute'); await expect( w.webContents.savePage('save_page.html', 'HTMLOnly') ).to.eventually.be.rejectedWith('Path must be absolute'); await expect( w.webContents.savePage('save_page.html', 'MHTML') ).to.eventually.be.rejectedWith('Path must be absolute'); }); it('should save page to disk with HTMLOnly', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'HTMLOnly'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.false('js path'); expect(fs.existsSync(savePageCssPath)).to.be.false('css path'); }); it('should save page to disk with MHTML', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'MHTML'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.false('js path'); expect(fs.existsSync(savePageCssPath)).to.be.false('css path'); }); it('should save page to disk with HTMLComplete', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'HTMLComplete'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.true('js path'); expect(fs.existsSync(savePageCssPath)).to.be.true('css path'); }); }); describe('BrowserWindow options argument is optional', () => { afterEach(closeAllWindows); it('should create a window with default size (800x600)', () => { const w = new BrowserWindow(); expect(w.getSize()).to.deep.equal([800, 600]); }); }); describe('BrowserWindow.restore()', () => { afterEach(closeAllWindows); it('should restore the previous window size', () => { const w = new BrowserWindow({ minWidth: 800, width: 800 }); const initialSize = w.getSize(); w.minimize(); w.restore(); expectBoundsEqual(w.getSize(), initialSize); }); it('does not crash when restoring hidden minimized window', () => { const w = new BrowserWindow({}); w.minimize(); w.hide(); w.show(); }); }); // 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 = emittedOnce(w, 'hide'); let shown = emittedOnce(w, 'show'); const maximize = emittedOnce(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 = emittedOnce(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 = emittedOnce(w, 'minimize'); w.minimize(); await minimize; w.unmaximize(); await delay(1000); expect(w.isMinimized()).to.be.true(); }); it('should not change the size or position of a normal window', async () => { const w = new BrowserWindow(); const initialSize = w.getSize(); const initialPosition = w.getPosition(); w.unmaximize(); await delay(1000); expectBoundsEqual(w.getSize(), initialSize); expectBoundsEqual(w.getPosition(), initialPosition); }); 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 delay(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 = emittedOnce(w, 'show'); // start fullscreen and hidden w.setFullScreen(true); w.show(); await shown; const leftFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leftFullScreen; expect(w.isVisible()).to.be.true('visible'); expect(w.isFullScreen()).to.be.false('fullscreen'); }); it('should keep window hidden if already in hidden state', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const leftFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leftFullScreen; expect(w.isVisible()).to.be.false('visible'); expect(w.isFullScreen()).to.be.false('fullscreen'); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setFullScreen(false) when HTML fullscreen', () => { it('exits HTML fullscreen when window leaves fullscreen', async () => { const w = new BrowserWindow(); await w.loadURL('about:blank'); await w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true); await emittedOnce(w, 'enter-full-screen'); // Wait a tick for the full-screen state to 'stick' await delay(); w.setFullScreen(false); await emittedOnce(w, 'leave-html-full-screen'); }); }); }); describe('parent window', () => { afterEach(closeAllWindows); ifit(process.platform === 'darwin')('sheet-begin event emits when window opens a sheet', async () => { const w = new BrowserWindow(); const sheetBegin = emittedOnce(w, 'sheet-begin'); // eslint-disable-next-line no-new new BrowserWindow({ modal: true, parent: w }); await sheetBegin; }); ifit(process.platform === 'darwin')('sheet-end event emits when window has closed a sheet', async () => { const w = new BrowserWindow(); const sheet = new BrowserWindow({ modal: true, parent: w }); const sheetEnd = emittedOnce(w, 'sheet-end'); sheet.close(); await sheetEnd; }); describe('parent option', () => { it('sets parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(c.getParentWindow()).to.equal(w); }); it('adds window to child windows of parent', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(w.getChildWindows()).to.deep.equal([c]); }); it('removes from child windows of parent when window is closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); const closed = emittedOnce(c, 'closed'); c.close(); await closed; // The child window list is not immediately cleared, so wait a tick until it's ready. await delay(); expect(w.getChildWindows().length).to.equal(0); }); it('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 delay(); 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 = emittedOnce(c, 'closed'); c.setParentWindow(w); c.close(); await closed; // The child window list is not immediately cleared, so wait a tick until it's ready. await delay(); expect(w.getChildWindows().length).to.equal(0); }); }); describe('modal option', () => { it('does not freeze or crash', async () => { const parentWindow = new BrowserWindow(); const createTwo = async () => { const two = new BrowserWindow({ width: 300, height: 200, parent: parentWindow, modal: true, show: false }); const twoShown = emittedOnce(two, 'show'); two.show(); await twoShown; setTimeout(() => two.close(), 500); await emittedOnce(two, 'closed'); }; const one = new BrowserWindow({ width: 600, height: 400, parent: parentWindow, modal: true, show: false }); const oneShown = emittedOnce(one, 'show'); one.show(); await oneShown; setTimeout(() => one.destroy(), 500); await emittedOnce(one, 'closed'); await createTwo(); }); ifit(process.platform !== 'darwin')('disables parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); expect(w.isEnabled()).to.be.true('w.isEnabled'); c.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); }); ifit(process.platform !== 'darwin')('re-enables an enabled parent window when closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const closed = emittedOnce(c, 'closed'); c.show(); c.close(); await closed; expect(w.isEnabled()).to.be.true('w.isEnabled'); }); ifit(process.platform !== 'darwin')('does not re-enable a disabled parent window when closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const closed = emittedOnce(c, 'closed'); w.setEnabled(false); c.show(); c.close(); await closed; expect(w.isEnabled()).to.be.false('w.isEnabled'); }); ifit(process.platform !== 'darwin')('disables parent window recursively', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const c2 = new BrowserWindow({ show: false, parent: w, modal: true }); c.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c2.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c.destroy(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c2.destroy(); expect(w.isEnabled()).to.be.true('w.isEnabled'); }); }); }); describe('window states', () => { afterEach(closeAllWindows); it('does not resize frameless windows when states change', () => { const w = new BrowserWindow({ frame: false, width: 300, height: 200, show: false }); w.minimizable = false; w.minimizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.resizable = false; w.resizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.maximizable = false; w.maximizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.fullScreenable = false; w.fullScreenable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.closable = false; w.closable = true; expect(w.getSize()).to.deep.equal([300, 200]); }); describe('resizable state', () => { it('with properties', () => { it('can be set with resizable constructor option', () => { const w = new BrowserWindow({ show: false, resizable: false }); expect(w.resizable).to.be.false('resizable'); if (process.platform === 'darwin') { expect(w.maximizable).to.to.true('maximizable'); } }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.resizable).to.be.true('resizable'); w.resizable = false; expect(w.resizable).to.be.false('resizable'); w.resizable = true; expect(w.resizable).to.be.true('resizable'); }); }); it('with functions', () => { it('can be set with resizable constructor option', () => { const w = new BrowserWindow({ show: false, resizable: false }); expect(w.isResizable()).to.be.false('resizable'); if (process.platform === 'darwin') { expect(w.isMaximizable()).to.to.true('maximizable'); } }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isResizable()).to.be.true('resizable'); w.setResizable(false); expect(w.isResizable()).to.be.false('resizable'); w.setResizable(true); expect(w.isResizable()).to.be.true('resizable'); }); }); it('works for a frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); expect(w.resizable).to.be.true('resizable'); if (process.platform === 'win32') { const w = new BrowserWindow({ show: false, thickFrame: false }); expect(w.resizable).to.be.false('resizable'); } }); // On Linux there is no "resizable" property of a window. ifit(process.platform !== 'linux')('does affect maximizability when disabled and enabled', () => { const w = new BrowserWindow({ show: false }); expect(w.resizable).to.be.true('resizable'); expect(w.maximizable).to.be.true('maximizable'); w.resizable = false; expect(w.maximizable).to.be.false('not maximizable'); w.resizable = true; expect(w.maximizable).to.be.true('maximizable'); }); ifit(process.platform === 'win32')('works for a window smaller than 64x64', () => { const w = new BrowserWindow({ show: false, frame: false, resizable: false, transparent: true }); w.setContentSize(60, 60); expectBoundsEqual(w.getContentSize(), [60, 60]); w.setContentSize(30, 30); expectBoundsEqual(w.getContentSize(), [30, 30]); w.setContentSize(10, 10); expectBoundsEqual(w.getContentSize(), [10, 10]); }); }); describe('loading main frame state', () => { let server: http.Server = null as unknown as http.Server; let serverUrl: string = null as unknown as string; before((done) => { server = http.createServer((request, response) => { response.end(); }).listen(0, '127.0.0.1', () => { serverUrl = 'http://127.0.0.1:' + (server.address() as AddressInfo).port; done(); }); }); after(() => { server.close(); }); it('is true when the main frame is loading', async () => { const w = new BrowserWindow({ show: false }); const didStartLoading = emittedOnce(w.webContents, 'did-start-loading'); w.webContents.loadURL(serverUrl); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame'); }); it('is false when only a subframe is loading', async () => { const w = new BrowserWindow({ show: false }); const didStopLoading = emittedOnce(w.webContents, 'did-stop-loading'); w.webContents.loadURL(serverUrl); await didStopLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); const didStartLoading = emittedOnce(w.webContents, 'did-start-loading'); w.webContents.executeJavaScript(` var iframe = document.createElement('iframe') iframe.src = '${serverUrl}/page2' document.body.appendChild(iframe) `); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); }); it('is true when navigating to pages from the same origin', async () => { const w = new BrowserWindow({ show: false }); const didStopLoading = emittedOnce(w.webContents, 'did-stop-loading'); w.webContents.loadURL(serverUrl); await didStopLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); const didStartLoading = emittedOnce(w.webContents, 'did-start-loading'); w.webContents.loadURL(`${serverUrl}/page2`); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame'); }); }); }); ifdescribe(process.platform !== 'linux')('window states (excluding Linux)', () => { // Not implemented on Linux. afterEach(closeAllWindows); describe('movable state', () => { it('with properties', () => { it('can be set with movable constructor option', () => { const w = new BrowserWindow({ show: false, movable: false }); expect(w.movable).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.movable).to.be.true('movable'); w.movable = false; expect(w.movable).to.be.false('movable'); w.movable = true; expect(w.movable).to.be.true('movable'); }); }); it('with functions', () => { it('can be set with movable constructor option', () => { const w = new BrowserWindow({ show: false, movable: false }); expect(w.isMovable()).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMovable()).to.be.true('movable'); w.setMovable(false); expect(w.isMovable()).to.be.false('movable'); w.setMovable(true); expect(w.isMovable()).to.be.true('movable'); }); }); }); describe('visibleOnAllWorkspaces state', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.visibleOnAllWorkspaces).to.be.false(); w.visibleOnAllWorkspaces = true; expect(w.visibleOnAllWorkspaces).to.be.true(); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isVisibleOnAllWorkspaces()).to.be.false(); w.setVisibleOnAllWorkspaces(true); expect(w.isVisibleOnAllWorkspaces()).to.be.true(); }); }); }); ifdescribe(process.platform === 'darwin')('documentEdited state', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.documentEdited).to.be.false(); w.documentEdited = true; expect(w.documentEdited).to.be.true(); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isDocumentEdited()).to.be.false(); w.setDocumentEdited(true); expect(w.isDocumentEdited()).to.be.true(); }); }); }); ifdescribe(process.platform === 'darwin')('representedFilename', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.representedFilename).to.eql(''); w.representedFilename = 'a name'; expect(w.representedFilename).to.eql('a name'); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.getRepresentedFilename()).to.eql(''); w.setRepresentedFilename('a name'); expect(w.getRepresentedFilename()).to.eql('a name'); }); }); }); describe('native window title', () => { it('with properties', () => { it('can be set with title constructor option', () => { const w = new BrowserWindow({ show: false, title: 'mYtItLe' }); expect(w.title).to.eql('mYtItLe'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.title).to.eql('Electron Test Main'); w.title = 'NEW TITLE'; expect(w.title).to.eql('NEW TITLE'); }); }); it('with functions', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, title: 'mYtItLe' }); expect(w.getTitle()).to.eql('mYtItLe'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.getTitle()).to.eql('Electron Test Main'); w.setTitle('NEW TITLE'); expect(w.getTitle()).to.eql('NEW TITLE'); }); }); }); describe('minimizable state', () => { it('with properties', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, minimizable: false }); expect(w.minimizable).to.be.false('minimizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.minimizable).to.be.true('minimizable'); w.minimizable = false; expect(w.minimizable).to.be.false('minimizable'); w.minimizable = true; expect(w.minimizable).to.be.true('minimizable'); }); }); it('with functions', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, minimizable: false }); expect(w.isMinimizable()).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMinimizable()).to.be.true('isMinimizable'); w.setMinimizable(false); expect(w.isMinimizable()).to.be.false('isMinimizable'); w.setMinimizable(true); expect(w.isMinimizable()).to.be.true('isMinimizable'); }); }); }); describe('maximizable state (property)', () => { it('with properties', () => { it('can be set with maximizable constructor option', () => { const w = new BrowserWindow({ show: false, maximizable: false }); expect(w.maximizable).to.be.false('maximizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.maximizable).to.be.true('maximizable'); w.maximizable = false; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; expect(w.maximizable).to.be.true('maximizable'); }); it('is not affected when changing other states', () => { const w = new BrowserWindow({ show: false }); w.maximizable = false; expect(w.maximizable).to.be.false('maximizable'); w.minimizable = false; expect(w.maximizable).to.be.false('maximizable'); w.closable = false; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; expect(w.maximizable).to.be.true('maximizable'); w.closable = true; expect(w.maximizable).to.be.true('maximizable'); w.fullScreenable = false; expect(w.maximizable).to.be.true('maximizable'); }); }); it('with functions', () => { it('can be set with maximizable constructor option', () => { const w = new BrowserWindow({ show: false, maximizable: false }); expect(w.isMaximizable()).to.be.false('isMaximizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setMaximizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); it('is not affected when changing other states', () => { const w = new BrowserWindow({ show: false }); w.setMaximizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMinimizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setClosable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setClosable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setFullScreenable(false); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); }); }); ifdescribe(process.platform === 'win32')('maximizable state', () => { it('with properties', () => { it('is reset to its former state', () => { const w = new BrowserWindow({ show: false }); w.maximizable = false; w.resizable = false; w.resizable = true; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; w.resizable = false; w.resizable = true; expect(w.maximizable).to.be.true('maximizable'); }); }); it('with functions', () => { it('is reset to its former state', () => { const w = new BrowserWindow({ show: false }); w.setMaximizable(false); w.setResizable(false); w.setResizable(true); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); w.setResizable(false); w.setResizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); }); }); ifdescribe(process.platform !== 'darwin')('menuBarVisible state', () => { describe('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.menuBarVisible).to.be.true(); w.menuBarVisible = false; expect(w.menuBarVisible).to.be.false(); w.menuBarVisible = true; expect(w.menuBarVisible).to.be.true(); }); }); describe('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); w.setMenuBarVisibility(false); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); w.setMenuBarVisibility(true); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); }); }); }); ifdescribe(process.platform === 'darwin')('fullscreenable state', () => { it('with functions', () => { it('can be set with fullscreenable constructor option', () => { const w = new BrowserWindow({ show: false, fullscreenable: false }); expect(w.isFullScreenable()).to.be.false('isFullScreenable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isFullScreenable()).to.be.true('isFullScreenable'); w.setFullScreenable(false); expect(w.isFullScreenable()).to.be.false('isFullScreenable'); w.setFullScreenable(true); expect(w.isFullScreenable()).to.be.true('isFullScreenable'); }); }); }); // fullscreen events are dispatched eagerly and twiddling things too fast can confuse poor Electron ifdescribe(process.platform === 'darwin')('kiosk state', () => { it('with properties', () => { it('can be set with a constructor property', () => { const w = new BrowserWindow({ kiosk: true }); expect(w.kiosk).to.be.true(); }); it('can be changed ', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.kiosk = true; expect(w.isKiosk()).to.be.true('isKiosk'); await enterFullScreen; await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.kiosk = false; expect(w.isKiosk()).to.be.false('isKiosk'); await leaveFullScreen; }); }); it('with functions', () => { it('can be set with a constructor property', () => { const w = new BrowserWindow({ kiosk: true }); expect(w.isKiosk()).to.be.true(); }); it('can be changed ', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setKiosk(true); expect(w.isKiosk()).to.be.true('isKiosk'); await enterFullScreen; await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setKiosk(false); expect(w.isKiosk()).to.be.false('isKiosk'); await leaveFullScreen; }); }); }); ifdescribe(process.platform === 'darwin')('fullscreen state with resizable set', () => { it('resizable flag should be set to true and restored', async () => { const w = new BrowserWindow({ resizable: false }); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.resizable).to.be.true('resizable'); await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.resizable).to.be.false('resizable'); }); }); ifdescribe(process.platform === 'darwin')('fullscreen state', () => { it('should not cause a crash if called when exiting fullscreen', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; }); it('can be changed with setFullScreen method', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('isFullScreen'); }); it('handles several transitions starting with fullscreen', async () => { const w = new BrowserWindow({ fullscreen: true, show: true }); expect(w.isFullScreen()).to.be.true('not fullscreen'); w.setFullScreen(false); w.setFullScreen(true); const enterFullScreen = emittedNTimes(w, 'enter-full-screen', 2); await enterFullScreen; expect(w.isFullScreen()).to.be.true('not fullscreen'); await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); }); it('handles several transitions in close proximity', async () => { const w = new BrowserWindow(); expect(w.isFullScreen()).to.be.false('is fullscreen'); w.setFullScreen(true); w.setFullScreen(false); w.setFullScreen(true); const enterFullScreen = emittedNTimes(w, 'enter-full-screen', 2); await enterFullScreen; expect(w.isFullScreen()).to.be.true('not fullscreen'); }); it('does not crash when exiting simpleFullScreen (properties)', async () => { const w = new BrowserWindow(); w.setSimpleFullScreen(true); await delay(1000); w.setFullScreen(!w.isFullScreen()); }); it('does not crash when exiting simpleFullScreen (functions)', async () => { const w = new BrowserWindow(); w.simpleFullScreen = true; await delay(1000); w.setFullScreen(!w.isFullScreen()); }); it('should not be changed by setKiosk method', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await delay(); w.setKiosk(true); await delay(); w.setKiosk(false); expect(w.isFullScreen()).to.be.true('isFullScreen'); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('isFullScreen'); }); // FIXME: https://github.com/electron/electron/issues/30140 xit('multiple windows inherit correct fullscreen state', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await delay(); const w2 = new BrowserWindow({ show: false }); const enterFullScreen2 = emittedOnce(w2, 'enter-full-screen'); w2.show(); await enterFullScreen2; expect(w2.isFullScreen()).to.be.true('isFullScreen'); }); }); describe('closable state', () => { it('with properties', () => { it('can be set with closable constructor option', () => { const w = new BrowserWindow({ show: false, closable: false }); expect(w.closable).to.be.false('closable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.closable).to.be.true('closable'); w.closable = false; expect(w.closable).to.be.false('closable'); w.closable = true; expect(w.closable).to.be.true('closable'); }); }); it('with functions', () => { it('can be set with closable constructor option', () => { const w = new BrowserWindow({ show: false, closable: false }); expect(w.isClosable()).to.be.false('isClosable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isClosable()).to.be.true('isClosable'); w.setClosable(false); expect(w.isClosable()).to.be.false('isClosable'); w.setClosable(true); expect(w.isClosable()).to.be.true('isClosable'); }); }); }); describe('hasShadow state', () => { it('with properties', () => { it('returns a boolean on all platforms', () => { const w = new BrowserWindow({ show: false }); expect(w.shadow).to.be.a('boolean'); }); // On Windows there's no shadow by default & it can't be changed dynamically. it('can be changed with hasShadow option', () => { const hasShadow = process.platform !== 'darwin'; const w = new BrowserWindow({ show: false, hasShadow }); expect(w.shadow).to.equal(hasShadow); }); it('can be changed with setHasShadow method', () => { const w = new BrowserWindow({ show: false }); w.shadow = false; expect(w.shadow).to.be.false('hasShadow'); w.shadow = true; expect(w.shadow).to.be.true('hasShadow'); w.shadow = false; expect(w.shadow).to.be.false('hasShadow'); }); }); describe('with functions', () => { it('returns a boolean on all platforms', () => { const w = new BrowserWindow({ show: false }); const hasShadow = w.hasShadow(); expect(hasShadow).to.be.a('boolean'); }); // On Windows there's no shadow by default & it can't be changed dynamically. it('can be changed with hasShadow option', () => { const hasShadow = process.platform !== 'darwin'; const w = new BrowserWindow({ show: false, hasShadow }); expect(w.hasShadow()).to.equal(hasShadow); }); it('can be changed with setHasShadow method', () => { const w = new BrowserWindow({ show: false }); w.setHasShadow(false); expect(w.hasShadow()).to.be.false('hasShadow'); w.setHasShadow(true); expect(w.hasShadow()).to.be.true('hasShadow'); w.setHasShadow(false); expect(w.hasShadow()).to.be.false('hasShadow'); }); }); }); }); describe('window.getMediaSourceId()', () => { afterEach(closeAllWindows); it('returns valid source id', async () => { const w = new BrowserWindow({ show: false }); const shown = emittedOnce(w, 'show'); w.show(); await shown; // Check format 'window:1234:0'. const sourceId = w.getMediaSourceId(); expect(sourceId).to.match(/^window:\d+:\d+$/); }); }); ifdescribe(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('window.getNativeWindowHandle()', () => { afterEach(closeAllWindows); it('returns valid handle', () => { const w = new BrowserWindow({ show: false }); // The module's source code is hosted at // https://github.com/electron/node-is-valid-window const isValidWindow = require('is-valid-window'); expect(isValidWindow(w.getNativeWindowHandle())).to.be.true('is valid window'); }); }); ifdescribe(process.platform === 'darwin')('previewFile', () => { afterEach(closeAllWindows); it('opens the path in Quick Look on macOS', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.previewFile(__filename); w.closeFilePreview(); }).to.not.throw(); }); }); describe('contextIsolation option with and without sandbox option', () => { const expectedContextData = { preloadContext: { preloadProperty: 'number', pageProperty: 'undefined', typeofRequire: 'function', typeofProcess: 'object', typeofArrayPush: 'function', typeofFunctionApply: 'function', typeofPreloadExecuteJavaScriptProperty: 'undefined' }, pageContext: { preloadProperty: 'undefined', pageProperty: 'string', typeofRequire: 'undefined', typeofProcess: 'undefined', typeofArrayPush: 'number', typeofFunctionApply: 'boolean', typeofPreloadExecuteJavaScriptProperty: 'number', typeofOpenedWindow: 'object' } }; afterEach(closeAllWindows); it('separates the page context from the Electron/preload context', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = emittedOnce(ipcMain, 'isolated-world'); iw.loadFile(path.join(fixtures, 'api', 'isolated.html')); const [, data] = await p; expect(data).to.deep.equal(expectedContextData); }); it('recreates the contexts on reload', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); await iw.loadFile(path.join(fixtures, 'api', 'isolated.html')); const isolatedWorld = emittedOnce(ipcMain, 'isolated-world'); iw.webContents.reload(); const [, data] = await isolatedWorld; expect(data).to.deep.equal(expectedContextData); }); it('enables context isolation on child windows', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const browserWindowCreated = emittedOnce(app, 'browser-window-created'); iw.loadFile(path.join(fixtures, 'pages', 'window-open.html')); const [, window] = await browserWindowCreated; expect(window.webContents.getLastWebPreferences().contextIsolation).to.be.true('contextIsolation'); }); it('separates the page context from the Electron/preload context with sandbox on', async () => { const ws = new BrowserWindow({ show: false, webPreferences: { sandbox: true, contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = emittedOnce(ipcMain, 'isolated-world'); ws.loadFile(path.join(fixtures, 'api', 'isolated.html')); const [, data] = await p; expect(data).to.deep.equal(expectedContextData); }); it('recreates the contexts on reload with sandbox on', async () => { const ws = new BrowserWindow({ show: false, webPreferences: { sandbox: true, contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); await ws.loadFile(path.join(fixtures, 'api', 'isolated.html')); const isolatedWorld = emittedOnce(ipcMain, 'isolated-world'); ws.webContents.reload(); const [, data] = await isolatedWorld; expect(data).to.deep.equal(expectedContextData); }); it('supports fetch api', async () => { const fetchWindow = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-fetch-preload.js') } }); const p = emittedOnce(ipcMain, 'isolated-fetch-error'); fetchWindow.loadURL('about:blank'); const [, error] = await p; expect(error).to.equal('Failed to fetch'); }); it('doesn\'t break ipc serialization', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = emittedOnce(ipcMain, 'isolated-world'); iw.loadURL('about:blank'); iw.webContents.executeJavaScript(` const opened = window.open() openedLocation = opened.location.href opened.close() window.postMessage({openedLocation}, '*') `); const [, data] = await p; expect(data.pageContext.openedLocation).to.equal('about:blank'); }); it('reports process.contextIsolated', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-process.js') } }); const p = emittedOnce(ipcMain, 'context-isolation'); iw.loadURL('about:blank'); const [, contextIsolation] = await p; expect(contextIsolation).to.be.true('contextIsolation'); }); }); it('reloading does not cause Node.js module API hangs after reload', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); let count = 0; ipcMain.on('async-node-api-done', () => { if (count === 3) { ipcMain.removeAllListeners('async-node-api-done'); done(); } else { count++; w.reload(); } }); w.loadFile(path.join(fixtures, 'pages', 'send-after-node.html')); }); describe('window.webContents.focus()', () => { afterEach(closeAllWindows); it('focuses window', async () => { const w1 = new BrowserWindow({ x: 100, y: 300, width: 300, height: 200 }); w1.loadURL('about:blank'); const w2 = new BrowserWindow({ x: 300, y: 300, width: 300, height: 200 }); w2.loadURL('about:blank'); const w1Focused = emittedOnce(w1, 'focus'); w1.webContents.focus(); await w1Focused; expect(w1.webContents.isFocused()).to.be.true('focuses window'); }); }); ifdescribe(features.isOffscreenRenderingEnabled())('offscreen rendering', () => { let w: BrowserWindow; beforeEach(function () { w = new BrowserWindow({ width: 100, height: 100, show: false, webPreferences: { backgroundThrottling: false, offscreen: true } }); }); afterEach(closeAllWindows); it('creates offscreen window with correct size', async () => { const paint = emittedOnce(w.webContents, 'paint'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); const [,, data] = await paint; expect(data.constructor.name).to.equal('NativeImage'); expect(data.isEmpty()).to.be.false('data is empty'); const size = data.getSize(); const { scaleFactor } = screen.getPrimaryDisplay(); expect(size.width).to.be.closeTo(100 * scaleFactor, 2); expect(size.height).to.be.closeTo(100 * scaleFactor, 2); }); it('does not crash after navigation', () => { w.webContents.loadURL('about:blank'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); }); describe('window.webContents.isOffscreen()', () => { it('is true for offscreen type', () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); expect(w.webContents.isOffscreen()).to.be.true('isOffscreen'); }); it('is false for regular window', () => { const c = new BrowserWindow({ show: false }); expect(c.webContents.isOffscreen()).to.be.false('isOffscreen'); c.destroy(); }); }); describe('window.webContents.isPainting()', () => { it('returns whether is currently painting', async () => { const paint = emittedOnce(w.webContents, 'paint'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await paint; expect(w.webContents.isPainting()).to.be.true('isPainting'); }); }); describe('window.webContents.stopPainting()', () => { it('stops painting', async () => { const domReady = emittedOnce(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.stopPainting(); expect(w.webContents.isPainting()).to.be.false('isPainting'); }); }); describe('window.webContents.startPainting()', () => { it('starts painting', async () => { const domReady = emittedOnce(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.stopPainting(); w.webContents.startPainting(); await emittedOnce(w.webContents, 'paint'); expect(w.webContents.isPainting()).to.be.true('isPainting'); }); }); describe('frameRate APIs', () => { it('has default frame rate (function)', async () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await emittedOnce(w.webContents, 'paint'); expect(w.webContents.getFrameRate()).to.equal(60); }); it('has default frame rate (property)', async () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await emittedOnce(w.webContents, 'paint'); expect(w.webContents.frameRate).to.equal(60); }); it('sets custom frame rate (function)', async () => { const domReady = emittedOnce(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.setFrameRate(30); await emittedOnce(w.webContents, 'paint'); expect(w.webContents.getFrameRate()).to.equal(30); }); it('sets custom frame rate (property)', async () => { const domReady = emittedOnce(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.frameRate = 30; await emittedOnce(w.webContents, 'paint'); expect(w.webContents.frameRate).to.equal(30); }); }); }); describe('"transparent" option', () => { afterEach(closeAllWindows); // Only applicable on Windows where transparent windows can't be maximized. ifit(process.platform === 'win32')('can show maximized frameless window', async () => { const display = screen.getPrimaryDisplay(); const w = new BrowserWindow({ ...display.bounds, frame: false, transparent: true, show: true }); w.loadURL('about:blank'); await emittedOnce(w, 'ready-to-show'); expect(w.isMaximized()).to.be.true(); // Fails when the transparent HWND is in an invalid maximized state. expect(w.getBounds()).to.deep.equal(display.workArea); const newBounds = { width: 256, height: 256, x: 0, y: 0 }; w.setBounds(newBounds); expect(w.getBounds()).to.deep.equal(newBounds); }); // Linux and arm64 platforms (WOA and macOS) do not return any capture sources ifit(process.platform !== 'linux' && process.arch !== 'arm64')('should not display a visible background', async () => { const display = screen.getPrimaryDisplay(); const backgroundWindow = new BrowserWindow({ ...display.bounds, frame: false, backgroundColor: CHROMA_COLOR_HEX, hasShadow: false }); await backgroundWindow.loadURL('about:blank'); const foregroundWindow = new BrowserWindow({ ...display.bounds, show: true, transparent: true, frame: false, hasShadow: false }); foregroundWindow.loadFile(path.join(__dirname, 'fixtures', 'pages', 'half-background-color.html')); await emittedOnce(foregroundWindow, 'ready-to-show'); const screenCapture = await captureScreen(); const leftHalfColor = getPixelColor(screenCapture, { x: display.size.width / 4, y: display.size.height / 2 }); const rightHalfColor = getPixelColor(screenCapture, { x: display.size.width - (display.size.width / 4), y: display.size.height / 2 }); expect(areColorsSimilar(leftHalfColor, CHROMA_COLOR_HEX)).to.be.true(); expect(areColorsSimilar(rightHalfColor, '#ff0000')).to.be.true(); }); }); describe('"backgroundColor" option', () => { afterEach(closeAllWindows); // Linux/WOA doesn't return any capture sources. ifit(process.platform !== 'linux' && (process.platform !== 'win32' || process.arch !== 'arm64'))('should display the set color', async () => { const display = screen.getPrimaryDisplay(); const w = new BrowserWindow({ ...display.bounds, show: true, backgroundColor: CHROMA_COLOR_HEX }); w.loadURL('about:blank'); await emittedOnce(w, 'ready-to-show'); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); expect(areColorsSimilar(centerColor, CHROMA_COLOR_HEX)).to.be.true(); }); }); });
closed
electron/electron
https://github.com/electron/electron
33,097
Print the document WebView The print - > PageSize document is ambiguous
### 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 ![image](https://user-images.githubusercontent.com/39638510/155918554-ff390805-0e94-4e16-bc5e-ecc9ed631909.png) ![image](https://user-images.githubusercontent.com/39638510/155918561-6af614c3-5254-47bc-b73f-120fbe5a9da9.png) The unit of width and height is not clear. I don't know whether it should be Px, cm or mm ### Proposed Solution hope you can clarify the unit data of what to wear ### Alternatives Considered none ### Additional Information _No response_
https://github.com/electron/electron/issues/33097
https://github.com/electron/electron/pull/34088
97c9451efc3035a1072b1ff87aee125f7a9fa053
04b33b319b7fca9fbf415d67953643f9b29e2160
2022-02-28T03:21:42Z
c++
2022-05-17T15:59:24Z
docs/api/webview-tag.md
# `<webview>` Tag ## Warning Electron's `webview` tag is based on [Chromium's `webview`][chrome-webview], which is undergoing dramatic architectural changes. This impacts the stability of `webviews`, including rendering, navigation, and event routing. We currently recommend to not use the `webview` tag and to consider alternatives, like `iframe`, [Electron's `BrowserView`](browser-view.md), or an architecture that avoids embedded content altogether. ## Enabling By default the `webview` tag is disabled in Electron >= 5. You need to enable the tag by setting the `webviewTag` webPreferences option when constructing your `BrowserWindow`. For more information see the [BrowserWindow constructor docs](browser-window.md). ## Overview > Display external web content in an isolated frame and process. Process: [Renderer](../glossary.md#renderer-process)<br /> _This class is not exported from the `'electron'` module. It is only available as a return value of other methods in the Electron API._ Use the `webview` tag to embed 'guest' content (such as web pages) in your Electron app. The guest content is contained within the `webview` container. An embedded page within your app controls how the guest content is laid out and rendered. Unlike an `iframe`, the `webview` runs in a separate process than your app. It doesn't have the same permissions as your web page and all interactions between your app and embedded content will be asynchronous. This keeps your app safe from the embedded content. **Note:** Most methods called on the webview from the host page require a synchronous call to the main process. ## Example To embed a web page in your app, add the `webview` tag to your app's embedder page (this is the app page that will display the guest content). In its simplest form, the `webview` tag includes the `src` of the web page and css styles that control the appearance of the `webview` container: ```html <webview id="foo" src="https://www.github.com/" style="display:inline-flex; width:640px; height:480px"></webview> ``` If you want to control the guest content in any way, you can write JavaScript that listens for `webview` events and responds to those events using the `webview` methods. Here's sample code with two event listeners: one that listens for the web page to start loading, the other for the web page to stop loading, and displays a "loading..." message during the load time: ```html <script> onload = () => { const webview = document.querySelector('webview') const indicator = document.querySelector('.indicator') const loadstart = () => { indicator.innerText = 'loading...' } const loadstop = () => { indicator.innerText = '' } webview.addEventListener('did-start-loading', loadstart) webview.addEventListener('did-stop-loading', loadstop) } </script> ``` ## Internal implementation Under the hood `webview` is implemented with [Out-of-Process iframes (OOPIFs)](https://www.chromium.org/developers/design-documents/oop-iframes). The `webview` tag is essentially a custom element using shadow DOM to wrap an `iframe` element inside it. So the behavior of `webview` is very similar to a cross-domain `iframe`, as examples: * When clicking into a `webview`, the page focus will move from the embedder frame to `webview`. * You can not add keyboard, mouse, and scroll event listeners to `webview`. * All reactions between the embedder frame and `webview` are asynchronous. ## CSS Styling Notes Please note that the `webview` tag's style uses `display:flex;` internally to ensure the child `iframe` element fills the full height and width of its `webview` container when used with traditional and flexbox layouts. Please do not overwrite the default `display:flex;` CSS property, unless specifying `display:inline-flex;` for inline layout. ## Tag Attributes The `webview` tag has the following attributes: ### `src` ```html <webview src="https://www.github.com/"></webview> ``` A `string` representing the visible URL. Writing to this attribute initiates top-level navigation. Assigning `src` its own value will reload the current page. The `src` attribute can also accept data URLs, such as `data:text/plain,Hello, world!`. ### `nodeintegration` ```html <webview src="http://www.google.com/" nodeintegration></webview> ``` A `boolean`. When this attribute is present the guest page in `webview` will have node integration and can use node APIs like `require` and `process` to access low level system resources. Node integration is disabled by default in the guest page. ### `nodeintegrationinsubframes` ```html <webview src="http://www.google.com/" nodeintegrationinsubframes></webview> ``` A `boolean` for the experimental option for enabling NodeJS support in sub-frames such as iframes inside the `webview`. All your preloads will load for every iframe, you can use `process.isMainFrame` to determine if you are in the main frame or not. This option is disabled by default in the guest page. ### `plugins` ```html <webview src="https://www.github.com/" plugins></webview> ``` A `boolean`. When this attribute is present the guest page in `webview` will be able to use browser plugins. Plugins are disabled by default. ### `preload` ```html <!-- from a file --> <webview src="https://www.github.com/" preload="./test.js"></webview> <!-- or if you want to load from an asar archive --> <webview src="https://www.github.com/" preload="./app.asar/test.js"></webview> ``` A `string` that specifies a script that will be loaded before other scripts run in the guest page. The protocol of script's URL must be `file:` (even when using `asar:` archives) because it will be loaded by Node's `require` under the hood, which treats `asar:` archives as virtual directories. When the guest page doesn't have node integration this script will still have access to all Node APIs, but global objects injected by Node will be deleted after this script has finished executing. ### `httpreferrer` ```html <webview src="https://www.github.com/" httpreferrer="http://cheng.guru"></webview> ``` A `string` that sets the referrer URL for the guest page. ### `useragent` ```html <webview src="https://www.github.com/" useragent="Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; AS; rv:11.0) like Gecko"></webview> ``` A `string` that sets the user agent for the guest page before the page is navigated to. Once the page is loaded, use the `setUserAgent` method to change the user agent. ### `disablewebsecurity` ```html <webview src="https://www.github.com/" disablewebsecurity></webview> ``` A `boolean`. When this attribute is present the guest page will have web security disabled. Web security is enabled by default. ### `partition` ```html <webview src="https://github.com" partition="persist:github"></webview> <webview src="https://electronjs.org" partition="electron"></webview> ``` A `string` that sets the session used by the page. If `partition` starts with `persist:`, the page will use a persistent session available to all pages in the app with the same `partition`. if there is no `persist:` prefix, the page will use an in-memory session. By assigning the same `partition`, multiple pages can share the same session. If the `partition` is unset then default session of the app will be used. This value can only be modified before the first navigation, since the session of an active renderer process cannot change. Subsequent attempts to modify the value will fail with a DOM exception. ### `allowpopups` ```html <webview src="https://www.github.com/" allowpopups></webview> ``` A `boolean`. When this attribute is present the guest page will be allowed to open new windows. Popups are disabled by default. ### `webpreferences` ```html <webview src="https://github.com" webpreferences="allowRunningInsecureContent, javascript=no"></webview> ``` A `string` which is a comma separated list of strings which specifies the web preferences to be set on the webview. The full list of supported preference strings can be found in [BrowserWindow](browser-window.md#new-browserwindowoptions). The string follows the same format as the features string in `window.open`. A name by itself is given a `true` boolean value. A preference can be set to another value by including an `=`, followed by the value. Special values `yes` and `1` are interpreted as `true`, while `no` and `0` are interpreted as `false`. ### `enableblinkfeatures` ```html <webview src="https://www.github.com/" enableblinkfeatures="PreciseMemoryInfo, CSSVariables"></webview> ``` A `string` which is a list of strings which specifies the blink features to be enabled separated by `,`. The full list of supported feature strings can be found in the [RuntimeEnabledFeatures.json5][runtime-enabled-features] file. ### `disableblinkfeatures` ```html <webview src="https://www.github.com/" disableblinkfeatures="PreciseMemoryInfo, CSSVariables"></webview> ``` A `string` which is a list of strings which specifies the blink features to be disabled separated by `,`. The full list of supported feature strings can be found in the [RuntimeEnabledFeatures.json5][runtime-enabled-features] file. ## Methods The `webview` tag has the following methods: **Note:** The webview element must be loaded before using the methods. **Example** ```javascript const webview = document.querySelector('webview') webview.addEventListener('dom-ready', () => { webview.openDevTools() }) ``` ### `<webview>.loadURL(url[, options])` * `url` URL * `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`](webview-tag.md#event-did-finish-load)), and rejects if the page fails to load (see [`did-fail-load`](webview-tag.md#event-did-fail-load)). Loads the `url` in the webview, the `url` must contain the protocol prefix, e.g. the `http://` or `file://`. ### `<webview>.downloadURL(url)` * `url` string Initiates a download of the resource at `url` without navigating. ### `<webview>.getURL()` Returns `string` - The URL of guest page. ### `<webview>.getTitle()` Returns `string` - The title of guest page. ### `<webview>.isLoading()` Returns `boolean` - Whether guest page is still loading resources. ### `<webview>.isLoadingMainFrame()` Returns `boolean` - Whether the main frame (and not just iframes or frames within it) is still loading. ### `<webview>.isWaitingForResponse()` Returns `boolean` - Whether the guest page is waiting for a first-response for the main resource of the page. ### `<webview>.stop()` Stops any pending navigation. ### `<webview>.reload()` Reloads the guest page. ### `<webview>.reloadIgnoringCache()` Reloads the guest page and ignores cache. ### `<webview>.canGoBack()` Returns `boolean` - Whether the guest page can go back. ### `<webview>.canGoForward()` Returns `boolean` - Whether the guest page can go forward. ### `<webview>.canGoToOffset(offset)` * `offset` Integer Returns `boolean` - Whether the guest page can go to `offset`. ### `<webview>.clearHistory()` Clears the navigation history. ### `<webview>.goBack()` Makes the guest page go back. ### `<webview>.goForward()` Makes the guest page go forward. ### `<webview>.goToIndex(index)` * `index` Integer Navigates to the specified absolute index. ### `<webview>.goToOffset(offset)` * `offset` Integer Navigates to the specified offset from the "current entry". ### `<webview>.isCrashed()` Returns `boolean` - Whether the renderer process has crashed. ### `<webview>.setUserAgent(userAgent)` * `userAgent` string Overrides the user agent for the guest page. ### `<webview>.getUserAgent()` Returns `string` - The user agent for guest page. ### `<webview>.insertCSS(css)` * `css` string Returns `Promise<string>` - A promise that resolves with a key for the inserted CSS that can later be used to remove the CSS via `<webview>.removeInsertedCSS(key)`. Injects CSS into the current web page and returns a unique key for the inserted stylesheet. ### `<webview>.removeInsertedCSS(key)` * `key` string Returns `Promise<void>` - Resolves if the removal was successful. Removes the inserted CSS from the current web page. The stylesheet is identified by its key, which is returned from `<webview>.insertCSS(css)`. ### `<webview>.executeJavaScript(code[, userGesture])` * `code` string * `userGesture` boolean (optional) - Default `false`. Returns `Promise<any>` - A promise that resolves with the result of the executed code or is rejected if the result of the code is a rejected promise. Evaluates `code` in page. If `userGesture` is set, it will create the user gesture context in the page. HTML APIs like `requestFullScreen`, which require user action, can take advantage of this option for automation. ### `<webview>.openDevTools()` Opens a DevTools window for guest page. ### `<webview>.closeDevTools()` Closes the DevTools window of guest page. ### `<webview>.isDevToolsOpened()` Returns `boolean` - Whether guest page has a DevTools window attached. ### `<webview>.isDevToolsFocused()` Returns `boolean` - Whether DevTools window of guest page is focused. ### `<webview>.inspectElement(x, y)` * `x` Integer * `y` Integer Starts inspecting element at position (`x`, `y`) of guest page. ### `<webview>.inspectSharedWorker()` Opens the DevTools for the shared worker context present in the guest page. ### `<webview>.inspectServiceWorker()` Opens the DevTools for the service worker context present in the guest page. ### `<webview>.setAudioMuted(muted)` * `muted` boolean Set guest page muted. ### `<webview>.isAudioMuted()` Returns `boolean` - Whether guest page has been muted. ### `<webview>.isCurrentlyAudible()` Returns `boolean` - Whether audio is currently playing. ### `<webview>.undo()` Executes editing command `undo` in page. ### `<webview>.redo()` Executes editing command `redo` in page. ### `<webview>.cut()` Executes editing command `cut` in page. ### `<webview>.copy()` Executes editing command `copy` in page. ### `<webview>.paste()` Executes editing command `paste` in page. ### `<webview>.pasteAndMatchStyle()` Executes editing command `pasteAndMatchStyle` in page. ### `<webview>.delete()` Executes editing command `delete` in page. ### `<webview>.selectAll()` Executes editing command `selectAll` in page. ### `<webview>.unselect()` Executes editing command `unselect` in page. ### `<webview>.replace(text)` * `text` string Executes editing command `replace` in page. ### `<webview>.replaceMisspelling(text)` * `text` string Executes editing command `replaceMisspelling` in page. ### `<webview>.insertText(text)` * `text` string Returns `Promise<void>` Inserts `text` to the focused element. ### `<webview>.findInPage(text[, options])` * `text` string - Content to be searched, must not be empty. * `options` Object (optional) * `forward` boolean (optional) - Whether to search forward or backward, defaults to `true`. * `findNext` boolean (optional) - Whether to begin a new text finding session with this request. Should be `true` for initial requests, and `false` for follow-up requests. Defaults to `false`. * `matchCase` boolean (optional) - Whether search should be case-sensitive, defaults to `false`. Returns `Integer` - The request id used for the request. Starts a request to find all matches for the `text` in the web page. The result of the request can be obtained by subscribing to [`found-in-page`](webview-tag.md#event-found-in-page) event. ### `<webview>.stopFindInPage(action)` * `action` string - Specifies the action to take place when ending [`<webview>.findInPage`](#webviewfindinpagetext-options) request. * `clearSelection` - Clear the selection. * `keepSelection` - Translate the selection into a normal selection. * `activateSelection` - Focus and click the selection node. Stops any `findInPage` request for the `webview` with the provided `action`. ### `<webview>.print([options])` * `options` Object (optional) * `silent` boolean (optional) - Don't ask user for print settings. Default is `false`. * `printBackground` boolean (optional) - Prints the background color and image of the web page. Default is `false`. * `deviceName` string (optional) - Set the printer device name to use. Must be the system-defined name and not the 'friendly' name, e.g 'Brother_QL_820NWB' and not 'Brother QL-820NWB'. * `color` boolean (optional) - Set whether the printed web page will be in color or grayscale. Default is `true`. * `margins` Object (optional) * `marginType` string (optional) - Can be `default`, `none`, `printableArea`, or `custom`. If `custom` is chosen, you will also need to specify `top`, `bottom`, `left`, and `right`. * `top` number (optional) - The top margin of the printed web page, in pixels. * `bottom` number (optional) - The bottom margin of the printed web page, in pixels. * `left` number (optional) - The left margin of the printed web page, in pixels. * `right` number (optional) - The right margin of the printed web page, in pixels. * `landscape` boolean (optional) - Whether the web page should be printed in landscape mode. Default is `false`. * `scaleFactor` number (optional) - The scale factor of the web page. * `pagesPerSheet` number (optional) - The number of pages to print per page sheet. * `collate` boolean (optional) - Whether the web page should be collated. * `copies` number (optional) - The number of copies of the web page to print. * `pageRanges` Object[] (optional) - The page range to print. * `from` number - Index of the first page to print (0-based). * `to` number - Index of the last page to print (inclusive) (0-based). * `duplexMode` string (optional) - Set the duplex mode of the printed web page. Can be `simplex`, `shortEdge`, or `longEdge`. * `dpi` Record<string, number> (optional) * `horizontal` number (optional) - The horizontal dpi. * `vertical` number (optional) - The vertical dpi. * `header` string (optional) - string to be printed as page header. * `footer` string (optional) - string to be printed as page footer. * `pageSize` string | Size (optional) - Specify page size of the printed document. Can be `A3`, `A4`, `A5`, `Legal`, `Letter`, `Tabloid` or an Object containing `height`. Returns `Promise<void>` Prints `webview`'s web page. Same as `webContents.print([options])`. ### `<webview>.printToPDF(options)` * `options` Object * `headerFooter` Record<string, string> (optional) - the header and footer for the PDF. * `title` string - The title for the PDF header. * `url` string - the url for the PDF footer. * `landscape` boolean (optional) - `true` for landscape, `false` for portrait. * `marginsType` Integer (optional) - Specifies the type of margins to use. Uses 0 for default margin, 1 for no margin, and 2 for minimum margin. and `width` in microns. * `scaleFactor` number (optional) - The scale factor of the web page. Can range from 0 to 100. * `pageRanges` Record<string, number> (optional) - The page range to print. On macOS, only the first range is honored. * `from` number - Index of the first page to print (0-based). * `to` number - Index of the last page to print (inclusive) (0-based). * `pageSize` string | Size (optional) - Specify page size of the generated PDF. Can be `A3`, `A4`, `A5`, `Legal`, `Letter`, `Tabloid` or an Object containing `height` * `printBackground` boolean (optional) - Whether to print CSS backgrounds. * `printSelectionOnly` boolean (optional) - Whether to print selection only. Returns `Promise<Uint8Array>` - Resolves with the generated PDF data. Prints `webview`'s web page as PDF, Same as `webContents.printToPDF(options)`. ### `<webview>.capturePage([rect])` * `rect` [Rectangle](structures/rectangle.md) (optional) - The area of the page to be captured. Returns `Promise<NativeImage>` - Resolves with a [NativeImage](native-image.md) Captures a snapshot of the page within `rect`. Omitting `rect` will capture the whole visible page. ### `<webview>.send(channel, ...args)` * `channel` string * `...args` any[] Returns `Promise<void>` Send an asynchronous message to renderer process via `channel`, you can also send arbitrary arguments. The renderer process can handle the message by listening to the `channel` event with the [`ipcRenderer`](ipc-renderer.md) module. See [webContents.send](web-contents.md#contentssendchannel-args) for examples. ### `<webview>.sendToFrame(frameId, channel, ...args)` * `frameId` [number, number] - `[processId, frameId]` * `channel` string * `...args` any[] Returns `Promise<void>` Send an asynchronous message to renderer process via `channel`, you can also send arbitrary arguments. The renderer process can handle the message by listening to the `channel` event with the [`ipcRenderer`](ipc-renderer.md) module. See [webContents.sendToFrame](web-contents.md#contentssendtoframeframeid-channel-args) for examples. ### `<webview>.sendInputEvent(event)` * `event` [MouseInputEvent](structures/mouse-input-event.md) | [MouseWheelInputEvent](structures/mouse-wheel-input-event.md) | [KeyboardInputEvent](structures/keyboard-input-event.md) Returns `Promise<void>` Sends an input `event` to the page. See [webContents.sendInputEvent](web-contents.md#contentssendinputeventinputevent) for detailed description of `event` object. ### `<webview>.setZoomFactor(factor)` * `factor` number - Zoom factor. Changes the zoom factor to the specified factor. Zoom factor is zoom percent divided by 100, so 300% = 3.0. ### `<webview>.setZoomLevel(level)` * `level` number - Zoom level. Changes the zoom level to the specified level. The original size is 0 and each increment above or below represents zooming 20% larger or smaller to default limits of 300% and 50% of original size, respectively. The formula for this is `scale := 1.2 ^ level`. > **NOTE**: The zoom policy at the Chromium level is same-origin, meaning that the > zoom level for a specific domain propagates across all instances of windows with > the same domain. Differentiating the window URLs will make zoom work per-window. ### `<webview>.getZoomFactor()` Returns `number` - the current zoom factor. ### `<webview>.getZoomLevel()` Returns `number` - the current zoom level. ### `<webview>.setVisualZoomLevelLimits(minimumLevel, maximumLevel)` * `minimumLevel` number * `maximumLevel` number Returns `Promise<void>` Sets the maximum and minimum pinch-to-zoom level. ### `<webview>.showDefinitionForSelection()` _macOS_ Shows pop-up dictionary that searches the selected word on the page. ### `<webview>.getWebContentsId()` Returns `number` - The WebContents ID of this `webview`. ## DOM Events The following DOM events are available to the `webview` tag: ### Event: 'load-commit' Returns: * `url` string * `isMainFrame` boolean Fired when a load has committed. This includes navigation within the current document as well as subframe document-level loads, but does not include asynchronous resource loads. ### Event: 'did-finish-load' Fired when the navigation is done, i.e. the spinner of the tab will stop spinning, and the `onload` event is dispatched. ### Event: 'did-fail-load' Returns: * `errorCode` Integer * `errorDescription` string * `validatedURL` string * `isMainFrame` boolean This event is like `did-finish-load`, but fired when the load failed or was cancelled, e.g. `window.stop()` is invoked. ### Event: 'did-frame-finish-load' Returns: * `isMainFrame` boolean Fired when a frame has done navigation. ### Event: 'did-start-loading' Corresponds to the points in time when the spinner of the tab starts spinning. ### Event: 'did-stop-loading' Corresponds to the points in time when the spinner of the tab stops spinning. ### Event: 'did-attach' Fired when attached to the embedder web contents. ### Event: 'dom-ready' Fired when document in the given frame is loaded. ### Event: 'page-title-updated' Returns: * `title` string * `explicitSet` boolean Fired when page title is set during navigation. `explicitSet` is false when title is synthesized from file url. ### Event: 'page-favicon-updated' Returns: * `favicons` string[] - Array of URLs. Fired when page receives favicon urls. ### Event: 'enter-html-full-screen' Fired when page enters fullscreen triggered by HTML API. ### Event: 'leave-html-full-screen' Fired when page leaves fullscreen triggered by HTML API. ### Event: 'console-message' Returns: * `level` Integer - The log level, from 0 to 3. In order it matches `verbose`, `info`, `warning` and `error`. * `message` string - The actual console message * `line` Integer - The line number of the source that triggered this console message * `sourceId` string Fired when the guest window logs a console message. The following example code forwards all log messages to the embedder's console without regard for log level or other properties. ```javascript const webview = document.querySelector('webview') webview.addEventListener('console-message', (e) => { console.log('Guest page logged a message:', e.message) }) ``` ### Event: 'found-in-page' Returns: * `result` Object * `requestId` Integer * `activeMatchOrdinal` Integer - Position of the active match. * `matches` Integer - Number of Matches. * `selectionArea` Rectangle - Coordinates of first match region. * `finalUpdate` boolean Fired when a result is available for [`webview.findInPage`](#webviewfindinpagetext-options) request. ```javascript const webview = document.querySelector('webview') webview.addEventListener('found-in-page', (e) => { webview.stopFindInPage('keepSelection') }) const requestId = webview.findInPage('test') console.log(requestId) ``` ### Event: 'new-window' Returns: * `url` string * `frameName` string * `disposition` string - Can be `default`, `foreground-tab`, `background-tab`, `new-window`, `save-to-disk` and `other`. * `options` BrowserWindowConstructorOptions - The options which should be used for creating the new [`BrowserWindow`](browser-window.md). Fired when the guest page attempts to open a new browser window. The following example code opens the new url in system's default browser. ```javascript const { shell } = require('electron') const webview = document.querySelector('webview') webview.addEventListener('new-window', async (e) => { const protocol = (new URL(e.url)).protocol if (protocol === 'http:' || protocol === 'https:') { await shell.openExternal(e.url) } }) ``` ### Event: 'will-navigate' Returns: * `url` string Emitted when a user or the page wants to start navigation. It can happen when the `window.location` object is changed or a user clicks a link in the page. This event will not emit when the navigation is started programmatically with APIs like `<webview>.loadURL` and `<webview>.back`. It is also not emitted during in-page navigation, such as clicking anchor links or updating the `window.location.hash`. Use `did-navigate-in-page` event for this purpose. Calling `event.preventDefault()` does __NOT__ have any effect. ### Event: 'did-start-navigation' Returns: * `url` string * `isInPlace` boolean * `isMainFrame` boolean * `frameProcessId` Integer * `frameRoutingId` Integer Emitted when any frame (including main) starts navigating. `isInPlace` will be `true` for in-page navigations. ### Event: 'did-redirect-navigation' Returns: * `url` string * `isInPlace` boolean * `isMainFrame` boolean * `frameProcessId` Integer * `frameRoutingId` Integer Emitted after a server side redirect occurs during navigation. For example a 302 redirect. ### Event: 'did-navigate' Returns: * `url` string Emitted when a navigation is done. This event is not emitted for in-page navigations, such as clicking anchor links or updating the `window.location.hash`. Use `did-navigate-in-page` event for this purpose. ### Event: 'did-frame-navigate' Returns: * `url` string * `httpResponseCode` Integer - -1 for non HTTP navigations * `httpStatusText` string - empty for non HTTP navigations, * `isMainFrame` boolean * `frameProcessId` Integer * `frameRoutingId` Integer Emitted when any frame navigation is done. This event is not emitted for in-page navigations, such as clicking anchor links or updating the `window.location.hash`. Use `did-navigate-in-page` event for this purpose. ### Event: 'did-navigate-in-page' Returns: * `isMainFrame` boolean * `url` string Emitted when an in-page navigation happened. When in-page navigation happens, the page URL changes but does not cause navigation outside of the page. Examples of this occurring are when anchor links are clicked or when the DOM `hashchange` event is triggered. ### Event: 'close' Fired when the guest page attempts to close itself. The following example code navigates the `webview` to `about:blank` when the guest attempts to close itself. ```javascript const webview = document.querySelector('webview') webview.addEventListener('close', () => { webview.src = 'about:blank' }) ``` ### Event: 'ipc-message' Returns: * `frameId` [number, number] - pair of `[processId, frameId]`. * `channel` string * `args` any[] Fired when the guest page has sent an asynchronous message to embedder page. With `sendToHost` method and `ipc-message` event you can communicate between guest page and embedder page: ```javascript // In embedder page. const webview = document.querySelector('webview') webview.addEventListener('ipc-message', (event) => { console.log(event.channel) // Prints "pong" }) webview.send('ping') ``` ```javascript // In guest page. const { ipcRenderer } = require('electron') ipcRenderer.on('ping', () => { ipcRenderer.sendToHost('pong') }) ``` ### Event: 'crashed' Fired when the renderer process is crashed. ### Event: 'plugin-crashed' Returns: * `name` string * `version` string Fired when a plugin process is crashed. ### Event: 'destroyed' Fired when the WebContents is destroyed. ### Event: 'media-started-playing' Emitted when media starts playing. ### Event: 'media-paused' Emitted when media is paused or done playing. ### Event: 'did-change-theme-color' Returns: * `themeColor` string Emitted when a page's theme color changes. This is usually due to encountering a meta tag: ```html <meta name='theme-color' content='#ff0000'> ``` ### Event: 'update-target-url' Returns: * `url` string Emitted when mouse moves over a link or the keyboard moves the focus to a link. ### Event: 'devtools-opened' Emitted when DevTools is opened. ### Event: 'devtools-closed' Emitted when DevTools is closed. ### Event: 'devtools-focused' Emitted when DevTools is focused / opened. [runtime-enabled-features]: https://cs.chromium.org/chromium/src/third_party/blink/renderer/platform/runtime_enabled_features.json5?l=70 [chrome-webview]: https://developer.chrome.com/docs/extensions/reference/webviewTag/ ### Event: 'context-menu' Returns: * `params` Object * `x` Integer - x coordinate. * `y` Integer - y coordinate. * `linkURL` string - URL of the link that encloses the node the context menu was invoked on. * `linkText` string - Text associated with the link. May be an empty string if the contents of the link are an image. * `pageURL` string - URL of the top level page that the context menu was invoked on. * `frameURL` string - URL of the subframe that the context menu was invoked on. * `srcURL` string - Source URL for the element that the context menu was invoked on. Elements with source URLs are images, audio and video. * `mediaType` string - Type of the node the context menu was invoked on. Can be `none`, `image`, `audio`, `video`, `canvas`, `file` or `plugin`. * `hasImageContents` boolean - Whether the context menu was invoked on an image which has non-empty contents. * `isEditable` boolean - Whether the context is editable. * `selectionText` string - Text of the selection that the context menu was invoked on. * `titleText` string - Title text of the selection that the context menu was invoked on. * `altText` string - Alt text of the selection that the context menu was invoked on. * `suggestedFilename` string - Suggested filename to be used when saving file through 'Save Link As' option of context menu. * `selectionRect` [Rectangle](structures/rectangle.md) - Rect representing the coordinates in the document space of the selection. * `selectionStartOffset` number - Start position of the selection text. * `referrerPolicy` [Referrer](structures/referrer.md) - The referrer policy of the frame on which the menu is invoked. * `misspelledWord` string - The misspelled word under the cursor, if any. * `dictionarySuggestions` string[] - An array of suggested words to show the user to replace the `misspelledWord`. Only available if there is a misspelled word and spellchecker is enabled. * `frameCharset` string - The character encoding of the frame on which the menu was invoked. * `inputFieldType` string - If the context menu was invoked on an input field, the type of that field. Possible values are `none`, `plainText`, `password`, `other`. * `spellcheckEnabled` boolean - If the context is editable, whether or not spellchecking is enabled. * `menuSourceType` string - Input source that invoked the context menu. Can be `none`, `mouse`, `keyboard`, `touch`, `touchMenu`, `longPress`, `longTap`, `touchHandle`, `stylus`, `adjustSelection`, or `adjustSelectionReset`. * `mediaFlags` Object - The flags for the media element the context menu was invoked on. * `inError` boolean - Whether the media element has crashed. * `isPaused` boolean - Whether the media element is paused. * `isMuted` boolean - Whether the media element is muted. * `hasAudio` boolean - Whether the media element has audio. * `isLooping` boolean - Whether the media element is looping. * `isControlsVisible` boolean - Whether the media element's controls are visible. * `canToggleControls` boolean - Whether the media element's controls are toggleable. * `canPrint` boolean - Whether the media element can be printed. * `canSave` boolean - Whether or not the media element can be downloaded. * `canShowPictureInPicture` boolean - Whether the media element can show picture-in-picture. * `isShowingPictureInPicture` boolean - Whether the media element is currently showing picture-in-picture. * `canRotate` boolean - Whether the media element can be rotated. * `canLoop` boolean - Whether the media element can be looped. * `editFlags` Object - These flags indicate whether the renderer believes it is able to perform the corresponding action. * `canUndo` boolean - Whether the renderer believes it can undo. * `canRedo` boolean - Whether the renderer believes it can redo. * `canCut` boolean - Whether the renderer believes it can cut. * `canCopy` boolean - Whether the renderer believes it can copy. * `canPaste` boolean - Whether the renderer believes it can paste. * `canDelete` boolean - Whether the renderer believes it can delete. * `canSelectAll` boolean - Whether the renderer believes it can select all. * `canEditRichly` boolean - Whether the renderer believes it can edit text richly. Emitted when there is a new context menu that needs to be handled.
closed
electron/electron
https://github.com/electron/electron
33,097
Print the document WebView The print - > PageSize document is ambiguous
### 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 ![image](https://user-images.githubusercontent.com/39638510/155918554-ff390805-0e94-4e16-bc5e-ecc9ed631909.png) ![image](https://user-images.githubusercontent.com/39638510/155918561-6af614c3-5254-47bc-b73f-120fbe5a9da9.png) The unit of width and height is not clear. I don't know whether it should be Px, cm or mm ### Proposed Solution hope you can clarify the unit data of what to wear ### Alternatives Considered none ### Additional Information _No response_
https://github.com/electron/electron/issues/33097
https://github.com/electron/electron/pull/34088
97c9451efc3035a1072b1ff87aee125f7a9fa053
04b33b319b7fca9fbf415d67953643f9b29e2160
2022-02-28T03:21:42Z
c++
2022-05-17T15:59:24Z
docs/api/webview-tag.md
# `<webview>` Tag ## Warning Electron's `webview` tag is based on [Chromium's `webview`][chrome-webview], which is undergoing dramatic architectural changes. This impacts the stability of `webviews`, including rendering, navigation, and event routing. We currently recommend to not use the `webview` tag and to consider alternatives, like `iframe`, [Electron's `BrowserView`](browser-view.md), or an architecture that avoids embedded content altogether. ## Enabling By default the `webview` tag is disabled in Electron >= 5. You need to enable the tag by setting the `webviewTag` webPreferences option when constructing your `BrowserWindow`. For more information see the [BrowserWindow constructor docs](browser-window.md). ## Overview > Display external web content in an isolated frame and process. Process: [Renderer](../glossary.md#renderer-process)<br /> _This class is not exported from the `'electron'` module. It is only available as a return value of other methods in the Electron API._ Use the `webview` tag to embed 'guest' content (such as web pages) in your Electron app. The guest content is contained within the `webview` container. An embedded page within your app controls how the guest content is laid out and rendered. Unlike an `iframe`, the `webview` runs in a separate process than your app. It doesn't have the same permissions as your web page and all interactions between your app and embedded content will be asynchronous. This keeps your app safe from the embedded content. **Note:** Most methods called on the webview from the host page require a synchronous call to the main process. ## Example To embed a web page in your app, add the `webview` tag to your app's embedder page (this is the app page that will display the guest content). In its simplest form, the `webview` tag includes the `src` of the web page and css styles that control the appearance of the `webview` container: ```html <webview id="foo" src="https://www.github.com/" style="display:inline-flex; width:640px; height:480px"></webview> ``` If you want to control the guest content in any way, you can write JavaScript that listens for `webview` events and responds to those events using the `webview` methods. Here's sample code with two event listeners: one that listens for the web page to start loading, the other for the web page to stop loading, and displays a "loading..." message during the load time: ```html <script> onload = () => { const webview = document.querySelector('webview') const indicator = document.querySelector('.indicator') const loadstart = () => { indicator.innerText = 'loading...' } const loadstop = () => { indicator.innerText = '' } webview.addEventListener('did-start-loading', loadstart) webview.addEventListener('did-stop-loading', loadstop) } </script> ``` ## Internal implementation Under the hood `webview` is implemented with [Out-of-Process iframes (OOPIFs)](https://www.chromium.org/developers/design-documents/oop-iframes). The `webview` tag is essentially a custom element using shadow DOM to wrap an `iframe` element inside it. So the behavior of `webview` is very similar to a cross-domain `iframe`, as examples: * When clicking into a `webview`, the page focus will move from the embedder frame to `webview`. * You can not add keyboard, mouse, and scroll event listeners to `webview`. * All reactions between the embedder frame and `webview` are asynchronous. ## CSS Styling Notes Please note that the `webview` tag's style uses `display:flex;` internally to ensure the child `iframe` element fills the full height and width of its `webview` container when used with traditional and flexbox layouts. Please do not overwrite the default `display:flex;` CSS property, unless specifying `display:inline-flex;` for inline layout. ## Tag Attributes The `webview` tag has the following attributes: ### `src` ```html <webview src="https://www.github.com/"></webview> ``` A `string` representing the visible URL. Writing to this attribute initiates top-level navigation. Assigning `src` its own value will reload the current page. The `src` attribute can also accept data URLs, such as `data:text/plain,Hello, world!`. ### `nodeintegration` ```html <webview src="http://www.google.com/" nodeintegration></webview> ``` A `boolean`. When this attribute is present the guest page in `webview` will have node integration and can use node APIs like `require` and `process` to access low level system resources. Node integration is disabled by default in the guest page. ### `nodeintegrationinsubframes` ```html <webview src="http://www.google.com/" nodeintegrationinsubframes></webview> ``` A `boolean` for the experimental option for enabling NodeJS support in sub-frames such as iframes inside the `webview`. All your preloads will load for every iframe, you can use `process.isMainFrame` to determine if you are in the main frame or not. This option is disabled by default in the guest page. ### `plugins` ```html <webview src="https://www.github.com/" plugins></webview> ``` A `boolean`. When this attribute is present the guest page in `webview` will be able to use browser plugins. Plugins are disabled by default. ### `preload` ```html <!-- from a file --> <webview src="https://www.github.com/" preload="./test.js"></webview> <!-- or if you want to load from an asar archive --> <webview src="https://www.github.com/" preload="./app.asar/test.js"></webview> ``` A `string` that specifies a script that will be loaded before other scripts run in the guest page. The protocol of script's URL must be `file:` (even when using `asar:` archives) because it will be loaded by Node's `require` under the hood, which treats `asar:` archives as virtual directories. When the guest page doesn't have node integration this script will still have access to all Node APIs, but global objects injected by Node will be deleted after this script has finished executing. ### `httpreferrer` ```html <webview src="https://www.github.com/" httpreferrer="http://cheng.guru"></webview> ``` A `string` that sets the referrer URL for the guest page. ### `useragent` ```html <webview src="https://www.github.com/" useragent="Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; AS; rv:11.0) like Gecko"></webview> ``` A `string` that sets the user agent for the guest page before the page is navigated to. Once the page is loaded, use the `setUserAgent` method to change the user agent. ### `disablewebsecurity` ```html <webview src="https://www.github.com/" disablewebsecurity></webview> ``` A `boolean`. When this attribute is present the guest page will have web security disabled. Web security is enabled by default. ### `partition` ```html <webview src="https://github.com" partition="persist:github"></webview> <webview src="https://electronjs.org" partition="electron"></webview> ``` A `string` that sets the session used by the page. If `partition` starts with `persist:`, the page will use a persistent session available to all pages in the app with the same `partition`. if there is no `persist:` prefix, the page will use an in-memory session. By assigning the same `partition`, multiple pages can share the same session. If the `partition` is unset then default session of the app will be used. This value can only be modified before the first navigation, since the session of an active renderer process cannot change. Subsequent attempts to modify the value will fail with a DOM exception. ### `allowpopups` ```html <webview src="https://www.github.com/" allowpopups></webview> ``` A `boolean`. When this attribute is present the guest page will be allowed to open new windows. Popups are disabled by default. ### `webpreferences` ```html <webview src="https://github.com" webpreferences="allowRunningInsecureContent, javascript=no"></webview> ``` A `string` which is a comma separated list of strings which specifies the web preferences to be set on the webview. The full list of supported preference strings can be found in [BrowserWindow](browser-window.md#new-browserwindowoptions). The string follows the same format as the features string in `window.open`. A name by itself is given a `true` boolean value. A preference can be set to another value by including an `=`, followed by the value. Special values `yes` and `1` are interpreted as `true`, while `no` and `0` are interpreted as `false`. ### `enableblinkfeatures` ```html <webview src="https://www.github.com/" enableblinkfeatures="PreciseMemoryInfo, CSSVariables"></webview> ``` A `string` which is a list of strings which specifies the blink features to be enabled separated by `,`. The full list of supported feature strings can be found in the [RuntimeEnabledFeatures.json5][runtime-enabled-features] file. ### `disableblinkfeatures` ```html <webview src="https://www.github.com/" disableblinkfeatures="PreciseMemoryInfo, CSSVariables"></webview> ``` A `string` which is a list of strings which specifies the blink features to be disabled separated by `,`. The full list of supported feature strings can be found in the [RuntimeEnabledFeatures.json5][runtime-enabled-features] file. ## Methods The `webview` tag has the following methods: **Note:** The webview element must be loaded before using the methods. **Example** ```javascript const webview = document.querySelector('webview') webview.addEventListener('dom-ready', () => { webview.openDevTools() }) ``` ### `<webview>.loadURL(url[, options])` * `url` URL * `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`](webview-tag.md#event-did-finish-load)), and rejects if the page fails to load (see [`did-fail-load`](webview-tag.md#event-did-fail-load)). Loads the `url` in the webview, the `url` must contain the protocol prefix, e.g. the `http://` or `file://`. ### `<webview>.downloadURL(url)` * `url` string Initiates a download of the resource at `url` without navigating. ### `<webview>.getURL()` Returns `string` - The URL of guest page. ### `<webview>.getTitle()` Returns `string` - The title of guest page. ### `<webview>.isLoading()` Returns `boolean` - Whether guest page is still loading resources. ### `<webview>.isLoadingMainFrame()` Returns `boolean` - Whether the main frame (and not just iframes or frames within it) is still loading. ### `<webview>.isWaitingForResponse()` Returns `boolean` - Whether the guest page is waiting for a first-response for the main resource of the page. ### `<webview>.stop()` Stops any pending navigation. ### `<webview>.reload()` Reloads the guest page. ### `<webview>.reloadIgnoringCache()` Reloads the guest page and ignores cache. ### `<webview>.canGoBack()` Returns `boolean` - Whether the guest page can go back. ### `<webview>.canGoForward()` Returns `boolean` - Whether the guest page can go forward. ### `<webview>.canGoToOffset(offset)` * `offset` Integer Returns `boolean` - Whether the guest page can go to `offset`. ### `<webview>.clearHistory()` Clears the navigation history. ### `<webview>.goBack()` Makes the guest page go back. ### `<webview>.goForward()` Makes the guest page go forward. ### `<webview>.goToIndex(index)` * `index` Integer Navigates to the specified absolute index. ### `<webview>.goToOffset(offset)` * `offset` Integer Navigates to the specified offset from the "current entry". ### `<webview>.isCrashed()` Returns `boolean` - Whether the renderer process has crashed. ### `<webview>.setUserAgent(userAgent)` * `userAgent` string Overrides the user agent for the guest page. ### `<webview>.getUserAgent()` Returns `string` - The user agent for guest page. ### `<webview>.insertCSS(css)` * `css` string Returns `Promise<string>` - A promise that resolves with a key for the inserted CSS that can later be used to remove the CSS via `<webview>.removeInsertedCSS(key)`. Injects CSS into the current web page and returns a unique key for the inserted stylesheet. ### `<webview>.removeInsertedCSS(key)` * `key` string Returns `Promise<void>` - Resolves if the removal was successful. Removes the inserted CSS from the current web page. The stylesheet is identified by its key, which is returned from `<webview>.insertCSS(css)`. ### `<webview>.executeJavaScript(code[, userGesture])` * `code` string * `userGesture` boolean (optional) - Default `false`. Returns `Promise<any>` - A promise that resolves with the result of the executed code or is rejected if the result of the code is a rejected promise. Evaluates `code` in page. If `userGesture` is set, it will create the user gesture context in the page. HTML APIs like `requestFullScreen`, which require user action, can take advantage of this option for automation. ### `<webview>.openDevTools()` Opens a DevTools window for guest page. ### `<webview>.closeDevTools()` Closes the DevTools window of guest page. ### `<webview>.isDevToolsOpened()` Returns `boolean` - Whether guest page has a DevTools window attached. ### `<webview>.isDevToolsFocused()` Returns `boolean` - Whether DevTools window of guest page is focused. ### `<webview>.inspectElement(x, y)` * `x` Integer * `y` Integer Starts inspecting element at position (`x`, `y`) of guest page. ### `<webview>.inspectSharedWorker()` Opens the DevTools for the shared worker context present in the guest page. ### `<webview>.inspectServiceWorker()` Opens the DevTools for the service worker context present in the guest page. ### `<webview>.setAudioMuted(muted)` * `muted` boolean Set guest page muted. ### `<webview>.isAudioMuted()` Returns `boolean` - Whether guest page has been muted. ### `<webview>.isCurrentlyAudible()` Returns `boolean` - Whether audio is currently playing. ### `<webview>.undo()` Executes editing command `undo` in page. ### `<webview>.redo()` Executes editing command `redo` in page. ### `<webview>.cut()` Executes editing command `cut` in page. ### `<webview>.copy()` Executes editing command `copy` in page. ### `<webview>.paste()` Executes editing command `paste` in page. ### `<webview>.pasteAndMatchStyle()` Executes editing command `pasteAndMatchStyle` in page. ### `<webview>.delete()` Executes editing command `delete` in page. ### `<webview>.selectAll()` Executes editing command `selectAll` in page. ### `<webview>.unselect()` Executes editing command `unselect` in page. ### `<webview>.replace(text)` * `text` string Executes editing command `replace` in page. ### `<webview>.replaceMisspelling(text)` * `text` string Executes editing command `replaceMisspelling` in page. ### `<webview>.insertText(text)` * `text` string Returns `Promise<void>` Inserts `text` to the focused element. ### `<webview>.findInPage(text[, options])` * `text` string - Content to be searched, must not be empty. * `options` Object (optional) * `forward` boolean (optional) - Whether to search forward or backward, defaults to `true`. * `findNext` boolean (optional) - Whether to begin a new text finding session with this request. Should be `true` for initial requests, and `false` for follow-up requests. Defaults to `false`. * `matchCase` boolean (optional) - Whether search should be case-sensitive, defaults to `false`. Returns `Integer` - The request id used for the request. Starts a request to find all matches for the `text` in the web page. The result of the request can be obtained by subscribing to [`found-in-page`](webview-tag.md#event-found-in-page) event. ### `<webview>.stopFindInPage(action)` * `action` string - Specifies the action to take place when ending [`<webview>.findInPage`](#webviewfindinpagetext-options) request. * `clearSelection` - Clear the selection. * `keepSelection` - Translate the selection into a normal selection. * `activateSelection` - Focus and click the selection node. Stops any `findInPage` request for the `webview` with the provided `action`. ### `<webview>.print([options])` * `options` Object (optional) * `silent` boolean (optional) - Don't ask user for print settings. Default is `false`. * `printBackground` boolean (optional) - Prints the background color and image of the web page. Default is `false`. * `deviceName` string (optional) - Set the printer device name to use. Must be the system-defined name and not the 'friendly' name, e.g 'Brother_QL_820NWB' and not 'Brother QL-820NWB'. * `color` boolean (optional) - Set whether the printed web page will be in color or grayscale. Default is `true`. * `margins` Object (optional) * `marginType` string (optional) - Can be `default`, `none`, `printableArea`, or `custom`. If `custom` is chosen, you will also need to specify `top`, `bottom`, `left`, and `right`. * `top` number (optional) - The top margin of the printed web page, in pixels. * `bottom` number (optional) - The bottom margin of the printed web page, in pixels. * `left` number (optional) - The left margin of the printed web page, in pixels. * `right` number (optional) - The right margin of the printed web page, in pixels. * `landscape` boolean (optional) - Whether the web page should be printed in landscape mode. Default is `false`. * `scaleFactor` number (optional) - The scale factor of the web page. * `pagesPerSheet` number (optional) - The number of pages to print per page sheet. * `collate` boolean (optional) - Whether the web page should be collated. * `copies` number (optional) - The number of copies of the web page to print. * `pageRanges` Object[] (optional) - The page range to print. * `from` number - Index of the first page to print (0-based). * `to` number - Index of the last page to print (inclusive) (0-based). * `duplexMode` string (optional) - Set the duplex mode of the printed web page. Can be `simplex`, `shortEdge`, or `longEdge`. * `dpi` Record<string, number> (optional) * `horizontal` number (optional) - The horizontal dpi. * `vertical` number (optional) - The vertical dpi. * `header` string (optional) - string to be printed as page header. * `footer` string (optional) - string to be printed as page footer. * `pageSize` string | Size (optional) - Specify page size of the printed document. Can be `A3`, `A4`, `A5`, `Legal`, `Letter`, `Tabloid` or an Object containing `height`. Returns `Promise<void>` Prints `webview`'s web page. Same as `webContents.print([options])`. ### `<webview>.printToPDF(options)` * `options` Object * `headerFooter` Record<string, string> (optional) - the header and footer for the PDF. * `title` string - The title for the PDF header. * `url` string - the url for the PDF footer. * `landscape` boolean (optional) - `true` for landscape, `false` for portrait. * `marginsType` Integer (optional) - Specifies the type of margins to use. Uses 0 for default margin, 1 for no margin, and 2 for minimum margin. and `width` in microns. * `scaleFactor` number (optional) - The scale factor of the web page. Can range from 0 to 100. * `pageRanges` Record<string, number> (optional) - The page range to print. On macOS, only the first range is honored. * `from` number - Index of the first page to print (0-based). * `to` number - Index of the last page to print (inclusive) (0-based). * `pageSize` string | Size (optional) - Specify page size of the generated PDF. Can be `A3`, `A4`, `A5`, `Legal`, `Letter`, `Tabloid` or an Object containing `height` * `printBackground` boolean (optional) - Whether to print CSS backgrounds. * `printSelectionOnly` boolean (optional) - Whether to print selection only. Returns `Promise<Uint8Array>` - Resolves with the generated PDF data. Prints `webview`'s web page as PDF, Same as `webContents.printToPDF(options)`. ### `<webview>.capturePage([rect])` * `rect` [Rectangle](structures/rectangle.md) (optional) - The area of the page to be captured. Returns `Promise<NativeImage>` - Resolves with a [NativeImage](native-image.md) Captures a snapshot of the page within `rect`. Omitting `rect` will capture the whole visible page. ### `<webview>.send(channel, ...args)` * `channel` string * `...args` any[] Returns `Promise<void>` Send an asynchronous message to renderer process via `channel`, you can also send arbitrary arguments. The renderer process can handle the message by listening to the `channel` event with the [`ipcRenderer`](ipc-renderer.md) module. See [webContents.send](web-contents.md#contentssendchannel-args) for examples. ### `<webview>.sendToFrame(frameId, channel, ...args)` * `frameId` [number, number] - `[processId, frameId]` * `channel` string * `...args` any[] Returns `Promise<void>` Send an asynchronous message to renderer process via `channel`, you can also send arbitrary arguments. The renderer process can handle the message by listening to the `channel` event with the [`ipcRenderer`](ipc-renderer.md) module. See [webContents.sendToFrame](web-contents.md#contentssendtoframeframeid-channel-args) for examples. ### `<webview>.sendInputEvent(event)` * `event` [MouseInputEvent](structures/mouse-input-event.md) | [MouseWheelInputEvent](structures/mouse-wheel-input-event.md) | [KeyboardInputEvent](structures/keyboard-input-event.md) Returns `Promise<void>` Sends an input `event` to the page. See [webContents.sendInputEvent](web-contents.md#contentssendinputeventinputevent) for detailed description of `event` object. ### `<webview>.setZoomFactor(factor)` * `factor` number - Zoom factor. Changes the zoom factor to the specified factor. Zoom factor is zoom percent divided by 100, so 300% = 3.0. ### `<webview>.setZoomLevel(level)` * `level` number - Zoom level. Changes the zoom level to the specified level. The original size is 0 and each increment above or below represents zooming 20% larger or smaller to default limits of 300% and 50% of original size, respectively. The formula for this is `scale := 1.2 ^ level`. > **NOTE**: The zoom policy at the Chromium level is same-origin, meaning that the > zoom level for a specific domain propagates across all instances of windows with > the same domain. Differentiating the window URLs will make zoom work per-window. ### `<webview>.getZoomFactor()` Returns `number` - the current zoom factor. ### `<webview>.getZoomLevel()` Returns `number` - the current zoom level. ### `<webview>.setVisualZoomLevelLimits(minimumLevel, maximumLevel)` * `minimumLevel` number * `maximumLevel` number Returns `Promise<void>` Sets the maximum and minimum pinch-to-zoom level. ### `<webview>.showDefinitionForSelection()` _macOS_ Shows pop-up dictionary that searches the selected word on the page. ### `<webview>.getWebContentsId()` Returns `number` - The WebContents ID of this `webview`. ## DOM Events The following DOM events are available to the `webview` tag: ### Event: 'load-commit' Returns: * `url` string * `isMainFrame` boolean Fired when a load has committed. This includes navigation within the current document as well as subframe document-level loads, but does not include asynchronous resource loads. ### Event: 'did-finish-load' Fired when the navigation is done, i.e. the spinner of the tab will stop spinning, and the `onload` event is dispatched. ### Event: 'did-fail-load' Returns: * `errorCode` Integer * `errorDescription` string * `validatedURL` string * `isMainFrame` boolean This event is like `did-finish-load`, but fired when the load failed or was cancelled, e.g. `window.stop()` is invoked. ### Event: 'did-frame-finish-load' Returns: * `isMainFrame` boolean Fired when a frame has done navigation. ### Event: 'did-start-loading' Corresponds to the points in time when the spinner of the tab starts spinning. ### Event: 'did-stop-loading' Corresponds to the points in time when the spinner of the tab stops spinning. ### Event: 'did-attach' Fired when attached to the embedder web contents. ### Event: 'dom-ready' Fired when document in the given frame is loaded. ### Event: 'page-title-updated' Returns: * `title` string * `explicitSet` boolean Fired when page title is set during navigation. `explicitSet` is false when title is synthesized from file url. ### Event: 'page-favicon-updated' Returns: * `favicons` string[] - Array of URLs. Fired when page receives favicon urls. ### Event: 'enter-html-full-screen' Fired when page enters fullscreen triggered by HTML API. ### Event: 'leave-html-full-screen' Fired when page leaves fullscreen triggered by HTML API. ### Event: 'console-message' Returns: * `level` Integer - The log level, from 0 to 3. In order it matches `verbose`, `info`, `warning` and `error`. * `message` string - The actual console message * `line` Integer - The line number of the source that triggered this console message * `sourceId` string Fired when the guest window logs a console message. The following example code forwards all log messages to the embedder's console without regard for log level or other properties. ```javascript const webview = document.querySelector('webview') webview.addEventListener('console-message', (e) => { console.log('Guest page logged a message:', e.message) }) ``` ### Event: 'found-in-page' Returns: * `result` Object * `requestId` Integer * `activeMatchOrdinal` Integer - Position of the active match. * `matches` Integer - Number of Matches. * `selectionArea` Rectangle - Coordinates of first match region. * `finalUpdate` boolean Fired when a result is available for [`webview.findInPage`](#webviewfindinpagetext-options) request. ```javascript const webview = document.querySelector('webview') webview.addEventListener('found-in-page', (e) => { webview.stopFindInPage('keepSelection') }) const requestId = webview.findInPage('test') console.log(requestId) ``` ### Event: 'new-window' Returns: * `url` string * `frameName` string * `disposition` string - Can be `default`, `foreground-tab`, `background-tab`, `new-window`, `save-to-disk` and `other`. * `options` BrowserWindowConstructorOptions - The options which should be used for creating the new [`BrowserWindow`](browser-window.md). Fired when the guest page attempts to open a new browser window. The following example code opens the new url in system's default browser. ```javascript const { shell } = require('electron') const webview = document.querySelector('webview') webview.addEventListener('new-window', async (e) => { const protocol = (new URL(e.url)).protocol if (protocol === 'http:' || protocol === 'https:') { await shell.openExternal(e.url) } }) ``` ### Event: 'will-navigate' Returns: * `url` string Emitted when a user or the page wants to start navigation. It can happen when the `window.location` object is changed or a user clicks a link in the page. This event will not emit when the navigation is started programmatically with APIs like `<webview>.loadURL` and `<webview>.back`. It is also not emitted during in-page navigation, such as clicking anchor links or updating the `window.location.hash`. Use `did-navigate-in-page` event for this purpose. Calling `event.preventDefault()` does __NOT__ have any effect. ### Event: 'did-start-navigation' Returns: * `url` string * `isInPlace` boolean * `isMainFrame` boolean * `frameProcessId` Integer * `frameRoutingId` Integer Emitted when any frame (including main) starts navigating. `isInPlace` will be `true` for in-page navigations. ### Event: 'did-redirect-navigation' Returns: * `url` string * `isInPlace` boolean * `isMainFrame` boolean * `frameProcessId` Integer * `frameRoutingId` Integer Emitted after a server side redirect occurs during navigation. For example a 302 redirect. ### Event: 'did-navigate' Returns: * `url` string Emitted when a navigation is done. This event is not emitted for in-page navigations, such as clicking anchor links or updating the `window.location.hash`. Use `did-navigate-in-page` event for this purpose. ### Event: 'did-frame-navigate' Returns: * `url` string * `httpResponseCode` Integer - -1 for non HTTP navigations * `httpStatusText` string - empty for non HTTP navigations, * `isMainFrame` boolean * `frameProcessId` Integer * `frameRoutingId` Integer Emitted when any frame navigation is done. This event is not emitted for in-page navigations, such as clicking anchor links or updating the `window.location.hash`. Use `did-navigate-in-page` event for this purpose. ### Event: 'did-navigate-in-page' Returns: * `isMainFrame` boolean * `url` string Emitted when an in-page navigation happened. When in-page navigation happens, the page URL changes but does not cause navigation outside of the page. Examples of this occurring are when anchor links are clicked or when the DOM `hashchange` event is triggered. ### Event: 'close' Fired when the guest page attempts to close itself. The following example code navigates the `webview` to `about:blank` when the guest attempts to close itself. ```javascript const webview = document.querySelector('webview') webview.addEventListener('close', () => { webview.src = 'about:blank' }) ``` ### Event: 'ipc-message' Returns: * `frameId` [number, number] - pair of `[processId, frameId]`. * `channel` string * `args` any[] Fired when the guest page has sent an asynchronous message to embedder page. With `sendToHost` method and `ipc-message` event you can communicate between guest page and embedder page: ```javascript // In embedder page. const webview = document.querySelector('webview') webview.addEventListener('ipc-message', (event) => { console.log(event.channel) // Prints "pong" }) webview.send('ping') ``` ```javascript // In guest page. const { ipcRenderer } = require('electron') ipcRenderer.on('ping', () => { ipcRenderer.sendToHost('pong') }) ``` ### Event: 'crashed' Fired when the renderer process is crashed. ### Event: 'plugin-crashed' Returns: * `name` string * `version` string Fired when a plugin process is crashed. ### Event: 'destroyed' Fired when the WebContents is destroyed. ### Event: 'media-started-playing' Emitted when media starts playing. ### Event: 'media-paused' Emitted when media is paused or done playing. ### Event: 'did-change-theme-color' Returns: * `themeColor` string Emitted when a page's theme color changes. This is usually due to encountering a meta tag: ```html <meta name='theme-color' content='#ff0000'> ``` ### Event: 'update-target-url' Returns: * `url` string Emitted when mouse moves over a link or the keyboard moves the focus to a link. ### Event: 'devtools-opened' Emitted when DevTools is opened. ### Event: 'devtools-closed' Emitted when DevTools is closed. ### Event: 'devtools-focused' Emitted when DevTools is focused / opened. [runtime-enabled-features]: https://cs.chromium.org/chromium/src/third_party/blink/renderer/platform/runtime_enabled_features.json5?l=70 [chrome-webview]: https://developer.chrome.com/docs/extensions/reference/webviewTag/ ### Event: 'context-menu' Returns: * `params` Object * `x` Integer - x coordinate. * `y` Integer - y coordinate. * `linkURL` string - URL of the link that encloses the node the context menu was invoked on. * `linkText` string - Text associated with the link. May be an empty string if the contents of the link are an image. * `pageURL` string - URL of the top level page that the context menu was invoked on. * `frameURL` string - URL of the subframe that the context menu was invoked on. * `srcURL` string - Source URL for the element that the context menu was invoked on. Elements with source URLs are images, audio and video. * `mediaType` string - Type of the node the context menu was invoked on. Can be `none`, `image`, `audio`, `video`, `canvas`, `file` or `plugin`. * `hasImageContents` boolean - Whether the context menu was invoked on an image which has non-empty contents. * `isEditable` boolean - Whether the context is editable. * `selectionText` string - Text of the selection that the context menu was invoked on. * `titleText` string - Title text of the selection that the context menu was invoked on. * `altText` string - Alt text of the selection that the context menu was invoked on. * `suggestedFilename` string - Suggested filename to be used when saving file through 'Save Link As' option of context menu. * `selectionRect` [Rectangle](structures/rectangle.md) - Rect representing the coordinates in the document space of the selection. * `selectionStartOffset` number - Start position of the selection text. * `referrerPolicy` [Referrer](structures/referrer.md) - The referrer policy of the frame on which the menu is invoked. * `misspelledWord` string - The misspelled word under the cursor, if any. * `dictionarySuggestions` string[] - An array of suggested words to show the user to replace the `misspelledWord`. Only available if there is a misspelled word and spellchecker is enabled. * `frameCharset` string - The character encoding of the frame on which the menu was invoked. * `inputFieldType` string - If the context menu was invoked on an input field, the type of that field. Possible values are `none`, `plainText`, `password`, `other`. * `spellcheckEnabled` boolean - If the context is editable, whether or not spellchecking is enabled. * `menuSourceType` string - Input source that invoked the context menu. Can be `none`, `mouse`, `keyboard`, `touch`, `touchMenu`, `longPress`, `longTap`, `touchHandle`, `stylus`, `adjustSelection`, or `adjustSelectionReset`. * `mediaFlags` Object - The flags for the media element the context menu was invoked on. * `inError` boolean - Whether the media element has crashed. * `isPaused` boolean - Whether the media element is paused. * `isMuted` boolean - Whether the media element is muted. * `hasAudio` boolean - Whether the media element has audio. * `isLooping` boolean - Whether the media element is looping. * `isControlsVisible` boolean - Whether the media element's controls are visible. * `canToggleControls` boolean - Whether the media element's controls are toggleable. * `canPrint` boolean - Whether the media element can be printed. * `canSave` boolean - Whether or not the media element can be downloaded. * `canShowPictureInPicture` boolean - Whether the media element can show picture-in-picture. * `isShowingPictureInPicture` boolean - Whether the media element is currently showing picture-in-picture. * `canRotate` boolean - Whether the media element can be rotated. * `canLoop` boolean - Whether the media element can be looped. * `editFlags` Object - These flags indicate whether the renderer believes it is able to perform the corresponding action. * `canUndo` boolean - Whether the renderer believes it can undo. * `canRedo` boolean - Whether the renderer believes it can redo. * `canCut` boolean - Whether the renderer believes it can cut. * `canCopy` boolean - Whether the renderer believes it can copy. * `canPaste` boolean - Whether the renderer believes it can paste. * `canDelete` boolean - Whether the renderer believes it can delete. * `canSelectAll` boolean - Whether the renderer believes it can select all. * `canEditRichly` boolean - Whether the renderer believes it can edit text richly. Emitted when there is a new context menu that needs to be handled.
closed
electron/electron
https://github.com/electron/electron
33,897
[Bug]: setSize on BrowserWindow during will-resize is applied on mouse-up and not immediately
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.4.0 ### What operating system are you using? Windows ### Operating System Version Windows 10 Pro 21H2 ### What arch are you using? ia32 ### Last Known Working Electron version 17.3.1 ### Expected Behavior When calling the setSize on a browser window in the main process during the will-resize event, the width and height should be applied immediately in combination with the preventDefault on the event. ### Actual Behavior When calling the setSize on a browser window in the main process during the will-resize event, the width and height isn't set immediately anymore in combination with the preventDefault on the event. When you resize the window and during will-resize event you set the size of the window (for e.g. handling minimal width and minimal height), the new size isn't affective immediately. The size is applied when you stop resizing by a mouse up. With Electron version 17.3.1 and lower the setSize worked fine during will-resize event. ### Testcase Gist URL https://gist.github.com/ccc3e3fa4f724b5d717d9fc8f9c8dfe2 ### Additional Information I suspect that the new behavior is caused by the following PR: https://github.com/electron/electron/pull/33288 My application has some behavior implemented for controlling the minimal width and height in combination with the zoom factor. This is now broken and resizing freezes the resizing when the minimal width or height is reached. The setSize I use to continue resizing for the width/height where the limit isn't reached yet. It looks like the new behavior in Electron 17.4.0 is delaying the setSize until resize is done which breaks the behavior of my application.
https://github.com/electron/electron/issues/33897
https://github.com/electron/electron/pull/34204
455544dfb6b8fb4e3912c54d69379d88cd1250ef
73e0bf973d2b7835290d61cab6638309a21a2719
2022-04-22T10:12:41Z
c++
2022-05-19T08:03:02Z
shell/browser/native_window_views_win.cc
// Copyright (c) 2015 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include <dwmapi.h> #include <shellapi.h> #include <wrl/client.h> #include "base/win/atl.h" // Must be before UIAutomationCore.h #include "content/public/browser/browser_accessibility_state.h" #include "shell/browser/browser.h" #include "shell/browser/native_window_views.h" #include "shell/browser/ui/views/root_view.h" #include "shell/common/electron_constants.h" #include "ui/display/display.h" #include "ui/display/win/screen_win.h" #include "ui/gfx/geometry/insets.h" #include "ui/gfx/geometry/resize_utils.h" #include "ui/views/widget/native_widget_private.h" // Must be included after other Windows headers. #include <UIAutomationClient.h> #include <UIAutomationCoreApi.h> namespace electron { namespace { // Convert Win32 WM_APPCOMMANDS to strings. const char* AppCommandToString(int command_id) { switch (command_id) { case APPCOMMAND_BROWSER_BACKWARD: return kBrowserBackward; case APPCOMMAND_BROWSER_FORWARD: return kBrowserForward; case APPCOMMAND_BROWSER_REFRESH: return "browser-refresh"; case APPCOMMAND_BROWSER_STOP: return "browser-stop"; case APPCOMMAND_BROWSER_SEARCH: return "browser-search"; case APPCOMMAND_BROWSER_FAVORITES: return "browser-favorites"; case APPCOMMAND_BROWSER_HOME: return "browser-home"; case APPCOMMAND_VOLUME_MUTE: return "volume-mute"; case APPCOMMAND_VOLUME_DOWN: return "volume-down"; case APPCOMMAND_VOLUME_UP: return "volume-up"; case APPCOMMAND_MEDIA_NEXTTRACK: return "media-nexttrack"; case APPCOMMAND_MEDIA_PREVIOUSTRACK: return "media-previoustrack"; case APPCOMMAND_MEDIA_STOP: return "media-stop"; case APPCOMMAND_MEDIA_PLAY_PAUSE: return "media-play-pause"; case APPCOMMAND_LAUNCH_MAIL: return "launch-mail"; case APPCOMMAND_LAUNCH_MEDIA_SELECT: return "launch-media-select"; case APPCOMMAND_LAUNCH_APP1: return "launch-app1"; case APPCOMMAND_LAUNCH_APP2: return "launch-app2"; case APPCOMMAND_BASS_DOWN: return "bass-down"; case APPCOMMAND_BASS_BOOST: return "bass-boost"; case APPCOMMAND_BASS_UP: return "bass-up"; case APPCOMMAND_TREBLE_DOWN: return "treble-down"; case APPCOMMAND_TREBLE_UP: return "treble-up"; case APPCOMMAND_MICROPHONE_VOLUME_MUTE: return "microphone-volume-mute"; case APPCOMMAND_MICROPHONE_VOLUME_DOWN: return "microphone-volume-down"; case APPCOMMAND_MICROPHONE_VOLUME_UP: return "microphone-volume-up"; case APPCOMMAND_HELP: return "help"; case APPCOMMAND_FIND: return "find"; case APPCOMMAND_NEW: return "new"; case APPCOMMAND_OPEN: return "open"; case APPCOMMAND_CLOSE: return "close"; case APPCOMMAND_SAVE: return "save"; case APPCOMMAND_PRINT: return "print"; case APPCOMMAND_UNDO: return "undo"; case APPCOMMAND_REDO: return "redo"; case APPCOMMAND_COPY: return "copy"; case APPCOMMAND_CUT: return "cut"; case APPCOMMAND_PASTE: return "paste"; case APPCOMMAND_REPLY_TO_MAIL: return "reply-to-mail"; case APPCOMMAND_FORWARD_MAIL: return "forward-mail"; case APPCOMMAND_SEND_MAIL: return "send-mail"; case APPCOMMAND_SPELL_CHECK: return "spell-check"; case APPCOMMAND_MIC_ON_OFF_TOGGLE: return "mic-on-off-toggle"; case APPCOMMAND_CORRECTION_LIST: return "correction-list"; case APPCOMMAND_MEDIA_PLAY: return "media-play"; case APPCOMMAND_MEDIA_PAUSE: return "media-pause"; case APPCOMMAND_MEDIA_RECORD: return "media-record"; case APPCOMMAND_MEDIA_FAST_FORWARD: return "media-fast-forward"; case APPCOMMAND_MEDIA_REWIND: return "media-rewind"; case APPCOMMAND_MEDIA_CHANNEL_UP: return "media-channel-up"; case APPCOMMAND_MEDIA_CHANNEL_DOWN: return "media-channel-down"; case APPCOMMAND_DELETE: return "delete"; case APPCOMMAND_DICTATE_OR_COMMAND_CONTROL_TOGGLE: return "dictate-or-command-control-toggle"; default: return "unknown"; } } // Copied from ui/views/win/hwnd_message_handler.cc gfx::ResizeEdge GetWindowResizeEdge(WPARAM param) { switch (param) { case WMSZ_BOTTOM: return gfx::ResizeEdge::kBottom; case WMSZ_TOP: return gfx::ResizeEdge::kTop; case WMSZ_LEFT: return gfx::ResizeEdge::kLeft; case WMSZ_RIGHT: return gfx::ResizeEdge::kRight; case WMSZ_TOPLEFT: return gfx::ResizeEdge::kTopLeft; case WMSZ_TOPRIGHT: return gfx::ResizeEdge::kTopRight; case WMSZ_BOTTOMLEFT: return gfx::ResizeEdge::kBottomLeft; case WMSZ_BOTTOMRIGHT: return gfx::ResizeEdge::kBottomRight; default: return gfx::ResizeEdge::kBottomRight; } } bool IsScreenReaderActive() { UINT screenReader = 0; SystemParametersInfo(SPI_GETSCREENREADER, 0, &screenReader, 0); return screenReader && UiaClientsAreListening(); } } // namespace std::set<NativeWindowViews*> NativeWindowViews::forwarding_windows_; HHOOK NativeWindowViews::mouse_hook_ = NULL; void NativeWindowViews::Maximize() { // Only use Maximize() when window is NOT transparent style if (!transparent()) { if (IsVisible()) { widget()->Maximize(); } else { widget()->native_widget_private()->Show(ui::SHOW_STATE_MAXIMIZED, gfx::Rect()); 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)); 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)); return true; // Tells Windows that the Move is handled. If not true, // frameless windows can be moved using // -webkit-app-region: drag elements. } return false; } case WM_ENDSESSION: { if (w_param) { NotifyWindowEndSession(); } return false; } case WM_PARENTNOTIFY: { if (LOWORD(w_param) == WM_CREATE) { // Because of reasons regarding legacy drivers and stuff, a window that // matches the client area is created and used internally by Chromium. // This is used when forwarding mouse messages. We only cache the first // occurrence (the webview window) because dev tools also cause this // message to be sent. if (!legacy_window_) { legacy_window_ = reinterpret_cast<HWND>(l_param); } } return false; } case WM_CONTEXTMENU: { bool prevent_default = false; NotifyWindowSystemContextMenu(GET_X_LPARAM(l_param), GET_Y_LPARAM(l_param), &prevent_default); return prevent_default; } case WM_SYSCOMMAND: { // Mask is needed to account for double clicking title bar to maximize WPARAM max_mask = 0xFFF0; if (transparent() && ((w_param & max_mask) == SC_MAXIMIZE)) { return true; } return false; } case WM_INITMENU: { // This is handling the scenario where the menu might get triggered by the // user doing "alt + space" resulting in system maximization and restore // being used on transparent windows when that does not work. if (transparent()) { HMENU menu = GetSystemMenu(GetAcceleratedWidget(), false); EnableMenuItem(menu, SC_MAXIMIZE, MF_BYCOMMAND | MF_DISABLED | MF_GRAYED); EnableMenuItem(menu, SC_RESTORE, MF_BYCOMMAND | MF_DISABLED | MF_GRAYED); return true; } return false; } default: { return false; } } } void NativeWindowViews::HandleSizeEvent(WPARAM w_param, LPARAM l_param) { // Here we handle the WM_SIZE event in order to figure out what is the current // window state and notify the user accordingly. switch (w_param) { case SIZE_MAXIMIZED: case SIZE_MINIMIZED: { WINDOWPLACEMENT wp; wp.length = sizeof(WINDOWPLACEMENT); if (GetWindowPlacement(GetAcceleratedWidget(), &wp)) { last_normal_placement_bounds_ = gfx::Rect(wp.rcNormalPosition); } // Note that SIZE_MAXIMIZED and SIZE_MINIMIZED might be emitted for // multiple times for one resize because of the SetWindowPlacement call. if (w_param == SIZE_MAXIMIZED && last_window_state_ != ui::SHOW_STATE_MAXIMIZED) { last_window_state_ = ui::SHOW_STATE_MAXIMIZED; NotifyWindowMaximize(); } else if (w_param == SIZE_MINIMIZED && last_window_state_ != ui::SHOW_STATE_MINIMIZED) { last_window_state_ = ui::SHOW_STATE_MINIMIZED; NotifyWindowMinimize(); } break; } case SIZE_RESTORED: switch (last_window_state_) { case ui::SHOW_STATE_MAXIMIZED: last_window_state_ = ui::SHOW_STATE_NORMAL; NotifyWindowUnmaximize(); break; case ui::SHOW_STATE_MINIMIZED: if (IsFullscreen()) { last_window_state_ = ui::SHOW_STATE_FULLSCREEN; NotifyWindowEnterFullScreen(); } else { last_window_state_ = ui::SHOW_STATE_NORMAL; NotifyWindowRestore(); } break; default: break; } break; } } void NativeWindowViews::SetForwardMouseMessages(bool forward) { if (forward && !forwarding_mouse_messages_) { forwarding_mouse_messages_ = true; forwarding_windows_.insert(this); // Subclassing is used to fix some issues when forwarding mouse messages; // see comments in |SubclassProc|. SetWindowSubclass(legacy_window_, SubclassProc, 1, reinterpret_cast<DWORD_PTR>(this)); if (!mouse_hook_) { mouse_hook_ = SetWindowsHookEx(WH_MOUSE_LL, MouseHookProc, NULL, 0); } } else if (!forward && forwarding_mouse_messages_) { forwarding_mouse_messages_ = false; forwarding_windows_.erase(this); RemoveWindowSubclass(legacy_window_, SubclassProc, 1); if (forwarding_windows_.empty()) { UnhookWindowsHookEx(mouse_hook_); mouse_hook_ = NULL; } } } LRESULT CALLBACK NativeWindowViews::SubclassProc(HWND hwnd, UINT msg, WPARAM w_param, LPARAM l_param, UINT_PTR subclass_id, DWORD_PTR ref_data) { auto* window = reinterpret_cast<NativeWindowViews*>(ref_data); switch (msg) { case WM_MOUSELEAVE: { // When input is forwarded to underlying windows, this message is posted. // If not handled, it interferes with Chromium logic, causing for example // mouseleave events to fire. If those events are used to exit forward // mode, excessive flickering on for example hover items in underlying // windows can occur due to rapidly entering and leaving forwarding mode. // By consuming and ignoring the message, we're essentially telling // Chromium that we have not left the window despite somebody else getting // the messages. As to why this is caught for the legacy window and not // the actual browser window is simply that the legacy window somehow // makes use of these events; posting to the main window didn't work. if (window->forwarding_mouse_messages_) { return 0; } break; } } return DefSubclassProc(hwnd, msg, w_param, l_param); } LRESULT CALLBACK NativeWindowViews::MouseHookProc(int n_code, WPARAM w_param, LPARAM l_param) { if (n_code < 0) { return CallNextHookEx(NULL, n_code, w_param, l_param); } // Post a WM_MOUSEMOVE message for those windows whose client area contains // the cursor since they are in a state where they would otherwise ignore all // mouse input. if (w_param == WM_MOUSEMOVE) { for (auto* window : forwarding_windows_) { // At first I considered enumerating windows to check whether the cursor // was directly above the window, but since nothing bad seems to happen // if we post the message even if some other window occludes it I have // just left it as is. RECT client_rect; GetClientRect(window->legacy_window_, &client_rect); POINT p = reinterpret_cast<MSLLHOOKSTRUCT*>(l_param)->pt; ScreenToClient(window->legacy_window_, &p); if (PtInRect(&client_rect, p)) { WPARAM w = 0; // No virtual keys pressed for our purposes LPARAM l = MAKELPARAM(p.x, p.y); PostMessage(window->legacy_window_, WM_MOUSEMOVE, w, l); } } } return CallNextHookEx(NULL, n_code, w_param, l_param); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
33,897
[Bug]: setSize on BrowserWindow during will-resize is applied on mouse-up and not immediately
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.4.0 ### What operating system are you using? Windows ### Operating System Version Windows 10 Pro 21H2 ### What arch are you using? ia32 ### Last Known Working Electron version 17.3.1 ### Expected Behavior When calling the setSize on a browser window in the main process during the will-resize event, the width and height should be applied immediately in combination with the preventDefault on the event. ### Actual Behavior When calling the setSize on a browser window in the main process during the will-resize event, the width and height isn't set immediately anymore in combination with the preventDefault on the event. When you resize the window and during will-resize event you set the size of the window (for e.g. handling minimal width and minimal height), the new size isn't affective immediately. The size is applied when you stop resizing by a mouse up. With Electron version 17.3.1 and lower the setSize worked fine during will-resize event. ### Testcase Gist URL https://gist.github.com/ccc3e3fa4f724b5d717d9fc8f9c8dfe2 ### Additional Information I suspect that the new behavior is caused by the following PR: https://github.com/electron/electron/pull/33288 My application has some behavior implemented for controlling the minimal width and height in combination with the zoom factor. This is now broken and resizing freezes the resizing when the minimal width or height is reached. The setSize I use to continue resizing for the width/height where the limit isn't reached yet. It looks like the new behavior in Electron 17.4.0 is delaying the setSize until resize is done which breaks the behavior of my application.
https://github.com/electron/electron/issues/33897
https://github.com/electron/electron/pull/34204
455544dfb6b8fb4e3912c54d69379d88cd1250ef
73e0bf973d2b7835290d61cab6638309a21a2719
2022-04-22T10:12:41Z
c++
2022-05-19T08:03:02Z
shell/browser/native_window_views_win.cc
// Copyright (c) 2015 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include <dwmapi.h> #include <shellapi.h> #include <wrl/client.h> #include "base/win/atl.h" // Must be before UIAutomationCore.h #include "content/public/browser/browser_accessibility_state.h" #include "shell/browser/browser.h" #include "shell/browser/native_window_views.h" #include "shell/browser/ui/views/root_view.h" #include "shell/common/electron_constants.h" #include "ui/display/display.h" #include "ui/display/win/screen_win.h" #include "ui/gfx/geometry/insets.h" #include "ui/gfx/geometry/resize_utils.h" #include "ui/views/widget/native_widget_private.h" // Must be included after other Windows headers. #include <UIAutomationClient.h> #include <UIAutomationCoreApi.h> namespace electron { namespace { // Convert Win32 WM_APPCOMMANDS to strings. const char* AppCommandToString(int command_id) { switch (command_id) { case APPCOMMAND_BROWSER_BACKWARD: return kBrowserBackward; case APPCOMMAND_BROWSER_FORWARD: return kBrowserForward; case APPCOMMAND_BROWSER_REFRESH: return "browser-refresh"; case APPCOMMAND_BROWSER_STOP: return "browser-stop"; case APPCOMMAND_BROWSER_SEARCH: return "browser-search"; case APPCOMMAND_BROWSER_FAVORITES: return "browser-favorites"; case APPCOMMAND_BROWSER_HOME: return "browser-home"; case APPCOMMAND_VOLUME_MUTE: return "volume-mute"; case APPCOMMAND_VOLUME_DOWN: return "volume-down"; case APPCOMMAND_VOLUME_UP: return "volume-up"; case APPCOMMAND_MEDIA_NEXTTRACK: return "media-nexttrack"; case APPCOMMAND_MEDIA_PREVIOUSTRACK: return "media-previoustrack"; case APPCOMMAND_MEDIA_STOP: return "media-stop"; case APPCOMMAND_MEDIA_PLAY_PAUSE: return "media-play-pause"; case APPCOMMAND_LAUNCH_MAIL: return "launch-mail"; case APPCOMMAND_LAUNCH_MEDIA_SELECT: return "launch-media-select"; case APPCOMMAND_LAUNCH_APP1: return "launch-app1"; case APPCOMMAND_LAUNCH_APP2: return "launch-app2"; case APPCOMMAND_BASS_DOWN: return "bass-down"; case APPCOMMAND_BASS_BOOST: return "bass-boost"; case APPCOMMAND_BASS_UP: return "bass-up"; case APPCOMMAND_TREBLE_DOWN: return "treble-down"; case APPCOMMAND_TREBLE_UP: return "treble-up"; case APPCOMMAND_MICROPHONE_VOLUME_MUTE: return "microphone-volume-mute"; case APPCOMMAND_MICROPHONE_VOLUME_DOWN: return "microphone-volume-down"; case APPCOMMAND_MICROPHONE_VOLUME_UP: return "microphone-volume-up"; case APPCOMMAND_HELP: return "help"; case APPCOMMAND_FIND: return "find"; case APPCOMMAND_NEW: return "new"; case APPCOMMAND_OPEN: return "open"; case APPCOMMAND_CLOSE: return "close"; case APPCOMMAND_SAVE: return "save"; case APPCOMMAND_PRINT: return "print"; case APPCOMMAND_UNDO: return "undo"; case APPCOMMAND_REDO: return "redo"; case APPCOMMAND_COPY: return "copy"; case APPCOMMAND_CUT: return "cut"; case APPCOMMAND_PASTE: return "paste"; case APPCOMMAND_REPLY_TO_MAIL: return "reply-to-mail"; case APPCOMMAND_FORWARD_MAIL: return "forward-mail"; case APPCOMMAND_SEND_MAIL: return "send-mail"; case APPCOMMAND_SPELL_CHECK: return "spell-check"; case APPCOMMAND_MIC_ON_OFF_TOGGLE: return "mic-on-off-toggle"; case APPCOMMAND_CORRECTION_LIST: return "correction-list"; case APPCOMMAND_MEDIA_PLAY: return "media-play"; case APPCOMMAND_MEDIA_PAUSE: return "media-pause"; case APPCOMMAND_MEDIA_RECORD: return "media-record"; case APPCOMMAND_MEDIA_FAST_FORWARD: return "media-fast-forward"; case APPCOMMAND_MEDIA_REWIND: return "media-rewind"; case APPCOMMAND_MEDIA_CHANNEL_UP: return "media-channel-up"; case APPCOMMAND_MEDIA_CHANNEL_DOWN: return "media-channel-down"; case APPCOMMAND_DELETE: return "delete"; case APPCOMMAND_DICTATE_OR_COMMAND_CONTROL_TOGGLE: return "dictate-or-command-control-toggle"; default: return "unknown"; } } // Copied from ui/views/win/hwnd_message_handler.cc gfx::ResizeEdge GetWindowResizeEdge(WPARAM param) { switch (param) { case WMSZ_BOTTOM: return gfx::ResizeEdge::kBottom; case WMSZ_TOP: return gfx::ResizeEdge::kTop; case WMSZ_LEFT: return gfx::ResizeEdge::kLeft; case WMSZ_RIGHT: return gfx::ResizeEdge::kRight; case WMSZ_TOPLEFT: return gfx::ResizeEdge::kTopLeft; case WMSZ_TOPRIGHT: return gfx::ResizeEdge::kTopRight; case WMSZ_BOTTOMLEFT: return gfx::ResizeEdge::kBottomLeft; case WMSZ_BOTTOMRIGHT: return gfx::ResizeEdge::kBottomRight; default: return gfx::ResizeEdge::kBottomRight; } } bool IsScreenReaderActive() { UINT screenReader = 0; SystemParametersInfo(SPI_GETSCREENREADER, 0, &screenReader, 0); return screenReader && UiaClientsAreListening(); } } // namespace std::set<NativeWindowViews*> NativeWindowViews::forwarding_windows_; HHOOK NativeWindowViews::mouse_hook_ = NULL; void NativeWindowViews::Maximize() { // Only use Maximize() when window is NOT transparent style if (!transparent()) { if (IsVisible()) { widget()->Maximize(); } else { widget()->native_widget_private()->Show(ui::SHOW_STATE_MAXIMIZED, gfx::Rect()); 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)); 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)); return true; // Tells Windows that the Move is handled. If not true, // frameless windows can be moved using // -webkit-app-region: drag elements. } return false; } case WM_ENDSESSION: { if (w_param) { NotifyWindowEndSession(); } return false; } case WM_PARENTNOTIFY: { if (LOWORD(w_param) == WM_CREATE) { // Because of reasons regarding legacy drivers and stuff, a window that // matches the client area is created and used internally by Chromium. // This is used when forwarding mouse messages. We only cache the first // occurrence (the webview window) because dev tools also cause this // message to be sent. if (!legacy_window_) { legacy_window_ = reinterpret_cast<HWND>(l_param); } } return false; } case WM_CONTEXTMENU: { bool prevent_default = false; NotifyWindowSystemContextMenu(GET_X_LPARAM(l_param), GET_Y_LPARAM(l_param), &prevent_default); return prevent_default; } case WM_SYSCOMMAND: { // Mask is needed to account for double clicking title bar to maximize WPARAM max_mask = 0xFFF0; if (transparent() && ((w_param & max_mask) == SC_MAXIMIZE)) { return true; } return false; } case WM_INITMENU: { // This is handling the scenario where the menu might get triggered by the // user doing "alt + space" resulting in system maximization and restore // being used on transparent windows when that does not work. if (transparent()) { HMENU menu = GetSystemMenu(GetAcceleratedWidget(), false); EnableMenuItem(menu, SC_MAXIMIZE, MF_BYCOMMAND | MF_DISABLED | MF_GRAYED); EnableMenuItem(menu, SC_RESTORE, MF_BYCOMMAND | MF_DISABLED | MF_GRAYED); return true; } return false; } default: { return false; } } } void NativeWindowViews::HandleSizeEvent(WPARAM w_param, LPARAM l_param) { // Here we handle the WM_SIZE event in order to figure out what is the current // window state and notify the user accordingly. switch (w_param) { case SIZE_MAXIMIZED: case SIZE_MINIMIZED: { WINDOWPLACEMENT wp; wp.length = sizeof(WINDOWPLACEMENT); if (GetWindowPlacement(GetAcceleratedWidget(), &wp)) { last_normal_placement_bounds_ = gfx::Rect(wp.rcNormalPosition); } // Note that SIZE_MAXIMIZED and SIZE_MINIMIZED might be emitted for // multiple times for one resize because of the SetWindowPlacement call. if (w_param == SIZE_MAXIMIZED && last_window_state_ != ui::SHOW_STATE_MAXIMIZED) { last_window_state_ = ui::SHOW_STATE_MAXIMIZED; NotifyWindowMaximize(); } else if (w_param == SIZE_MINIMIZED && last_window_state_ != ui::SHOW_STATE_MINIMIZED) { last_window_state_ = ui::SHOW_STATE_MINIMIZED; NotifyWindowMinimize(); } break; } case SIZE_RESTORED: switch (last_window_state_) { case ui::SHOW_STATE_MAXIMIZED: last_window_state_ = ui::SHOW_STATE_NORMAL; NotifyWindowUnmaximize(); break; case ui::SHOW_STATE_MINIMIZED: if (IsFullscreen()) { last_window_state_ = ui::SHOW_STATE_FULLSCREEN; NotifyWindowEnterFullScreen(); } else { last_window_state_ = ui::SHOW_STATE_NORMAL; NotifyWindowRestore(); } break; default: break; } break; } } void NativeWindowViews::SetForwardMouseMessages(bool forward) { if (forward && !forwarding_mouse_messages_) { forwarding_mouse_messages_ = true; forwarding_windows_.insert(this); // Subclassing is used to fix some issues when forwarding mouse messages; // see comments in |SubclassProc|. SetWindowSubclass(legacy_window_, SubclassProc, 1, reinterpret_cast<DWORD_PTR>(this)); if (!mouse_hook_) { mouse_hook_ = SetWindowsHookEx(WH_MOUSE_LL, MouseHookProc, NULL, 0); } } else if (!forward && forwarding_mouse_messages_) { forwarding_mouse_messages_ = false; forwarding_windows_.erase(this); RemoveWindowSubclass(legacy_window_, SubclassProc, 1); if (forwarding_windows_.empty()) { UnhookWindowsHookEx(mouse_hook_); mouse_hook_ = NULL; } } } LRESULT CALLBACK NativeWindowViews::SubclassProc(HWND hwnd, UINT msg, WPARAM w_param, LPARAM l_param, UINT_PTR subclass_id, DWORD_PTR ref_data) { auto* window = reinterpret_cast<NativeWindowViews*>(ref_data); switch (msg) { case WM_MOUSELEAVE: { // When input is forwarded to underlying windows, this message is posted. // If not handled, it interferes with Chromium logic, causing for example // mouseleave events to fire. If those events are used to exit forward // mode, excessive flickering on for example hover items in underlying // windows can occur due to rapidly entering and leaving forwarding mode. // By consuming and ignoring the message, we're essentially telling // Chromium that we have not left the window despite somebody else getting // the messages. As to why this is caught for the legacy window and not // the actual browser window is simply that the legacy window somehow // makes use of these events; posting to the main window didn't work. if (window->forwarding_mouse_messages_) { return 0; } break; } } return DefSubclassProc(hwnd, msg, w_param, l_param); } LRESULT CALLBACK NativeWindowViews::MouseHookProc(int n_code, WPARAM w_param, LPARAM l_param) { if (n_code < 0) { return CallNextHookEx(NULL, n_code, w_param, l_param); } // Post a WM_MOUSEMOVE message for those windows whose client area contains // the cursor since they are in a state where they would otherwise ignore all // mouse input. if (w_param == WM_MOUSEMOVE) { for (auto* window : forwarding_windows_) { // At first I considered enumerating windows to check whether the cursor // was directly above the window, but since nothing bad seems to happen // if we post the message even if some other window occludes it I have // just left it as is. RECT client_rect; GetClientRect(window->legacy_window_, &client_rect); POINT p = reinterpret_cast<MSLLHOOKSTRUCT*>(l_param)->pt; ScreenToClient(window->legacy_window_, &p); if (PtInRect(&client_rect, p)) { WPARAM w = 0; // No virtual keys pressed for our purposes LPARAM l = MAKELPARAM(p.x, p.y); PostMessage(window->legacy_window_, WM_MOUSEMOVE, w, l); } } } return CallNextHookEx(NULL, n_code, w_param, l_param); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
34,270
DCHECK on `webContents.print()`
Introduced by https://github.com/electron/electron/pull/33906. Root Cause: https://chromium-review.googlesource.com/c/chromium/src/+/3579297 <details> <summary> Stacktrace </summary> ``` [46358:0518/110313.131061:FATAL:values_mojom_traits.h(100)] Check failed: value.is_dict(). 0 Electron Framework 0x000000012ef92ba9 base::debug::CollectStackTrace(void**, unsigned long) + 9 1 Electron Framework 0x000000012eeb3ac3 base::debug::StackTrace::StackTrace() + 19 2 Electron Framework 0x000000012eecccdf logging::LogMessage::~LogMessage() + 175 3 Electron Framework 0x000000012eecdd2e logging::LogMessage::~LogMessage() + 14 4 Electron Framework 0x000000012a9ed02a mojo::internal::Serializer<mojo_base::mojom::DeprecatedDictionaryValueDataView, base::Value>::Serialize(base::Value&, mojo::internal::MessageFragment<mojo_base::mojom::internal::DeprecatedDictionaryValue_Data>&) + 90 5 Electron Framework 0x000000012e7582da printing::mojom::PrintRenderFrameProxy::PrintRequestedPages(bool, base::Value) + 362 6 Electron Framework 0x0000000133f15232 printing::PrintViewManagerBase::CompletePrintNow(content::RenderFrameHost*) + 146 7 Electron Framework 0x0000000133f14f3b printing::PrintViewManagerBase::PrintNow(content::RenderFrameHost*, bool, base::Value, base::OnceCallback<void (bool, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)>) + 395 8 Electron Framework 0x000000012a56ed16 electron::api::WebContents::OnGetDefaultPrinter(base::Value, base::OnceCallback<void (bool, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)>, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> >, bool, std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > >) + 1686 9 Electron Framework 0x000000012a580b93 void base::internal::FunctorTraits<void (electron::api::WebContents::*)(base::Value, base::OnceCallback<void (bool, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)>, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> >, bool, std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > >), void>::Invoke<void (electron::api::WebContents::*)(base::Value, base::OnceCallback<void (bool, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)>, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> >, bool, std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > >), base::WeakPtr<electron::api::WebContents>, base::Value, base::OnceCallback<void (bool, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)>, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> >, bool, std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > > >(void (electron::api::WebContents::*)(base::Value, base::OnceCallback<void (bool, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)>, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> >, bool, std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > >), base::WeakPtr<electron::api::WebContents>&&, base::Value&&, base::OnceCallback<void (bool, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)>&&, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> >&&, bool&&, std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > >&&) + 291 10 Electron Framework 0x000000012a58099d base::internal::Invoker<base::internal::BindState<void (electron::api::WebContents::*)(base::Value, base::OnceCallback<void (bool, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)>, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> >, bool, std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > >), base::WeakPtr<electron::api::WebContents>, base::Value, base::OnceCallback<void (bool, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)>, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> >, bool>, void (std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > >)>::RunOnce(base::internal::BindStateBase*, std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > >&&) + 77 11 Electron Framework 0x000000012a581102 void base::internal::ReplyAdapter<std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > >, std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > > >(base::OnceCallback<void (std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > >)>, std::__1::unique_ptr<std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > >, std::__1::default_delete<std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > > > >*) + 210 12 Electron Framework 0x000000012a4f9627 base::internal::Invoker<base::internal::BindState<void (*)(base::OnceCallback<(anonymous namespace)::CloseFileResult ()>, std::__1::unique_ptr<(anonymous namespace)::CloseFileResult, std::__1::default_delete<(anonymous namespace)::CloseFileResult> >*), base::OnceCallback<(anonymous namespace)::CloseFileResult ()>, base::internal::UnretainedWrapper<std::__1::unique_ptr<(anonymous namespace)::CloseFileResult, std::__1::default_delete<(anonymous namespace)::CloseFileResult> > > >, void ()>::RunOnce(base::internal::BindStateBase*) + 39 13 Electron Framework 0x000000012ef74403 base::(anonymous namespace)::PostTaskAndReplyRelay::RunReply(base::(anonymous namespace)::PostTaskAndReplyRelay) + 211 14 Electron Framework 0x000000012ef74499 base::internal::Invoker<base::internal::BindState<void (*)(base::(anonymous namespace)::PostTaskAndReplyRelay), base::(anonymous namespace)::PostTaskAndReplyRelay>, void ()>::RunOnce(base::internal::BindStateBase*) + 73 15 Electron Framework 0x000000012ef261f9 base::TaskAnnotator::RunTaskImpl(base::PendingTask&) + 313 16 Electron Framework 0x000000012ef4e1ca base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::DoWorkImpl(base::sequence_manager::LazyNow*) + 1066 17 Electron Framework 0x000000012ef4d88e base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::DoWork() + 126 18 Electron Framework 0x000000012ef4e9e2 non-virtual thunk to base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::DoWork() + 18 19 Electron Framework 0x000000012efa83e1 base::MessagePumpCFRunLoopBase::RunWork() + 97 20 Electron Framework 0x000000012efa78c2 base::mac::CallWithEHFrame(void () block_pointer) + 10 21 Electron Framework 0x000000012efa7e0f base::MessagePumpCFRunLoopBase::RunWorkSource(void*) + 63 22 CoreFoundation 0x00007ff80b673aeb __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17 23 CoreFoundation 0x00007ff80b673a53 __CFRunLoopDoSource0 + 180 24 CoreFoundation 0x00007ff80b6737cd __CFRunLoopDoSources0 + 242 25 CoreFoundation 0x00007ff80b6721e8 __CFRunLoopRun + 892 26 CoreFoundation 0x00007ff80b6717ac CFRunLoopRunSpecific + 562 27 HIToolbox 0x00007ff8142f8ce6 RunCurrentEventLoopInMode + 292 28 HIToolbox 0x00007ff8142f8a4a ReceiveNextEventCommon + 594 29 HIToolbox 0x00007ff8142f87e5 _BlockUntilNextEventMatchingListInModeWithFilter + 70 30 AppKit 0x00007ff80e09853d _DPSNextEvent + 927 31 AppKit 0x00007ff80e096bfa -[NSApplication(NSEvent) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] + 1394 32 AppKit 0x00007ff80e0892a9 -[NSApplication run] + 586 33 Electron Framework 0x000000012efa8e7c base::MessagePumpNSApplication::DoRun(base::MessagePump::Delegate*) + 348 34 Electron Framework 0x000000012efa796b base::MessagePumpCFRunLoopBase::Run(base::MessagePump::Delegate*) + 155 35 Electron Framework 0x000000012ef4ef97 base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::Run(bool, base::TimeDelta) + 695 36 Electron Framework 0x000000012ef01dc6 base::RunLoop::Run(base::Location const&) + 726 37 Electron Framework 0x000000012dac4c83 content::BrowserMainLoop::RunMainMessageLoop() + 243 38 Electron Framework 0x000000012dac6822 content::BrowserMainRunnerImpl::Run() + 82 39 Electron Framework 0x000000012dac1fce content::BrowserMain(content::MainFunctionParams) + 270 40 Electron Framework 0x000000012a90bd12 content::RunBrowserProcessMain(content::MainFunctionParams, content::ContentMainDelegate*) + 258 41 Electron Framework 0x000000012a90d28b content::ContentMainRunnerImpl::RunBrowser(content::MainFunctionParams, bool) + 1403 42 Electron Framework 0x000000012a90cc90 content::ContentMainRunnerImpl::Run() + 736 43 Electron Framework 0x000000012a90b637 content::RunContentProcess(content::ContentMainParams, content::ContentMainRunner*) + 2679 44 Electron Framework 0x000000012a90b752 content::ContentMain(content::ContentMainParams) + 98 45 Electron Framework 0x000000012a4b883d ElectronMain + 157 46 dyld 0x0000000114aee51e start + 462 Task trace: 0 Electron Framework 0x000000012a56f8b0 electron::api::WebContents::Print(gin::Arguments*) + 2832 1 Electron Framework 0x000000012a56f8b0 electron::api::WebContents::Print(gin::Arguments*) + 2832 2 Electron Framework 0x000000012f718430 IPC::(anonymous namespace)::ChannelAssociatedGroupController::Accept(mojo::Message*) + 784 3 Electron Framework 0x000000012f2f4f9e mojo::SimpleWatcher::Context::Notify(unsigned int, MojoHandleSignalsState, unsigned int) + 430 Crash keys: "ui_scheduler_async_stack" = "0x12A56F8B0 0x12A56F8B0" "io_scheduler_async_stack" = "0x12BEBEDDB 0x0" "platform" = "darwin" "process_type" = "browser" ``` </details>
https://github.com/electron/electron/issues/34270
https://github.com/electron/electron/pull/34271
73e0bf973d2b7835290d61cab6638309a21a2719
588005a9d5a74b953961605579cf4ad6f8dc2b20
2022-05-18T09:05:02Z
c++
2022-05-19T08:05:07Z
patches/chromium/printing.patch
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: Shelley Vohr <[email protected]> Date: Fri, 7 Jun 2019 13:59:37 -0700 Subject: printing.patch Add changeset that was previously applied to sources in chromium_src. The majority of changes originally come from these PRs: * https://github.com/electron/electron/pull/1835 * https://github.com/electron/electron/pull/8596 This patch also fixes callback for manual user cancellation and success. diff --git a/chrome/browser/printing/print_job.cc b/chrome/browser/printing/print_job.cc index 331a084371402b5a2440b5d60feac8f0189e84b9..6755d1f497cef4deea6b83df1d8720dcf54817e9 100644 --- a/chrome/browser/printing/print_job.cc +++ b/chrome/browser/printing/print_job.cc @@ -90,6 +90,7 @@ bool PrintWithReducedRasterization(PrefService* prefs) { return base::FeatureList::IsEnabled(features::kPrintWithReducedRasterization); } +#if 0 PrefService* GetPrefsForWebContents(content::WebContents* web_contents) { // TODO(thestig): Figure out why crbug.com/1083911 occurred, which is likely // because `web_contents` was null. As a result, this section has many more @@ -98,6 +99,7 @@ PrefService* GetPrefsForWebContents(content::WebContents* web_contents) { web_contents ? web_contents->GetBrowserContext() : nullptr; return context ? Profile::FromBrowserContext(context)->GetPrefs() : nullptr; } +#endif #endif // BUILDFLAG(IS_WIN) @@ -351,8 +353,10 @@ void PrintJob::StartPdfToEmfConversion( const PrintSettings& settings = document()->settings(); +#if 0 PrefService* prefs = GetPrefsForWebContents(worker_->GetWebContents()); - bool print_with_reduced_rasterization = PrintWithReducedRasterization(prefs); +#endif + bool print_with_reduced_rasterization = PrintWithReducedRasterization(nullptr); using RenderMode = PdfRenderSettings::Mode; RenderMode mode = print_with_reduced_rasterization @@ -442,8 +446,10 @@ void PrintJob::StartPdfToPostScriptConversion( if (ps_level2) { mode = PdfRenderSettings::Mode::POSTSCRIPT_LEVEL2; } else { +#if 0 PrefService* prefs = GetPrefsForWebContents(worker_->GetWebContents()); - mode = PrintWithPostScriptType42Fonts(prefs) +#endif + mode = PrintWithPostScriptType42Fonts(nullptr) ? PdfRenderSettings::Mode::POSTSCRIPT_LEVEL3_WITH_TYPE42_FONTS : PdfRenderSettings::Mode::POSTSCRIPT_LEVEL3; } diff --git a/chrome/browser/printing/print_job_worker.cc b/chrome/browser/printing/print_job_worker.cc index ee713c5686d4ea8a5d73cebf74e67381b685cff6..375ce3294727b84bf0071681c7bc35c772e4e3b9 100644 --- a/chrome/browser/printing/print_job_worker.cc +++ b/chrome/browser/printing/print_job_worker.cc @@ -20,7 +20,6 @@ #include "build/build_config.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/printing/print_job.h" -#include "chrome/grit/generated_resources.h" #include "components/crash/core/common/crash_keys.h" #include "components/device_event_log/device_event_log.h" #include "content/public/browser/browser_task_traits.h" @@ -28,6 +27,7 @@ #include "content/public/browser/global_routing_id.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/web_contents.h" +#include "chrome/grit/generated_resources.h" #include "printing/backend/print_backend.h" #include "printing/buildflags/buildflags.h" #include "printing/mojom/print.mojom.h" @@ -229,16 +229,21 @@ void PrintJobWorker::UpdatePrintSettings(base::Value::Dict new_settings, #endif // BUILDFLAG(IS_LINUX) && defined(USE_CUPS) } - mojom::ResultCode result; { #if BUILDFLAG(IS_WIN) // Blocking is needed here because Windows printer drivers are oftentimes // not thread-safe and have to be accessed on the UI thread. base::ScopedAllowBlocking allow_blocking; #endif - result = printing_context_->UpdatePrintSettings(std::move(new_settings)); + // Reset settings from previous print job + printing_context_->ResetSettings(); + mojom::ResultCode get_default_result = printing_context_->UseDefaultSettings(); + if (get_default_result == mojom::ResultCode::kSuccess) { + mojom::ResultCode update_result = + printing_context_->UpdatePrintSettings(std::move(new_settings)); + GetSettingsDone(std::move(callback), update_result); + } } - GetSettingsDone(std::move(callback), result); } #if BUILDFLAG(IS_CHROMEOS) diff --git a/chrome/browser/printing/print_job_worker_oop.cc b/chrome/browser/printing/print_job_worker_oop.cc index dd27bbf387718d6abda5080e7d2c609cd0eaff17..8837cf2aeaa2f87d51be8d00aa356c8a2c5e15c7 100644 --- a/chrome/browser/printing/print_job_worker_oop.cc +++ b/chrome/browser/printing/print_job_worker_oop.cc @@ -345,7 +345,7 @@ void PrintJobWorkerOop::OnFailure() { } void PrintJobWorkerOop::ShowErrorDialog() { - ShowPrintErrorDialog(); + // [electron]: removed. } void PrintJobWorkerOop::UnregisterServiceManagerClient() { diff --git a/chrome/browser/printing/print_view_manager_base.cc b/chrome/browser/printing/print_view_manager_base.cc index 3701853ada7f0ffe3cc8a798496f9f48541b4f47..a082dd9ee23b6d4918c194161386b973039d3ff6 100644 --- a/chrome/browser/printing/print_view_manager_base.cc +++ b/chrome/browser/printing/print_view_manager_base.cc @@ -30,10 +30,10 @@ #include "chrome/browser/printing/print_view_manager_common.h" #include "chrome/browser/printing/printer_query.h" #include "chrome/browser/profiles/profile.h" -#include "chrome/browser/ui/simple_message_box.h" -#include "chrome/browser/ui/webui/print_preview/printer_handler.h" #include "chrome/common/pref_names.h" +#if 0 #include "chrome/grit/generated_resources.h" +#endif #include "components/prefs/pref_service.h" #include "components/printing/browser/print_composite_client.h" #include "components/printing/browser/print_manager_utils.h" @@ -48,6 +48,7 @@ #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/web_contents.h" +#include "chrome/grit/generated_resources.h" #include "mojo/public/cpp/system/buffer.h" #include "printing/buildflags/buildflags.h" #include "printing/metafile_skia.h" @@ -87,6 +88,8 @@ using PrintSettingsCallback = base::OnceCallback<void(std::unique_ptr<PrinterQuery>)>; void ShowWarningMessageBox(const std::u16string& message) { + LOG(ERROR) << "Invalid printer settings " << message; +#if 0 // Runs always on the UI thread. static bool is_dialog_shown = false; if (is_dialog_shown) @@ -95,6 +98,7 @@ void ShowWarningMessageBox(const std::u16string& message) { base::AutoReset<bool> auto_reset(&is_dialog_shown, true); chrome::ShowWarningMessageBox(nullptr, std::u16string(), message); +#endif } #if BUILDFLAG(ENABLE_PRINT_PREVIEW) @@ -192,7 +196,9 @@ void UpdatePrintSettingsReplyOnIO( DCHECK_CURRENTLY_ON(content::BrowserThread::IO); DCHECK(printer_query); mojom::PrintPagesParamsPtr params = CreateEmptyPrintPagesParamsPtr(); - if (printer_query->last_status() == mojom::ResultCode::kSuccess) { + // We call update without first printing from defaults, + // so the last printer status will still be defaulted to PrintingContext::FAILED + if (printer_query) { RenderParamsFromPrintSettings(printer_query->settings(), params->params.get()); params->params->document_cookie = printer_query->cookie(); @@ -245,6 +251,7 @@ void ScriptedPrintReplyOnIO( mojom::PrintManagerHost::ScriptedPrintCallback callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); mojom::PrintPagesParamsPtr params = CreateEmptyPrintPagesParamsPtr(); + if (printer_query->last_status() == mojom::ResultCode::kSuccess && printer_query->settings().dpi()) { RenderParamsFromPrintSettings(printer_query->settings(), @@ -254,8 +261,9 @@ void ScriptedPrintReplyOnIO( } bool has_valid_cookie = params->params->document_cookie; bool has_dpi = !params->params->dpi.IsEmpty(); + bool canceled = printer_query->last_status() == mojom::ResultCode::kCanceled; content::GetUIThreadTaskRunner({})->PostTask( - FROM_HERE, base::BindOnce(std::move(callback), std::move(params))); + FROM_HERE, base::BindOnce(std::move(callback), std::move(params), canceled)); if (has_dpi && has_valid_cookie) { queue->QueuePrinterQuery(std::move(printer_query)); @@ -293,12 +301,14 @@ PrintViewManagerBase::PrintViewManagerBase(content::WebContents* web_contents) : PrintManager(web_contents), queue_(g_browser_process->print_job_manager()->queue()) { DCHECK(queue_); +#if 0 // Printing is always enabled. Profile* profile = Profile::FromBrowserContext(web_contents->GetBrowserContext()); printing_enabled_.Init( prefs::kPrintingEnabled, profile->GetPrefs(), base::BindRepeating(&PrintViewManagerBase::UpdatePrintingEnabled, weak_ptr_factory_.GetWeakPtr())); +#endif } PrintViewManagerBase::~PrintViewManagerBase() { @@ -306,7 +316,10 @@ PrintViewManagerBase::~PrintViewManagerBase() { DisconnectFromCurrentPrintJob(); } -bool PrintViewManagerBase::PrintNow(content::RenderFrameHost* rfh) { +bool PrintViewManagerBase::PrintNow(content::RenderFrameHost* rfh, + bool silent, + base::Value settings, + CompletionCallback callback) { // Remember the ID for `rfh`, to enable checking that the `RenderFrameHost` // is still valid after a possible inner message loop runs in // `DisconnectFromCurrentPrintJob()`. @@ -332,6 +345,9 @@ bool PrintViewManagerBase::PrintNow(content::RenderFrameHost* rfh) { #endif SetPrintingRFH(rfh); + callback_ = std::move(callback); + + GetPrintRenderFrame(rfh)->PrintRequestedPages(silent, std::move(settings)); #if BUILDFLAG(ENABLE_PRINT_CONTENT_ANALYSIS) enterprise_connectors::ContentAnalysisDelegate::Data scanning_data; @@ -500,7 +516,8 @@ void PrintViewManagerBase::GetDefaultPrintSettingsReply( void PrintViewManagerBase::ScriptedPrintReply( ScriptedPrintCallback callback, int process_id, - mojom::PrintPagesParamsPtr params) { + mojom::PrintPagesParamsPtr params, + bool canceled) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); #if BUILDFLAG(ENABLE_OOP_PRINTING) @@ -513,16 +530,19 @@ void PrintViewManagerBase::ScriptedPrintReply( return; } + if (canceled) + UserInitCanceled(); + set_cookie(params->params->document_cookie); - std::move(callback).Run(std::move(params)); + std::move(callback).Run(std::move(params), canceled); } void PrintViewManagerBase::UpdatePrintingEnabled() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); // The Unretained() is safe because ForEachRenderFrameHost() is synchronous. - web_contents()->GetMainFrame()->ForEachRenderFrameHost(base::BindRepeating( - &PrintViewManagerBase::SendPrintingEnabled, base::Unretained(this), - printing_enabled_.GetValue())); + web_contents()->GetMainFrame()->ForEachRenderFrameHost( + base::BindRepeating(&PrintViewManagerBase::SendPrintingEnabled, + base::Unretained(this), true)); } void PrintViewManagerBase::NavigationStopped() { @@ -638,11 +658,14 @@ void PrintViewManagerBase::DidPrintDocument( void PrintViewManagerBase::GetDefaultPrintSettings( GetDefaultPrintSettingsCallback callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); +#if 0 // Printing is always enabled. + if (!printing_enabled_.GetValue()) { GetDefaultPrintSettingsReply(std::move(callback), mojom::PrintParams::New()); return; } +#endif #if BUILDFLAG(ENABLE_OOP_PRINTING) if (printing::features::kEnableOopPrintDriversJobPrint.Get() && !service_manager_client_id_.has_value()) { @@ -672,18 +695,20 @@ void PrintViewManagerBase::UpdatePrintSettings( base::Value::Dict job_settings, UpdatePrintSettingsCallback callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); +#if 0 // Printing is always enabled. if (!printing_enabled_.GetValue()) { UpdatePrintSettingsReply(std::move(callback), CreateEmptyPrintPagesParamsPtr(), false); return; } - +#endif if (!job_settings.FindInt(kSettingPrinterType)) { UpdatePrintSettingsReply(std::move(callback), CreateEmptyPrintPagesParamsPtr(), false); return; } +#if 0 content::BrowserContext* context = web_contents() ? web_contents()->GetBrowserContext() : nullptr; PrefService* prefs = @@ -693,6 +718,7 @@ void PrintViewManagerBase::UpdatePrintSettings( if (value > 0) job_settings.Set(kSettingRasterizePdfDpi, value); } +#endif auto callback_wrapper = base::BindOnce(&PrintViewManagerBase::UpdatePrintSettingsReply, @@ -718,14 +744,14 @@ void PrintViewManagerBase::ScriptedPrint(mojom::ScriptedPrintParamsPtr params, // didn't happen for some reason. bad_message::ReceivedBadMessage( render_process_host, bad_message::PVMB_SCRIPTED_PRINT_FENCED_FRAME); - std::move(callback).Run(CreateEmptyPrintPagesParamsPtr()); + std::move(callback).Run(CreateEmptyPrintPagesParamsPtr(), false); return; } #if BUILDFLAG(ENABLE_OOP_PRINTING) if (printing::features::kEnableOopPrintDriversJobPrint.Get() && !service_manager_client_id_.has_value()) { // Renderer process has requested settings outside of the expected setup. - std::move(callback).Run(CreateEmptyPrintPagesParamsPtr()); + std::move(callback).Run(CreateEmptyPrintPagesParamsPtr(), false); return; } #endif @@ -763,7 +789,6 @@ void PrintViewManagerBase::PrintingFailed(int32_t cookie, PrintManager::PrintingFailed(cookie, reason); #if !BUILDFLAG(IS_ANDROID) // Android does not implement this function. - ShowPrintErrorDialog(); #endif ReleasePrinterQuery(); @@ -778,6 +803,11 @@ void PrintViewManagerBase::RemoveObserver(Observer& observer) { } void PrintViewManagerBase::ShowInvalidPrinterSettingsError() { + if (!callback_.is_null()) { + std::string cb_str = "Invalid printer settings"; + std::move(callback_).Run(printing_succeeded_, cb_str); + } + base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(&ShowWarningMessageBox, l10n_util::GetStringUTF16( @@ -788,10 +818,12 @@ void PrintViewManagerBase::RenderFrameHostStateChanged( content::RenderFrameHost* render_frame_host, content::RenderFrameHost::LifecycleState /*old_state*/, content::RenderFrameHost::LifecycleState new_state) { +#if 0 if (new_state == content::RenderFrameHost::LifecycleState::kActive && render_frame_host->GetProcess()->IsPdf()) { SendPrintingEnabled(printing_enabled_.GetValue(), render_frame_host); } +#endif } void PrintViewManagerBase::DidStartLoading() { @@ -851,6 +883,11 @@ void PrintViewManagerBase::OnJobDone() { ReleasePrintJob(); } +void PrintViewManagerBase::UserInitCanceled() { + printing_canceled_ = true; + ReleasePrintJob(); +} + void PrintViewManagerBase::OnFailed() { TerminatePrintJob(true); } @@ -908,7 +945,10 @@ bool PrintViewManagerBase::CreateNewPrintJob( // Disconnect the current |print_job_|. auto weak_this = weak_ptr_factory_.GetWeakPtr(); - DisconnectFromCurrentPrintJob(); + if (callback_.is_null()) { + // Disconnect the current |print_job_| only when calling window.print() + DisconnectFromCurrentPrintJob(); + } if (!weak_this) return false; @@ -987,6 +1027,13 @@ void PrintViewManagerBase::ReleasePrintJob() { UnregisterSystemPrintClient(); #endif + if (!callback_.is_null()) { + std::string cb_str = ""; + if (!printing_succeeded_) + cb_str = printing_canceled_ ? "canceled" : "failed"; + std::move(callback_).Run(printing_succeeded_, cb_str); + } + if (!print_job_) return; @@ -1036,7 +1083,7 @@ bool PrintViewManagerBase::RunInnerMessageLoop() { } bool PrintViewManagerBase::OpportunisticallyCreatePrintJob(int cookie) { - if (print_job_) + if (print_job_ && print_job_->document()) return true; if (!cookie) { @@ -1144,7 +1191,7 @@ void PrintViewManagerBase::SendPrintingEnabled(bool enabled, } void PrintViewManagerBase::CompletePrintNow(content::RenderFrameHost* rfh) { - GetPrintRenderFrame(rfh)->PrintRequestedPages(); + GetPrintRenderFrame(rfh)->PrintRequestedPages(true/*silent*/, base::Value{}/*job_settings*/); for (auto& observer : GetObservers()) observer.OnPrintNow(rfh); diff --git a/chrome/browser/printing/print_view_manager_base.h b/chrome/browser/printing/print_view_manager_base.h index 746df417a23f7760818ba265d4a7d589dec8bf34..5566e7dc2929a2542c599fed91fb1eeeb866e7bb 100644 --- a/chrome/browser/printing/print_view_manager_base.h +++ b/chrome/browser/printing/print_view_manager_base.h @@ -41,6 +41,8 @@ namespace printing { class PrintQueriesQueue; class PrinterQuery; +using CompletionCallback = base::OnceCallback<void(bool, const std::string&)>; + // Base class for managing the print commands for a WebContents. class PrintViewManagerBase : public PrintManager, public PrintJob::Observer { public: @@ -64,7 +66,10 @@ class PrintViewManagerBase : public PrintManager, public PrintJob::Observer { // Prints the current document immediately. Since the rendering is // asynchronous, the actual printing will not be completed on the return of // this function. Returns false if printing is impossible at the moment. - virtual bool PrintNow(content::RenderFrameHost* rfh); + virtual bool PrintNow(content::RenderFrameHost* rfh, + bool silent = true, + base::Value settings = {}, + CompletionCallback callback = {}); #if BUILDFLAG(ENABLE_PRINT_PREVIEW) // Prints the document in `print_data` with settings specified in @@ -113,6 +118,7 @@ class PrintViewManagerBase : public PrintManager, public PrintJob::Observer { void ShowInvalidPrinterSettingsError() override; void PrintingFailed(int32_t cookie, mojom::PrintFailureReason reason) override; + void UserInitCanceled(); // Adds and removes observers for `PrintViewManagerBase` events. The order in // which notifications are sent to observers is undefined. Observers must be @@ -241,7 +247,8 @@ class PrintViewManagerBase : public PrintManager, public PrintJob::Observer { // Runs `callback` with `params` to reply to ScriptedPrint(). void ScriptedPrintReply(ScriptedPrintCallback callback, int process_id, - mojom::PrintPagesParamsPtr params); + mojom::PrintPagesParamsPtr params, + bool canceled); // Requests the RenderView to render all the missing pages for the print job. // No-op if no print job is pending. Returns true if at least one page has @@ -314,9 +321,15 @@ class PrintViewManagerBase : public PrintManager, public PrintJob::Observer { // The current RFH that is printing with a system printing dialog. raw_ptr<content::RenderFrameHost> printing_rfh_ = nullptr; + // Respond with success of the print job. + CompletionCallback callback_; + // Indication of success of the print job. bool printing_succeeded_ = false; + // Indication of whether the print job was manually canceled + bool printing_canceled_ = false; + // Set while running an inner message loop inside RenderAllMissingPagesNow(). // This means we are _blocking_ until all the necessary pages have been // rendered or the print settings are being loaded. diff --git a/chrome/browser/ui/webui/print_preview/fake_print_render_frame.cc b/chrome/browser/ui/webui/print_preview/fake_print_render_frame.cc index aa727261738698610fab5abd3618d0d0f0d29792..8f95dae637ce25a073872ecdf229f14cc6d0614c 100644 --- a/chrome/browser/ui/webui/print_preview/fake_print_render_frame.cc +++ b/chrome/browser/ui/webui/print_preview/fake_print_render_frame.cc @@ -21,7 +21,7 @@ FakePrintRenderFrame::FakePrintRenderFrame( FakePrintRenderFrame::~FakePrintRenderFrame() = default; -void FakePrintRenderFrame::PrintRequestedPages() {} +void FakePrintRenderFrame::PrintRequestedPages(bool /*silent*/, ::base::Value /*settings*/) {} void FakePrintRenderFrame::PrintWithParams(mojom::PrintPagesParamsPtr params) { NOTREACHED(); diff --git a/chrome/browser/ui/webui/print_preview/fake_print_render_frame.h b/chrome/browser/ui/webui/print_preview/fake_print_render_frame.h index 5f4d6e314b21351e3e5912e3a43ef87774343085..2a93fe0139025d1a40b3f8e81378ee4213ac27c1 100644 --- a/chrome/browser/ui/webui/print_preview/fake_print_render_frame.h +++ b/chrome/browser/ui/webui/print_preview/fake_print_render_frame.h @@ -25,7 +25,7 @@ class FakePrintRenderFrame : public mojom::PrintRenderFrame { private: // printing::mojom::PrintRenderFrame: - void PrintRequestedPages() override; + void PrintRequestedPages(bool silent, ::base::Value settings) override; void PrintWithParams(mojom::PrintPagesParamsPtr params) override; void PrintForSystemDialog() override; void SetPrintPreviewUI( diff --git a/components/printing/browser/print_to_pdf/pdf_print_manager.cc b/components/printing/browser/print_to_pdf/pdf_print_manager.cc index 82591f8c2abbc1a180ef62f7264a68ca279e9b9c..ad27a15ba3028af1046482192dec789df5dda7b2 100644 --- a/components/printing/browser/print_to_pdf/pdf_print_manager.cc +++ b/components/printing/browser/print_to_pdf/pdf_print_manager.cc @@ -132,7 +132,8 @@ void PdfPrintManager::PrintToPdf( set_cookie(print_pages_params->params->document_cookie); callback_ = std::move(callback); - GetPrintRenderFrame(rfh)->PrintWithParams(std::move(print_pages_params)); + // TODO(electron-maintainers): do something with job_settings here? + GetPrintRenderFrame(rfh)->PrintRequestedPages(true/*silent*/, base::Value{}/*job_settings*/); } void PdfPrintManager::GetDefaultPrintSettings( @@ -147,7 +148,7 @@ void PdfPrintManager::ScriptedPrint( auto default_param = printing::mojom::PrintPagesParams::New(); default_param->params = printing::mojom::PrintParams::New(); DLOG(ERROR) << "Scripted print is not supported"; - std::move(callback).Run(std::move(default_param)); + std::move(callback).Run(std::move(default_param), true/*canceled*/); } void PdfPrintManager::ShowInvalidPrinterSettingsError() { diff --git a/components/printing/common/print.mojom b/components/printing/common/print.mojom index 8e5c441b3d0a2d35fc5c6f9d43b4a4ca167e09ca..fa53eb1c9dd4e7a6b321bdd4cda2164b95244323 100644 --- a/components/printing/common/print.mojom +++ b/components/printing/common/print.mojom @@ -280,7 +280,7 @@ enum PrintFailureReason { interface PrintRenderFrame { // Tells the RenderFrame to switch the CSS to print media type, render every // requested page, and then switch back the CSS to display media type. - PrintRequestedPages(); + PrintRequestedPages(bool silent, mojo_base.mojom.DeprecatedDictionaryValue settings); // Requests the frame to be printed with specified parameters. This is used // to programmatically produce PDF by request from the browser (e.g. over @@ -362,7 +362,7 @@ interface PrintManagerHost { // Request the print settings from the user. This step is about showing // UI to the user to select the final print settings. [Sync] - ScriptedPrint(ScriptedPrintParams params) => (PrintPagesParams settings); + ScriptedPrint(ScriptedPrintParams params) => (PrintPagesParams settings, bool canceled); // Tells the browser that there are invalid printer settings. ShowInvalidPrinterSettingsError(); diff --git a/components/printing/renderer/print_render_frame_helper.cc b/components/printing/renderer/print_render_frame_helper.cc index db8913ae41d46d14fd15c6127e126e4b129dc4b8..64ee08e9091e4d67ff55097bc22177d9567214a1 100644 --- a/components/printing/renderer/print_render_frame_helper.cc +++ b/components/printing/renderer/print_render_frame_helper.cc @@ -42,6 +42,7 @@ #include "printing/mojom/print.mojom.h" #include "printing/page_number.h" #include "printing/print_job_constants.h" +#include "printing/print_settings.h" #include "printing/units.h" #include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h" #include "third_party/blink/public/common/associated_interfaces/associated_interface_registry.h" @@ -1277,7 +1278,8 @@ void PrintRenderFrameHelper::ScriptedPrint(bool user_initiated) { if (!weak_this) return; - Print(web_frame, blink::WebNode(), PrintRequestType::kScripted); + Print(web_frame, blink::WebNode(), PrintRequestType::kScripted, + false /* silent */, base::DictionaryValue() /* new_settings */); if (!weak_this) return; @@ -1308,7 +1310,7 @@ void PrintRenderFrameHelper::BindPrintRenderFrameReceiver( receivers_.Add(this, std::move(receiver)); } -void PrintRenderFrameHelper::PrintRequestedPages() { +void PrintRenderFrameHelper::PrintRequestedPages(bool silent, base::Value settings) { ScopedIPC scoped_ipc(weak_ptr_factory_.GetWeakPtr()); if (ipc_nesting_level_ > kAllowedIpcDepthForPrint) return; @@ -1323,7 +1325,7 @@ void PrintRenderFrameHelper::PrintRequestedPages() { // plugin node and print that instead. auto plugin = delegate_->GetPdfElement(frame); - Print(frame, plugin, PrintRequestType::kRegular); + Print(frame, plugin, PrintRequestType::kRegular, silent, std::move(settings)); if (!render_frame_gone_) frame->DispatchAfterPrintEvent(); @@ -1389,7 +1391,8 @@ void PrintRenderFrameHelper::PrintForSystemDialog() { } Print(frame, print_preview_context_.source_node(), - PrintRequestType::kRegular); + PrintRequestType::kRegular, false, + base::DictionaryValue()); if (!render_frame_gone_) print_preview_context_.DispatchAfterPrintEvent(); // WARNING: |this| may be gone at this point. Do not do any more work here and @@ -1438,6 +1441,8 @@ void PrintRenderFrameHelper::PrintPreview(base::Value settings) { if (ipc_nesting_level_ > kAllowedIpcDepthForPrint) return; + blink::WebLocalFrame* frame = render_frame()->GetWebFrame(); + print_preview_context_.InitWithFrame(frame); print_preview_context_.OnPrintPreview(); #if BUILDFLAG(IS_CHROMEOS_ASH) @@ -2051,7 +2056,8 @@ void PrintRenderFrameHelper::PrintNode(const blink::WebNode& node) { return; Print(duplicate_node.GetDocument().GetFrame(), duplicate_node, - PrintRequestType::kRegular); + PrintRequestType::kRegular, false /* silent */, + base::DictionaryValue() /* new_settings */); // Check if |this| is still valid. if (!weak_this) return; @@ -2066,7 +2072,9 @@ void PrintRenderFrameHelper::PrintNode(const blink::WebNode& node) { void PrintRenderFrameHelper::Print(blink::WebLocalFrame* frame, const blink::WebNode& node, - PrintRequestType print_request_type) { + PrintRequestType print_request_type, + bool silent, + base::Value settings) { // If still not finished with earlier print request simply ignore. if (prep_frame_view_) return; @@ -2074,7 +2082,7 @@ void PrintRenderFrameHelper::Print(blink::WebLocalFrame* frame, FrameReference frame_ref(frame); uint32_t expected_page_count = 0; - if (!CalculateNumberOfPages(frame, node, &expected_page_count)) { + if (!CalculateNumberOfPages(frame, node, &expected_page_count, base::Value::AsDictionaryValue(settings))) { DidFinishPrinting(FAIL_PRINT_INIT); return; // Failed to init print page settings. } @@ -2093,8 +2101,15 @@ void PrintRenderFrameHelper::Print(blink::WebLocalFrame* frame, print_pages_params_->params->print_scaling_option; auto self = weak_ptr_factory_.GetWeakPtr(); - mojom::PrintPagesParamsPtr print_settings = GetPrintSettingsFromUser( + mojom::PrintPagesParamsPtr print_settings; + + if (silent) { + print_settings = mojom::PrintPagesParams::New(); + print_settings->params = print_pages_params_->params->Clone(); + } else { + print_settings = GetPrintSettingsFromUser( frame_ref.GetFrame(), node, expected_page_count, print_request_type); + } // Check if |this| is still valid. if (!self) return; @@ -2327,36 +2342,52 @@ void PrintRenderFrameHelper::IPCProcessed() { } } -bool PrintRenderFrameHelper::InitPrintSettings(bool fit_to_paper_size) { - mojom::PrintPagesParams settings; - settings.params = mojom::PrintParams::New(); - GetPrintManagerHost()->GetDefaultPrintSettings(&settings.params); +bool PrintRenderFrameHelper::InitPrintSettings( + bool fit_to_paper_size, + const base::DictionaryValue& new_settings) { + mojom::PrintPagesParamsPtr settings; + + if (new_settings.DictEmpty()) { + settings = mojom::PrintPagesParams::New(); + settings->params = mojom::PrintParams::New(); + GetPrintManagerHost()->GetDefaultPrintSettings(&settings->params); + } else { + bool canceled = false; + int cookie = + print_pages_params_ ? print_pages_params_->params->document_cookie : 0; + GetPrintManagerHost()->UpdatePrintSettings( + cookie, new_settings.GetDict().Clone(), &settings, &canceled); + if (canceled) + return false; + } // Check if the printer returned any settings, if the settings is empty, we // can safely assume there are no printer drivers configured. So we safely // terminate. bool result = true; - if (!PrintMsg_Print_Params_IsValid(*settings.params)) + if (!PrintMsg_Print_Params_IsValid(*settings->params)) result = false; // Reset to default values. ignore_css_margins_ = false; - settings.pages.clear(); + settings->pages.clear(); - settings.params->print_scaling_option = + settings->params->print_scaling_option = fit_to_paper_size ? mojom::PrintScalingOption::kFitToPrintableArea : mojom::PrintScalingOption::kSourceSize; - SetPrintPagesParams(settings); + SetPrintPagesParams(*settings); return result; } -bool PrintRenderFrameHelper::CalculateNumberOfPages(blink::WebLocalFrame* frame, - const blink::WebNode& node, - uint32_t* number_of_pages) { +bool PrintRenderFrameHelper::CalculateNumberOfPages( + blink::WebLocalFrame* frame, + const blink::WebNode& node, + uint32_t* number_of_pages, + const base::DictionaryValue& settings) { DCHECK(frame); bool fit_to_paper_size = !IsPrintingPdfFrame(frame, node); - if (!InitPrintSettings(fit_to_paper_size)) { + if (!InitPrintSettings(fit_to_paper_size, settings)) { notify_browser_of_print_failure_ = false; GetPrintManagerHost()->ShowInvalidPrinterSettingsError(); return false; @@ -2481,7 +2512,7 @@ mojom::PrintPagesParamsPtr PrintRenderFrameHelper::GetPrintSettingsFromUser( std::move(params), base::BindOnce( [](base::OnceClosure quit_closure, mojom::PrintPagesParamsPtr* output, - mojom::PrintPagesParamsPtr input) { + mojom::PrintPagesParamsPtr input, bool canceled) { *output = std::move(input); std::move(quit_closure).Run(); }, @@ -2725,18 +2756,7 @@ void PrintRenderFrameHelper::RequestPrintPreview(PrintPreviewRequestType type, } bool PrintRenderFrameHelper::CheckForCancel() { - const mojom::PrintParams& print_params = *print_pages_params_->params; - bool cancel = false; - - if (!GetPrintManagerHost()->CheckForCancel(print_params.preview_ui_id, - print_params.preview_request_id, - &cancel)) { - cancel = true; - } - - if (cancel) - notify_browser_of_print_failure_ = false; - return cancel; + return false; } bool PrintRenderFrameHelper::PreviewPageRendered( diff --git a/components/printing/renderer/print_render_frame_helper.h b/components/printing/renderer/print_render_frame_helper.h index 220b28a7e63625fe8b76290f0d2f40dd32cae255..72801431a5d19f31c1a7db785b0cbaee8e65cca3 100644 --- a/components/printing/renderer/print_render_frame_helper.h +++ b/components/printing/renderer/print_render_frame_helper.h @@ -255,7 +255,7 @@ class PrintRenderFrameHelper mojo::PendingAssociatedReceiver<mojom::PrintRenderFrame> receiver); // printing::mojom::PrintRenderFrame: - void PrintRequestedPages() override; + void PrintRequestedPages(bool silent, base::Value settings) override; void PrintWithParams(mojom::PrintPagesParamsPtr params) override; #if BUILDFLAG(ENABLE_PRINT_PREVIEW) void PrintForSystemDialog() override; @@ -327,7 +327,9 @@ class PrintRenderFrameHelper // WARNING: |this| may be gone after this method returns. void Print(blink::WebLocalFrame* frame, const blink::WebNode& node, - PrintRequestType print_request_type); + PrintRequestType print_request_type, + bool silent, + base::Value settings); // Notification when printing is done - signal tear-down/free resources. void DidFinishPrinting(PrintingResult result); @@ -336,12 +338,14 @@ class PrintRenderFrameHelper // Initialize print page settings with default settings. // Used only for native printing workflow. - bool InitPrintSettings(bool fit_to_paper_size); + bool InitPrintSettings(bool fit_to_paper_size, + const base::DictionaryValue& settings); // Calculate number of pages in source document. bool CalculateNumberOfPages(blink::WebLocalFrame* frame, const blink::WebNode& node, - uint32_t* number_of_pages); + uint32_t* number_of_pages, + const base::DictionaryValue& settings); #if BUILDFLAG(ENABLE_PRINT_PREVIEW) // Set options for print preset from source PDF document. diff --git a/printing/printing_context.cc b/printing/printing_context.cc index 8a8fcefa9da92a044f5bdf6a2f242048b325d442..6dae33514675d6843736b2c9a767a4b72cb103fa 100644 --- a/printing/printing_context.cc +++ b/printing/printing_context.cc @@ -117,7 +117,6 @@ mojom::ResultCode PrintingContext::UsePdfSettings() { mojom::ResultCode PrintingContext::UpdatePrintSettings( base::Value::Dict job_settings) { - ResetSettings(); { std::unique_ptr<PrintSettings> settings = PrintSettingsFromJobSettings(job_settings); diff --git a/printing/printing_context.h b/printing/printing_context.h index 2c8ef23f7cb75a743fa18e3c613f7c719988028c..265005d6d51f861aa7ccd7e0eba7809b3c652dae 100644 --- a/printing/printing_context.h +++ b/printing/printing_context.h @@ -170,6 +170,9 @@ class COMPONENT_EXPORT(PRINTING) PrintingContext { bool PrintingAborted() const { return abort_printing_; } + // Reinitializes the settings for object reuse. + void ResetSettings(); + int job_id() const { return job_id_; } protected: @@ -180,9 +183,6 @@ class COMPONENT_EXPORT(PRINTING) PrintingContext { static std::unique_ptr<PrintingContext> CreateImpl(Delegate* delegate, bool skip_system_calls); - // Reinitializes the settings for object reuse. - void ResetSettings(); - // Determine if system calls should be skipped by this instance. bool skip_system_calls() const { #if BUILDFLAG(ENABLE_OOP_PRINTING)
closed
electron/electron
https://github.com/electron/electron
34,270
DCHECK on `webContents.print()`
Introduced by https://github.com/electron/electron/pull/33906. Root Cause: https://chromium-review.googlesource.com/c/chromium/src/+/3579297 <details> <summary> Stacktrace </summary> ``` [46358:0518/110313.131061:FATAL:values_mojom_traits.h(100)] Check failed: value.is_dict(). 0 Electron Framework 0x000000012ef92ba9 base::debug::CollectStackTrace(void**, unsigned long) + 9 1 Electron Framework 0x000000012eeb3ac3 base::debug::StackTrace::StackTrace() + 19 2 Electron Framework 0x000000012eecccdf logging::LogMessage::~LogMessage() + 175 3 Electron Framework 0x000000012eecdd2e logging::LogMessage::~LogMessage() + 14 4 Electron Framework 0x000000012a9ed02a mojo::internal::Serializer<mojo_base::mojom::DeprecatedDictionaryValueDataView, base::Value>::Serialize(base::Value&, mojo::internal::MessageFragment<mojo_base::mojom::internal::DeprecatedDictionaryValue_Data>&) + 90 5 Electron Framework 0x000000012e7582da printing::mojom::PrintRenderFrameProxy::PrintRequestedPages(bool, base::Value) + 362 6 Electron Framework 0x0000000133f15232 printing::PrintViewManagerBase::CompletePrintNow(content::RenderFrameHost*) + 146 7 Electron Framework 0x0000000133f14f3b printing::PrintViewManagerBase::PrintNow(content::RenderFrameHost*, bool, base::Value, base::OnceCallback<void (bool, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)>) + 395 8 Electron Framework 0x000000012a56ed16 electron::api::WebContents::OnGetDefaultPrinter(base::Value, base::OnceCallback<void (bool, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)>, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> >, bool, std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > >) + 1686 9 Electron Framework 0x000000012a580b93 void base::internal::FunctorTraits<void (electron::api::WebContents::*)(base::Value, base::OnceCallback<void (bool, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)>, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> >, bool, std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > >), void>::Invoke<void (electron::api::WebContents::*)(base::Value, base::OnceCallback<void (bool, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)>, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> >, bool, std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > >), base::WeakPtr<electron::api::WebContents>, base::Value, base::OnceCallback<void (bool, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)>, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> >, bool, std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > > >(void (electron::api::WebContents::*)(base::Value, base::OnceCallback<void (bool, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)>, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> >, bool, std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > >), base::WeakPtr<electron::api::WebContents>&&, base::Value&&, base::OnceCallback<void (bool, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)>&&, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> >&&, bool&&, std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > >&&) + 291 10 Electron Framework 0x000000012a58099d base::internal::Invoker<base::internal::BindState<void (electron::api::WebContents::*)(base::Value, base::OnceCallback<void (bool, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)>, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> >, bool, std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > >), base::WeakPtr<electron::api::WebContents>, base::Value, base::OnceCallback<void (bool, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)>, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> >, bool>, void (std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > >)>::RunOnce(base::internal::BindStateBase*, std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > >&&) + 77 11 Electron Framework 0x000000012a581102 void base::internal::ReplyAdapter<std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > >, std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > > >(base::OnceCallback<void (std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > >)>, std::__1::unique_ptr<std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > >, std::__1::default_delete<std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > > > >*) + 210 12 Electron Framework 0x000000012a4f9627 base::internal::Invoker<base::internal::BindState<void (*)(base::OnceCallback<(anonymous namespace)::CloseFileResult ()>, std::__1::unique_ptr<(anonymous namespace)::CloseFileResult, std::__1::default_delete<(anonymous namespace)::CloseFileResult> >*), base::OnceCallback<(anonymous namespace)::CloseFileResult ()>, base::internal::UnretainedWrapper<std::__1::unique_ptr<(anonymous namespace)::CloseFileResult, std::__1::default_delete<(anonymous namespace)::CloseFileResult> > > >, void ()>::RunOnce(base::internal::BindStateBase*) + 39 13 Electron Framework 0x000000012ef74403 base::(anonymous namespace)::PostTaskAndReplyRelay::RunReply(base::(anonymous namespace)::PostTaskAndReplyRelay) + 211 14 Electron Framework 0x000000012ef74499 base::internal::Invoker<base::internal::BindState<void (*)(base::(anonymous namespace)::PostTaskAndReplyRelay), base::(anonymous namespace)::PostTaskAndReplyRelay>, void ()>::RunOnce(base::internal::BindStateBase*) + 73 15 Electron Framework 0x000000012ef261f9 base::TaskAnnotator::RunTaskImpl(base::PendingTask&) + 313 16 Electron Framework 0x000000012ef4e1ca base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::DoWorkImpl(base::sequence_manager::LazyNow*) + 1066 17 Electron Framework 0x000000012ef4d88e base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::DoWork() + 126 18 Electron Framework 0x000000012ef4e9e2 non-virtual thunk to base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::DoWork() + 18 19 Electron Framework 0x000000012efa83e1 base::MessagePumpCFRunLoopBase::RunWork() + 97 20 Electron Framework 0x000000012efa78c2 base::mac::CallWithEHFrame(void () block_pointer) + 10 21 Electron Framework 0x000000012efa7e0f base::MessagePumpCFRunLoopBase::RunWorkSource(void*) + 63 22 CoreFoundation 0x00007ff80b673aeb __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17 23 CoreFoundation 0x00007ff80b673a53 __CFRunLoopDoSource0 + 180 24 CoreFoundation 0x00007ff80b6737cd __CFRunLoopDoSources0 + 242 25 CoreFoundation 0x00007ff80b6721e8 __CFRunLoopRun + 892 26 CoreFoundation 0x00007ff80b6717ac CFRunLoopRunSpecific + 562 27 HIToolbox 0x00007ff8142f8ce6 RunCurrentEventLoopInMode + 292 28 HIToolbox 0x00007ff8142f8a4a ReceiveNextEventCommon + 594 29 HIToolbox 0x00007ff8142f87e5 _BlockUntilNextEventMatchingListInModeWithFilter + 70 30 AppKit 0x00007ff80e09853d _DPSNextEvent + 927 31 AppKit 0x00007ff80e096bfa -[NSApplication(NSEvent) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] + 1394 32 AppKit 0x00007ff80e0892a9 -[NSApplication run] + 586 33 Electron Framework 0x000000012efa8e7c base::MessagePumpNSApplication::DoRun(base::MessagePump::Delegate*) + 348 34 Electron Framework 0x000000012efa796b base::MessagePumpCFRunLoopBase::Run(base::MessagePump::Delegate*) + 155 35 Electron Framework 0x000000012ef4ef97 base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::Run(bool, base::TimeDelta) + 695 36 Electron Framework 0x000000012ef01dc6 base::RunLoop::Run(base::Location const&) + 726 37 Electron Framework 0x000000012dac4c83 content::BrowserMainLoop::RunMainMessageLoop() + 243 38 Electron Framework 0x000000012dac6822 content::BrowserMainRunnerImpl::Run() + 82 39 Electron Framework 0x000000012dac1fce content::BrowserMain(content::MainFunctionParams) + 270 40 Electron Framework 0x000000012a90bd12 content::RunBrowserProcessMain(content::MainFunctionParams, content::ContentMainDelegate*) + 258 41 Electron Framework 0x000000012a90d28b content::ContentMainRunnerImpl::RunBrowser(content::MainFunctionParams, bool) + 1403 42 Electron Framework 0x000000012a90cc90 content::ContentMainRunnerImpl::Run() + 736 43 Electron Framework 0x000000012a90b637 content::RunContentProcess(content::ContentMainParams, content::ContentMainRunner*) + 2679 44 Electron Framework 0x000000012a90b752 content::ContentMain(content::ContentMainParams) + 98 45 Electron Framework 0x000000012a4b883d ElectronMain + 157 46 dyld 0x0000000114aee51e start + 462 Task trace: 0 Electron Framework 0x000000012a56f8b0 electron::api::WebContents::Print(gin::Arguments*) + 2832 1 Electron Framework 0x000000012a56f8b0 electron::api::WebContents::Print(gin::Arguments*) + 2832 2 Electron Framework 0x000000012f718430 IPC::(anonymous namespace)::ChannelAssociatedGroupController::Accept(mojo::Message*) + 784 3 Electron Framework 0x000000012f2f4f9e mojo::SimpleWatcher::Context::Notify(unsigned int, MojoHandleSignalsState, unsigned int) + 430 Crash keys: "ui_scheduler_async_stack" = "0x12A56F8B0 0x12A56F8B0" "io_scheduler_async_stack" = "0x12BEBEDDB 0x0" "platform" = "darwin" "process_type" = "browser" ``` </details>
https://github.com/electron/electron/issues/34270
https://github.com/electron/electron/pull/34271
73e0bf973d2b7835290d61cab6638309a21a2719
588005a9d5a74b953961605579cf4ad6f8dc2b20
2022-05-18T09:05:02Z
c++
2022-05-19T08:05:07Z
shell/browser/api/electron_api_web_contents.cc
// Copyright (c) 2014 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/api/electron_api_web_contents.h" #include <limits> #include <memory> #include <set> #include <string> #include <unordered_set> #include <utility> #include <vector> #include "base/containers/id_map.h" #include "base/files/file_util.h" #include "base/json/json_reader.h" #include "base/no_destructor.h" #include "base/strings/utf_string_conversions.h" #include "base/task/current_thread.h" #include "base/task/thread_pool.h" #include "base/threading/scoped_blocking_call.h" #include "base/threading/sequenced_task_runner_handle.h" #include "base/threading/thread_restrictions.h" #include "base/threading/thread_task_runner_handle.h" #include "base/values.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/ui/exclusive_access/exclusive_access_manager.h" #include "chrome/browser/ui/views/eye_dropper/eye_dropper.h" #include "chrome/common/pref_names.h" #include "components/prefs/pref_service.h" #include "components/prefs/scoped_user_pref_update.h" #include "components/security_state/content/content_utils.h" #include "components/security_state/core/security_state.h" #include "content/browser/renderer_host/frame_tree_node.h" // nogncheck #include "content/browser/renderer_host/render_frame_host_manager.h" // nogncheck #include "content/browser/renderer_host/render_widget_host_impl.h" // nogncheck #include "content/browser/renderer_host/render_widget_host_view_base.h" // nogncheck #include "content/public/browser/child_process_security_policy.h" #include "content/public/browser/context_menu_params.h" #include "content/public/browser/desktop_media_id.h" #include "content/public/browser/desktop_streams_registry.h" #include "content/public/browser/download_request_utils.h" #include "content/public/browser/favicon_status.h" #include "content/public/browser/file_select_listener.h" #include "content/public/browser/native_web_keyboard_event.h" #include "content/public/browser/navigation_details.h" #include "content/public/browser/navigation_entry.h" #include "content/public/browser/navigation_handle.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/render_widget_host.h" #include "content/public/browser/render_widget_host_view.h" #include "content/public/browser/service_worker_context.h" #include "content/public/browser/site_instance.h" #include "content/public/browser/storage_partition.h" #include "content/public/browser/web_contents.h" #include "content/public/common/referrer_type_converters.h" #include "content/public/common/webplugininfo.h" #include "electron/buildflags/buildflags.h" #include "electron/shell/common/api/api.mojom.h" #include "gin/arguments.h" #include "gin/data_object_builder.h" #include "gin/handle.h" #include "gin/object_template_builder.h" #include "gin/wrappable.h" #include "mojo/public/cpp/bindings/associated_remote.h" #include "mojo/public/cpp/bindings/pending_receiver.h" #include "mojo/public/cpp/bindings/remote.h" #include "mojo/public/cpp/system/platform_handle.h" #include "ppapi/buildflags/buildflags.h" #include "printing/buildflags/buildflags.h" #include "printing/print_job_constants.h" #include "services/resource_coordinator/public/cpp/memory_instrumentation/memory_instrumentation.h" #include "services/service_manager/public/cpp/interface_provider.h" #include "shell/browser/api/electron_api_browser_window.h" #include "shell/browser/api/electron_api_debugger.h" #include "shell/browser/api/electron_api_session.h" #include "shell/browser/api/electron_api_web_frame_main.h" #include "shell/browser/api/message_port.h" #include "shell/browser/browser.h" #include "shell/browser/child_web_contents_tracker.h" #include "shell/browser/electron_autofill_driver_factory.h" #include "shell/browser/electron_browser_client.h" #include "shell/browser/electron_browser_context.h" #include "shell/browser/electron_browser_main_parts.h" #include "shell/browser/electron_javascript_dialog_manager.h" #include "shell/browser/electron_navigation_throttle.h" #include "shell/browser/file_select_helper.h" #include "shell/browser/native_window.h" #include "shell/browser/session_preferences.h" #include "shell/browser/ui/drag_util.h" #include "shell/browser/ui/file_dialog.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/ui/inspectable_web_contents_view.h" #include "shell/browser/web_contents_permission_helper.h" #include "shell/browser/web_contents_preferences.h" #include "shell/browser/web_contents_zoom_controller.h" #include "shell/browser/web_view_guest_delegate.h" #include "shell/browser/web_view_manager.h" #include "shell/common/api/electron_api_native_image.h" #include "shell/common/api/electron_bindings.h" #include "shell/common/color_util.h" #include "shell/common/electron_constants.h" #include "shell/common/gin_converters/base_converter.h" #include "shell/common/gin_converters/blink_converter.h" #include "shell/common/gin_converters/callback_converter.h" #include "shell/common/gin_converters/content_converter.h" #include "shell/common/gin_converters/file_path_converter.h" #include "shell/common/gin_converters/frame_converter.h" #include "shell/common/gin_converters/gfx_converter.h" #include "shell/common/gin_converters/gurl_converter.h" #include "shell/common/gin_converters/image_converter.h" #include "shell/common/gin_converters/net_converter.h" #include "shell/common/gin_converters/value_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/gin_helper/object_template_builder.h" #include "shell/common/language_util.h" #include "shell/common/mouse_util.h" #include "shell/common/node_includes.h" #include "shell/common/options_switches.h" #include "shell/common/process_util.h" #include "shell/common/v8_value_serializer.h" #include "storage/browser/file_system/isolated_context.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h" #include "third_party/blink/public/common/input/web_input_event.h" #include "third_party/blink/public/common/messaging/transferable_message_mojom_traits.h" #include "third_party/blink/public/common/page/page_zoom.h" #include "third_party/blink/public/mojom/frame/find_in_page.mojom.h" #include "third_party/blink/public/mojom/frame/fullscreen.mojom.h" #include "third_party/blink/public/mojom/messaging/transferable_message.mojom.h" #include "third_party/blink/public/mojom/renderer_preferences.mojom.h" #include "ui/base/cursor/cursor.h" #include "ui/base/cursor/mojom/cursor_type.mojom-shared.h" #include "ui/display/screen.h" #include "ui/events/base_event_utils.h" #if BUILDFLAG(ENABLE_OSR) #include "shell/browser/osr/osr_render_widget_host_view.h" #include "shell/browser/osr/osr_web_contents_view.h" #endif #if !BUILDFLAG(IS_MAC) #include "ui/aura/window.h" #else #include "ui/base/cocoa/defaults_utils.h" #endif #if BUILDFLAG(IS_LINUX) #include "ui/views/linux_ui/linux_ui.h" #endif #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_WIN) #include "ui/gfx/font_render_params.h" #endif #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #include "extensions/browser/script_executor.h" #include "extensions/browser/view_type_utils.h" #include "extensions/common/mojom/view_type.mojom.h" #include "shell/browser/extensions/electron_extension_web_contents_observer.h" #endif #if BUILDFLAG(ENABLE_PRINTING) #include "components/printing/browser/print_manager_utils.h" #include "printing/backend/print_backend.h" // nogncheck #include "printing/mojom/print.mojom.h" // nogncheck #include "shell/browser/printing/print_preview_message_handler.h" #include "shell/browser/printing/print_view_manager_electron.h" #if BUILDFLAG(IS_WIN) #include "printing/backend/win_helper.h" #endif #endif #if BUILDFLAG(ENABLE_PICTURE_IN_PICTURE) #include "chrome/browser/picture_in_picture/picture_in_picture_window_manager.h" #endif #if BUILDFLAG(ENABLE_PDF_VIEWER) #include "components/pdf/browser/pdf_web_contents_helper.h" // nogncheck #include "shell/browser/electron_pdf_web_contents_helper_client.h" #endif #if BUILDFLAG(ENABLE_PLUGINS) #include "content/public/browser/plugin_service.h" #endif #ifndef MAS_BUILD #include "chrome/browser/hang_monitor/hang_crash_dump.h" // nogncheck #endif namespace gin { #if BUILDFLAG(ENABLE_PRINTING) template <> struct Converter<printing::mojom::MarginType> { static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, printing::mojom::MarginType* out) { std::string type; if (ConvertFromV8(isolate, val, &type)) { if (type == "default") { *out = printing::mojom::MarginType::kDefaultMargins; return true; } if (type == "none") { *out = printing::mojom::MarginType::kNoMargins; return true; } if (type == "printableArea") { *out = printing::mojom::MarginType::kPrintableAreaMargins; return true; } if (type == "custom") { *out = printing::mojom::MarginType::kCustomMargins; return true; } } return false; } }; template <> struct Converter<printing::mojom::DuplexMode> { static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, printing::mojom::DuplexMode* out) { std::string mode; if (ConvertFromV8(isolate, val, &mode)) { if (mode == "simplex") { *out = printing::mojom::DuplexMode::kSimplex; return true; } if (mode == "longEdge") { *out = printing::mojom::DuplexMode::kLongEdge; return true; } if (mode == "shortEdge") { *out = printing::mojom::DuplexMode::kShortEdge; return true; } } return false; } }; #endif template <> struct Converter<WindowOpenDisposition> { static v8::Local<v8::Value> ToV8(v8::Isolate* isolate, WindowOpenDisposition val) { std::string disposition = "other"; switch (val) { case WindowOpenDisposition::CURRENT_TAB: disposition = "default"; break; case WindowOpenDisposition::NEW_FOREGROUND_TAB: disposition = "foreground-tab"; break; case WindowOpenDisposition::NEW_BACKGROUND_TAB: disposition = "background-tab"; break; case WindowOpenDisposition::NEW_POPUP: case WindowOpenDisposition::NEW_WINDOW: disposition = "new-window"; break; case WindowOpenDisposition::SAVE_TO_DISK: disposition = "save-to-disk"; break; default: break; } return gin::ConvertToV8(isolate, disposition); } }; template <> struct Converter<content::SavePageType> { static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, content::SavePageType* out) { std::string save_type; if (!ConvertFromV8(isolate, val, &save_type)) return false; save_type = base::ToLowerASCII(save_type); if (save_type == "htmlonly") { *out = content::SAVE_PAGE_TYPE_AS_ONLY_HTML; } else if (save_type == "htmlcomplete") { *out = content::SAVE_PAGE_TYPE_AS_COMPLETE_HTML; } else if (save_type == "mhtml") { *out = content::SAVE_PAGE_TYPE_AS_MHTML; } else { return false; } return true; } }; template <> struct Converter<electron::api::WebContents::Type> { static v8::Local<v8::Value> ToV8(v8::Isolate* isolate, electron::api::WebContents::Type val) { using Type = electron::api::WebContents::Type; std::string type; switch (val) { case Type::kBackgroundPage: type = "backgroundPage"; break; case Type::kBrowserWindow: type = "window"; break; case Type::kBrowserView: type = "browserView"; break; case Type::kRemote: type = "remote"; break; case Type::kWebView: type = "webview"; break; case Type::kOffScreen: type = "offscreen"; break; default: break; } return gin::ConvertToV8(isolate, type); } static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, electron::api::WebContents::Type* out) { using Type = electron::api::WebContents::Type; std::string type; if (!ConvertFromV8(isolate, val, &type)) return false; if (type == "backgroundPage") { *out = Type::kBackgroundPage; } else if (type == "browserView") { *out = Type::kBrowserView; } else if (type == "webview") { *out = Type::kWebView; #if BUILDFLAG(ENABLE_OSR) } else if (type == "offscreen") { *out = Type::kOffScreen; #endif } else { return false; } return true; } }; template <> struct Converter<scoped_refptr<content::DevToolsAgentHost>> { static v8::Local<v8::Value> ToV8( v8::Isolate* isolate, const scoped_refptr<content::DevToolsAgentHost>& val) { gin_helper::Dictionary dict(isolate, v8::Object::New(isolate)); dict.Set("id", val->GetId()); dict.Set("url", val->GetURL().spec()); return dict.GetHandle(); } }; } // namespace gin namespace electron { namespace api { namespace { base::IDMap<WebContents*>& GetAllWebContents() { static base::NoDestructor<base::IDMap<WebContents*>> s_all_web_contents; return *s_all_web_contents; } // Called when CapturePage is done. void OnCapturePageDone(gin_helper::Promise<gfx::Image> promise, const SkBitmap& bitmap) { // Hack to enable transparency in captured image promise.Resolve(gfx::Image::CreateFrom1xBitmap(bitmap)); } absl::optional<base::TimeDelta> GetCursorBlinkInterval() { #if BUILDFLAG(IS_MAC) absl::optional<base::TimeDelta> system_value( ui::TextInsertionCaretBlinkPeriodFromDefaults()); if (system_value) return *system_value; #elif BUILDFLAG(IS_LINUX) if (auto* linux_ui = views::LinuxUI::instance()) return linux_ui->GetCursorBlinkInterval(); #elif BUILDFLAG(IS_WIN) const auto system_msec = ::GetCaretBlinkTime(); if (system_msec != 0) { return (system_msec == INFINITE) ? base::TimeDelta() : base::Milliseconds(system_msec); } #endif return absl::nullopt; } #if BUILDFLAG(ENABLE_PRINTING) // This will return false if no printer with the provided device_name can be // found on the network. We need to check this because Chromium does not do // sanity checking of device_name validity and so will crash on invalid names. bool IsDeviceNameValid(const std::u16string& device_name) { #if BUILDFLAG(IS_MAC) base::ScopedCFTypeRef<CFStringRef> new_printer_id( base::SysUTF16ToCFStringRef(device_name)); PMPrinter new_printer = PMPrinterCreateFromPrinterID(new_printer_id.get()); bool printer_exists = new_printer != nullptr; PMRelease(new_printer); return printer_exists; #elif BUILDFLAG(IS_WIN) printing::ScopedPrinterHandle printer; return printer.OpenPrinterWithName(base::as_wcstr(device_name)); #else return true; #endif } std::pair<std::string, std::u16string> GetDefaultPrinterAsync() { #if BUILDFLAG(IS_WIN) // Blocking is needed here because Windows printer drivers are oftentimes // not thread-safe and have to be accessed on the UI thread. base::ThreadRestrictions::ScopedAllowIO allow_io; #endif scoped_refptr<printing::PrintBackend> print_backend = printing::PrintBackend::CreateInstance( g_browser_process->GetApplicationLocale()); std::string printer_name; printing::mojom::ResultCode code = print_backend->GetDefaultPrinterName(printer_name); // We don't want to return if this fails since some devices won't have a // default printer. if (code != printing::mojom::ResultCode::kSuccess) LOG(ERROR) << "Failed to get default printer name"; // Check for existing printers and pick the first one should it exist. if (printer_name.empty()) { printing::PrinterList printers; if (print_backend->EnumeratePrinters(&printers) != printing::mojom::ResultCode::kSuccess) return std::make_pair("Failed to enumerate printers", std::u16string()); if (!printers.empty()) printer_name = printers.front().printer_name; } return std::make_pair(std::string(), base::UTF8ToUTF16(printer_name)); } // Copied from // chrome/browser/ui/webui/print_preview/local_printer_handler_default.cc:L36-L54 scoped_refptr<base::TaskRunner> CreatePrinterHandlerTaskRunner() { // USER_VISIBLE because the result is displayed in the print preview dialog. #if !BUILDFLAG(IS_WIN) static constexpr base::TaskTraits kTraits = { base::MayBlock(), base::TaskPriority::USER_VISIBLE}; #endif #if defined(USE_CUPS) // CUPS is thread safe. return base::ThreadPool::CreateTaskRunner(kTraits); #elif BUILDFLAG(IS_WIN) // Windows drivers are likely not thread-safe and need to be accessed on the // UI thread. return content::GetUIThreadTaskRunner( {base::MayBlock(), base::TaskPriority::USER_VISIBLE}); #else // Be conservative on unsupported platforms. return base::ThreadPool::CreateSingleThreadTaskRunner(kTraits); #endif } #endif struct UserDataLink : public base::SupportsUserData::Data { explicit UserDataLink(base::WeakPtr<WebContents> contents) : web_contents(contents) {} base::WeakPtr<WebContents> web_contents; }; const void* kElectronApiWebContentsKey = &kElectronApiWebContentsKey; const char kRootName[] = "<root>"; struct FileSystem { FileSystem() = default; FileSystem(const std::string& type, const std::string& file_system_name, const std::string& root_url, const std::string& file_system_path) : type(type), file_system_name(file_system_name), root_url(root_url), file_system_path(file_system_path) {} std::string type; std::string file_system_name; std::string root_url; std::string file_system_path; }; std::string RegisterFileSystem(content::WebContents* web_contents, const base::FilePath& path) { auto* isolated_context = storage::IsolatedContext::GetInstance(); std::string root_name(kRootName); storage::IsolatedContext::ScopedFSHandle file_system = isolated_context->RegisterFileSystemForPath( storage::kFileSystemTypeLocal, std::string(), path, &root_name); content::ChildProcessSecurityPolicy* policy = content::ChildProcessSecurityPolicy::GetInstance(); content::RenderViewHost* render_view_host = web_contents->GetRenderViewHost(); int renderer_id = render_view_host->GetProcess()->GetID(); policy->GrantReadFileSystem(renderer_id, file_system.id()); policy->GrantWriteFileSystem(renderer_id, file_system.id()); policy->GrantCreateFileForFileSystem(renderer_id, file_system.id()); policy->GrantDeleteFromFileSystem(renderer_id, file_system.id()); if (!policy->CanReadFile(renderer_id, path)) policy->GrantReadFile(renderer_id, path); return file_system.id(); } FileSystem CreateFileSystemStruct(content::WebContents* web_contents, const std::string& file_system_id, const std::string& file_system_path, const std::string& type) { const GURL origin = web_contents->GetURL().DeprecatedGetOriginAsURL(); std::string file_system_name = storage::GetIsolatedFileSystemName(origin, file_system_id); std::string root_url = storage::GetIsolatedFileSystemRootURIString( origin, file_system_id, kRootName); return FileSystem(type, file_system_name, root_url, file_system_path); } std::unique_ptr<base::DictionaryValue> CreateFileSystemValue( const FileSystem& file_system) { auto file_system_value = std::make_unique<base::DictionaryValue>(); file_system_value->SetString("type", file_system.type); file_system_value->SetString("fileSystemName", file_system.file_system_name); file_system_value->SetString("rootURL", file_system.root_url); file_system_value->SetString("fileSystemPath", file_system.file_system_path); return file_system_value; } void WriteToFile(const base::FilePath& path, const std::string& content) { base::ScopedBlockingCall scoped_blocking_call(FROM_HERE, base::BlockingType::WILL_BLOCK); DCHECK(!path.empty()); base::WriteFile(path, content.data(), content.size()); } void AppendToFile(const base::FilePath& path, const std::string& content) { base::ScopedBlockingCall scoped_blocking_call(FROM_HERE, base::BlockingType::WILL_BLOCK); DCHECK(!path.empty()); base::AppendToFile(path, content); } PrefService* GetPrefService(content::WebContents* web_contents) { auto* context = web_contents->GetBrowserContext(); return static_cast<electron::ElectronBrowserContext*>(context)->prefs(); } std::map<std::string, std::string> GetAddedFileSystemPaths( content::WebContents* web_contents) { auto* pref_service = GetPrefService(web_contents); const base::Value* file_system_paths_value = pref_service->GetDictionary(prefs::kDevToolsFileSystemPaths); std::map<std::string, std::string> result; if (file_system_paths_value) { const base::DictionaryValue* file_system_paths_dict; file_system_paths_value->GetAsDictionary(&file_system_paths_dict); for (auto it : file_system_paths_dict->DictItems()) { std::string type = it.second.is_string() ? it.second.GetString() : std::string(); result[it.first] = type; } } return result; } bool IsDevToolsFileSystemAdded(content::WebContents* web_contents, const std::string& file_system_path) { auto file_system_paths = GetAddedFileSystemPaths(web_contents); return file_system_paths.find(file_system_path) != file_system_paths.end(); } void SetBackgroundColor(content::RenderWidgetHostView* rwhv, SkColor color) { rwhv->SetBackgroundColor(color); static_cast<content::RenderWidgetHostViewBase*>(rwhv) ->SetContentBackgroundColor(color); } } // namespace #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) WebContents::Type GetTypeFromViewType(extensions::mojom::ViewType view_type) { switch (view_type) { case extensions::mojom::ViewType::kExtensionBackgroundPage: return WebContents::Type::kBackgroundPage; case extensions::mojom::ViewType::kAppWindow: case extensions::mojom::ViewType::kComponent: case extensions::mojom::ViewType::kExtensionDialog: case extensions::mojom::ViewType::kExtensionPopup: case extensions::mojom::ViewType::kBackgroundContents: case extensions::mojom::ViewType::kExtensionGuest: case extensions::mojom::ViewType::kTabContents: case extensions::mojom::ViewType::kInvalid: return WebContents::Type::kRemote; } } #endif WebContents::WebContents(v8::Isolate* isolate, content::WebContents* web_contents) : content::WebContentsObserver(web_contents), type_(Type::kRemote), id_(GetAllWebContents().Add(this)), devtools_file_system_indexer_( base::MakeRefCounted<DevToolsFileSystemIndexer>()), exclusive_access_manager_(std::make_unique<ExclusiveAccessManager>(this)), file_task_runner_( base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()})) #if BUILDFLAG(ENABLE_PRINTING) , print_task_runner_(CreatePrinterHandlerTaskRunner()) #endif { #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) // WebContents created by extension host will have valid ViewType set. extensions::mojom::ViewType view_type = extensions::GetViewType(web_contents); if (view_type != extensions::mojom::ViewType::kInvalid) { InitWithExtensionView(isolate, web_contents, view_type); } extensions::ElectronExtensionWebContentsObserver::CreateForWebContents( web_contents); script_executor_ = std::make_unique<extensions::ScriptExecutor>(web_contents); #endif auto session = Session::CreateFrom(isolate, GetBrowserContext()); session_.Reset(isolate, session.ToV8()); web_contents->SetUserAgentOverride(blink::UserAgentOverride::UserAgentOnly( GetBrowserContext()->GetUserAgent()), false); web_contents->SetUserData(kElectronApiWebContentsKey, std::make_unique<UserDataLink>(GetWeakPtr())); InitZoomController(web_contents, gin::Dictionary::CreateEmpty(isolate)); } WebContents::WebContents(v8::Isolate* isolate, std::unique_ptr<content::WebContents> web_contents, Type type) : content::WebContentsObserver(web_contents.get()), type_(type), id_(GetAllWebContents().Add(this)), devtools_file_system_indexer_( base::MakeRefCounted<DevToolsFileSystemIndexer>()), exclusive_access_manager_(std::make_unique<ExclusiveAccessManager>(this)), file_task_runner_( base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()})) #if BUILDFLAG(ENABLE_PRINTING) , print_task_runner_(CreatePrinterHandlerTaskRunner()) #endif { DCHECK(type != Type::kRemote) << "Can't take ownership of a remote WebContents"; auto session = Session::CreateFrom(isolate, GetBrowserContext()); session_.Reset(isolate, session.ToV8()); InitWithSessionAndOptions(isolate, std::move(web_contents), session, gin::Dictionary::CreateEmpty(isolate)); } WebContents::WebContents(v8::Isolate* isolate, const gin_helper::Dictionary& options) : id_(GetAllWebContents().Add(this)), devtools_file_system_indexer_( base::MakeRefCounted<DevToolsFileSystemIndexer>()), exclusive_access_manager_(std::make_unique<ExclusiveAccessManager>(this)), file_task_runner_( base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()})) #if BUILDFLAG(ENABLE_PRINTING) , print_task_runner_(CreatePrinterHandlerTaskRunner()) #endif { // Read options. options.Get("backgroundThrottling", &background_throttling_); // Get type options.Get("type", &type_); #if BUILDFLAG(ENABLE_OSR) bool b = false; if (options.Get(options::kOffscreen, &b) && b) type_ = Type::kOffScreen; #endif // Init embedder earlier options.Get("embedder", &embedder_); // Whether to enable DevTools. options.Get("devTools", &enable_devtools_); // BrowserViews are not attached to a window initially so they should start // off as hidden. This is also important for compositor recycling. See: // https://github.com/electron/electron/pull/21372 bool initially_shown = type_ != Type::kBrowserView; options.Get(options::kShow, &initially_shown); // Obtain the session. std::string partition; gin::Handle<api::Session> session; if (options.Get("session", &session) && !session.IsEmpty()) { } else if (options.Get("partition", &partition)) { session = Session::FromPartition(isolate, partition); } else { // Use the default session if not specified. session = Session::FromPartition(isolate, ""); } session_.Reset(isolate, session.ToV8()); std::unique_ptr<content::WebContents> web_contents; if (IsGuest()) { scoped_refptr<content::SiteInstance> site_instance = content::SiteInstance::CreateForURL(session->browser_context(), GURL("chrome-guest://fake-host")); content::WebContents::CreateParams params(session->browser_context(), site_instance); guest_delegate_ = std::make_unique<WebViewGuestDelegate>(embedder_->web_contents(), this); params.guest_delegate = guest_delegate_.get(); #if BUILDFLAG(ENABLE_OSR) if (embedder_ && embedder_->IsOffScreen()) { auto* view = new OffScreenWebContentsView( false, base::BindRepeating(&WebContents::OnPaint, base::Unretained(this))); params.view = view; params.delegate_view = view; web_contents = content::WebContents::Create(params); view->SetWebContents(web_contents.get()); } else { #endif web_contents = content::WebContents::Create(params); #if BUILDFLAG(ENABLE_OSR) } } else if (IsOffScreen()) { // webPreferences does not have a transparent option, so if the window needs // to be transparent, that will be set at electron_api_browser_window.cc#L57 // and we then need to pull it back out and check it here. std::string background_color; options.GetHidden(options::kBackgroundColor, &background_color); bool transparent = ParseCSSColor(background_color) == SK_ColorTRANSPARENT; content::WebContents::CreateParams params(session->browser_context()); auto* view = new OffScreenWebContentsView( transparent, base::BindRepeating(&WebContents::OnPaint, base::Unretained(this))); params.view = view; params.delegate_view = view; web_contents = content::WebContents::Create(params); view->SetWebContents(web_contents.get()); #endif } else { content::WebContents::CreateParams params(session->browser_context()); params.initially_hidden = !initially_shown; web_contents = content::WebContents::Create(params); } InitWithSessionAndOptions(isolate, std::move(web_contents), session, options); } void WebContents::InitZoomController(content::WebContents* web_contents, const gin_helper::Dictionary& options) { WebContentsZoomController::CreateForWebContents(web_contents); zoom_controller_ = WebContentsZoomController::FromWebContents(web_contents); double zoom_factor; if (options.Get(options::kZoomFactor, &zoom_factor)) zoom_controller_->SetDefaultZoomFactor(zoom_factor); } void WebContents::InitWithSessionAndOptions( v8::Isolate* isolate, std::unique_ptr<content::WebContents> owned_web_contents, gin::Handle<api::Session> session, const gin_helper::Dictionary& options) { Observe(owned_web_contents.get()); InitWithWebContents(std::move(owned_web_contents), session->browser_context(), IsGuest()); inspectable_web_contents_->GetView()->SetDelegate(this); auto* prefs = web_contents()->GetMutableRendererPrefs(); // Collect preferred languages from OS and browser process. accept_languages // effects HTTP header, navigator.languages, and CJK fallback font selection. // // Note that an application locale set to the browser process might be // different with the one set to the preference list. // (e.g. overridden with --lang) std::string accept_languages = g_browser_process->GetApplicationLocale() + ","; for (auto const& language : electron::GetPreferredLanguages()) { if (language == g_browser_process->GetApplicationLocale()) continue; accept_languages += language + ","; } accept_languages.pop_back(); prefs->accept_languages = accept_languages; #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_WIN) // Update font settings. static const gfx::FontRenderParams params( gfx::GetFontRenderParams(gfx::FontRenderParamsQuery(), nullptr)); prefs->should_antialias_text = params.antialiasing; prefs->use_subpixel_positioning = params.subpixel_positioning; prefs->hinting = params.hinting; prefs->use_autohinter = params.autohinter; prefs->use_bitmaps = params.use_bitmaps; prefs->subpixel_rendering = params.subpixel_rendering; #endif // Honor the system's cursor blink rate settings if (auto interval = GetCursorBlinkInterval()) prefs->caret_blink_interval = *interval; // Save the preferences in C++. // If there's already a WebContentsPreferences object, we created it as part // of the webContents.setWindowOpenHandler path, so don't overwrite it. if (!WebContentsPreferences::From(web_contents())) { new WebContentsPreferences(web_contents(), options); } // Trigger re-calculation of webkit prefs. web_contents()->NotifyPreferencesChanged(); WebContentsPermissionHelper::CreateForWebContents(web_contents()); InitZoomController(web_contents(), options); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) extensions::ElectronExtensionWebContentsObserver::CreateForWebContents( web_contents()); script_executor_ = std::make_unique<extensions::ScriptExecutor>(web_contents()); #endif AutofillDriverFactory::CreateForWebContents(web_contents()); web_contents()->SetUserAgentOverride(blink::UserAgentOverride::UserAgentOnly( GetBrowserContext()->GetUserAgent()), false); if (IsGuest()) { NativeWindow* owner_window = nullptr; if (embedder_) { // New WebContents's owner_window is the embedder's owner_window. auto* relay = NativeWindowRelay::FromWebContents(embedder_->web_contents()); if (relay) owner_window = relay->GetNativeWindow(); } if (owner_window) SetOwnerWindow(owner_window); } web_contents()->SetUserData(kElectronApiWebContentsKey, std::make_unique<UserDataLink>(GetWeakPtr())); } #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) void WebContents::InitWithExtensionView(v8::Isolate* isolate, content::WebContents* web_contents, extensions::mojom::ViewType view_type) { // Must reassign type prior to calling `Init`. type_ = GetTypeFromViewType(view_type); if (type_ == Type::kRemote) return; if (type_ == Type::kBackgroundPage) // non-background-page WebContents are retained by other classes. We need // to pin here to prevent background-page WebContents from being GC'd. // The background page api::WebContents will live until the underlying // content::WebContents is destroyed. Pin(isolate); // Allow toggling DevTools for background pages Observe(web_contents); InitWithWebContents(std::unique_ptr<content::WebContents>(web_contents), GetBrowserContext(), IsGuest()); inspectable_web_contents_->GetView()->SetDelegate(this); } #endif void WebContents::InitWithWebContents( std::unique_ptr<content::WebContents> web_contents, ElectronBrowserContext* browser_context, bool is_guest) { browser_context_ = browser_context; web_contents->SetDelegate(this); #if BUILDFLAG(ENABLE_PRINTING) PrintPreviewMessageHandler::CreateForWebContents(web_contents.get()); PrintViewManagerElectron::CreateForWebContents(web_contents.get()); printing::CreateCompositeClientIfNeeded(web_contents.get(), browser_context->GetUserAgent()); #endif #if BUILDFLAG(ENABLE_PDF_VIEWER) pdf::PDFWebContentsHelper::CreateForWebContentsWithClient( web_contents.get(), std::make_unique<ElectronPDFWebContentsHelperClient>()); #endif // Determine whether the WebContents is offscreen. auto* web_preferences = WebContentsPreferences::From(web_contents.get()); offscreen_ = web_preferences && web_preferences->IsOffscreen(); // Create InspectableWebContents. inspectable_web_contents_ = std::make_unique<InspectableWebContents>( std::move(web_contents), browser_context->prefs(), is_guest); inspectable_web_contents_->SetDelegate(this); } WebContents::~WebContents() { // clear out objects that have been granted permissions so that when // WebContents::RenderFrameDeleted is called as a result of WebContents // destruction it doesn't try to clear out a granted_devices_ // on a destructed object. granted_devices_.clear(); if (!inspectable_web_contents_) { WebContentsDestroyed(); return; } inspectable_web_contents_->GetView()->SetDelegate(nullptr); // This event is only for internal use, which is emitted when WebContents is // being destroyed. Emit("will-destroy"); // For guest view based on OOPIF, the WebContents is released by the embedder // frame, and we need to clear the reference to the memory. bool not_owned_by_this = IsGuest() && attached_; #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) // And background pages are owned by extensions::ExtensionHost. if (type_ == Type::kBackgroundPage) not_owned_by_this = true; #endif if (not_owned_by_this) { inspectable_web_contents_->ReleaseWebContents(); WebContentsDestroyed(); } // InspectableWebContents will be automatically destroyed. } void WebContents::DeleteThisIfAlive() { // It is possible that the FirstWeakCallback has been called but the // SecondWeakCallback has not, in this case the garbage collection of // WebContents has already started and we should not |delete this|. // Calling |GetWrapper| can detect this corner case. auto* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); v8::Local<v8::Object> wrapper; if (!GetWrapper(isolate).ToLocal(&wrapper)) return; delete this; } void WebContents::Destroy() { // The content::WebContents should be destroyed asyncronously when possible // as user may choose to destroy WebContents during an event of it. if (Browser::Get()->is_shutting_down() || IsGuest()) { DeleteThisIfAlive(); } else { content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce( [](base::WeakPtr<WebContents> contents) { if (contents) contents->DeleteThisIfAlive(); }, GetWeakPtr())); } } bool WebContents::DidAddMessageToConsole( content::WebContents* source, blink::mojom::ConsoleMessageLevel level, const std::u16string& message, int32_t line_no, const std::u16string& source_id) { return Emit("console-message", static_cast<int32_t>(level), message, line_no, source_id); } void WebContents::OnCreateWindow( const GURL& target_url, const content::Referrer& referrer, const std::string& frame_name, WindowOpenDisposition disposition, const std::string& features, const scoped_refptr<network::ResourceRequestBody>& body) { Emit("-new-window", target_url, frame_name, disposition, features, referrer, body); } void WebContents::WebContentsCreatedWithFullParams( content::WebContents* source_contents, int opener_render_process_id, int opener_render_frame_id, const content::mojom::CreateNewWindowParams& params, content::WebContents* new_contents) { ChildWebContentsTracker::CreateForWebContents(new_contents); auto* tracker = ChildWebContentsTracker::FromWebContents(new_contents); tracker->url = params.target_url; tracker->frame_name = params.frame_name; tracker->referrer = params.referrer.To<content::Referrer>(); tracker->raw_features = params.raw_features; tracker->body = params.body; v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); gin_helper::Dictionary dict; gin::ConvertFromV8(isolate, pending_child_web_preferences_.Get(isolate), &dict); pending_child_web_preferences_.Reset(); // Associate the preferences passed in via `setWindowOpenHandler` with the // content::WebContents that was just created for the child window. These // preferences will be picked up by the RenderWidgetHost via its call to the // delegate's OverrideWebkitPrefs. new WebContentsPreferences(new_contents, dict); } bool WebContents::IsWebContentsCreationOverridden( content::SiteInstance* source_site_instance, content::mojom::WindowContainerType window_container_type, const GURL& opener_url, const content::mojom::CreateNewWindowParams& params) { bool default_prevented = Emit( "-will-add-new-contents", params.target_url, params.frame_name, params.raw_features, params.disposition, *params.referrer, params.body); // If the app prevented the default, redirect to CreateCustomWebContents, // which always returns nullptr, which will result in the window open being // prevented (window.open() will return null in the renderer). return default_prevented; } void WebContents::SetNextChildWebPreferences( const gin_helper::Dictionary preferences) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); // Store these prefs for when Chrome calls WebContentsCreatedWithFullParams // with the new child contents. pending_child_web_preferences_.Reset(isolate, preferences.GetHandle()); } content::WebContents* WebContents::CreateCustomWebContents( content::RenderFrameHost* opener, content::SiteInstance* source_site_instance, bool is_new_browsing_instance, const GURL& opener_url, const std::string& frame_name, const GURL& target_url, const content::StoragePartitionConfig& partition_config, content::SessionStorageNamespace* session_storage_namespace) { return nullptr; } void WebContents::AddNewContents( content::WebContents* source, std::unique_ptr<content::WebContents> new_contents, const GURL& target_url, WindowOpenDisposition disposition, const gfx::Rect& initial_rect, bool user_gesture, bool* was_blocked) { auto* tracker = ChildWebContentsTracker::FromWebContents(new_contents.get()); DCHECK(tracker); v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); auto api_web_contents = CreateAndTake(isolate, std::move(new_contents), Type::kBrowserWindow); // We call RenderFrameCreated here as at this point the empty "about:blank" // render frame has already been created. If the window never navigates again // RenderFrameCreated won't be called and certain prefs like // "kBackgroundColor" will not be applied. auto* frame = api_web_contents->MainFrame(); if (frame) { api_web_contents->HandleNewRenderFrame(frame); } if (Emit("-add-new-contents", api_web_contents, disposition, user_gesture, initial_rect.x(), initial_rect.y(), initial_rect.width(), initial_rect.height(), tracker->url, tracker->frame_name, tracker->referrer, tracker->raw_features, tracker->body)) { api_web_contents->Destroy(); } } content::WebContents* WebContents::OpenURLFromTab( content::WebContents* source, const content::OpenURLParams& params) { auto weak_this = GetWeakPtr(); if (params.disposition != WindowOpenDisposition::CURRENT_TAB) { Emit("-new-window", params.url, "", params.disposition, "", params.referrer, params.post_data); return nullptr; } if (!weak_this || !web_contents()) return nullptr; content::NavigationController::LoadURLParams load_url_params(params.url); load_url_params.referrer = params.referrer; load_url_params.transition_type = params.transition; load_url_params.extra_headers = params.extra_headers; load_url_params.should_replace_current_entry = params.should_replace_current_entry; load_url_params.is_renderer_initiated = params.is_renderer_initiated; load_url_params.started_from_context_menu = params.started_from_context_menu; load_url_params.initiator_origin = params.initiator_origin; load_url_params.source_site_instance = params.source_site_instance; load_url_params.frame_tree_node_id = params.frame_tree_node_id; load_url_params.redirect_chain = params.redirect_chain; load_url_params.has_user_gesture = params.user_gesture; load_url_params.blob_url_loader_factory = params.blob_url_loader_factory; load_url_params.href_translate = params.href_translate; load_url_params.reload_type = params.reload_type; if (params.post_data) { load_url_params.load_type = content::NavigationController::LOAD_TYPE_HTTP_POST; load_url_params.post_data = params.post_data; } source->GetController().LoadURLWithParams(load_url_params); return source; } void WebContents::BeforeUnloadFired(content::WebContents* tab, bool proceed, bool* proceed_to_fire_unload) { if (type_ == Type::kBrowserWindow || type_ == Type::kOffScreen || type_ == Type::kBrowserView) *proceed_to_fire_unload = proceed; else *proceed_to_fire_unload = true; // Note that Chromium does not emit this for navigations. Emit("before-unload-fired", proceed); } void WebContents::SetContentsBounds(content::WebContents* source, const gfx::Rect& rect) { for (ExtendedWebContentsObserver& observer : observers_) observer.OnSetContentBounds(rect); } void WebContents::CloseContents(content::WebContents* source) { Emit("close"); auto* autofill_driver_factory = AutofillDriverFactory::FromWebContents(web_contents()); if (autofill_driver_factory) { autofill_driver_factory->CloseAllPopups(); } for (ExtendedWebContentsObserver& observer : observers_) observer.OnCloseContents(); } void WebContents::ActivateContents(content::WebContents* source) { for (ExtendedWebContentsObserver& observer : observers_) observer.OnActivateContents(); } void WebContents::UpdateTargetURL(content::WebContents* source, const GURL& url) { Emit("update-target-url", url); } bool WebContents::HandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) { if (type_ == Type::kWebView && embedder_) { // Send the unhandled keyboard events back to the embedder. return embedder_->HandleKeyboardEvent(source, event); } else { return PlatformHandleKeyboardEvent(source, event); } } #if !BUILDFLAG(IS_MAC) // NOTE: The macOS version of this function is found in // electron_api_web_contents_mac.mm, as it requires calling into objective-C // code. bool WebContents::PlatformHandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) { // Escape exits tabbed fullscreen mode. if (event.windows_key_code == ui::VKEY_ESCAPE && is_html_fullscreen()) { ExitFullscreenModeForTab(source); return true; } // Check if the webContents has preferences and to ignore shortcuts auto* web_preferences = WebContentsPreferences::From(source); if (web_preferences && web_preferences->ShouldIgnoreMenuShortcuts()) return false; // Let the NativeWindow handle other parts. if (owner_window()) { owner_window()->HandleKeyboardEvent(source, event); return true; } return false; } #endif content::KeyboardEventProcessingResult WebContents::PreHandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) { if (exclusive_access_manager_->HandleUserKeyEvent(event)) return content::KeyboardEventProcessingResult::HANDLED; if (event.GetType() == blink::WebInputEvent::Type::kRawKeyDown || event.GetType() == blink::WebInputEvent::Type::kKeyUp) { bool prevent_default = Emit("before-input-event", event); if (prevent_default) { return content::KeyboardEventProcessingResult::HANDLED; } } return content::KeyboardEventProcessingResult::NOT_HANDLED; } void WebContents::ContentsZoomChange(bool zoom_in) { Emit("zoom-changed", zoom_in ? "in" : "out"); } Profile* WebContents::GetProfile() { return nullptr; } bool WebContents::IsFullscreen() const { return owner_window_ && owner_window_->IsFullscreen(); } void WebContents::EnterFullscreen(const GURL& url, ExclusiveAccessBubbleType bubble_type, const int64_t display_id) {} void WebContents::ExitFullscreen() {} void WebContents::UpdateExclusiveAccessExitBubbleContent( const GURL& url, ExclusiveAccessBubbleType bubble_type, ExclusiveAccessBubbleHideCallback bubble_first_hide_callback, bool force_update) {} void WebContents::OnExclusiveAccessUserInput() {} content::WebContents* WebContents::GetActiveWebContents() { return web_contents(); } bool WebContents::CanUserExitFullscreen() const { return true; } bool WebContents::IsExclusiveAccessBubbleDisplayed() const { return false; } void WebContents::EnterFullscreenModeForTab( content::RenderFrameHost* requesting_frame, const blink::mojom::FullscreenOptions& options) { auto* source = content::WebContents::FromRenderFrameHost(requesting_frame); auto* permission_helper = WebContentsPermissionHelper::FromWebContents(source); auto callback = base::BindRepeating(&WebContents::OnEnterFullscreenModeForTab, base::Unretained(this), requesting_frame, options); permission_helper->RequestFullscreenPermission(callback); exclusive_access_manager_->fullscreen_controller()->EnterFullscreenModeForTab( requesting_frame, options.display_id); } void WebContents::OnEnterFullscreenModeForTab( content::RenderFrameHost* requesting_frame, const blink::mojom::FullscreenOptions& options, bool allowed) { if (!allowed || !owner_window_) return; auto* source = content::WebContents::FromRenderFrameHost(requesting_frame); if (IsFullscreenForTabOrPending(source)) { DCHECK_EQ(fullscreen_frame_, source->GetFocusedFrame()); return; } SetHtmlApiFullscreen(true); if (native_fullscreen_) { // Explicitly trigger a view resize, as the size is not actually changing if // the browser is fullscreened, too. source->GetRenderViewHost()->GetWidget()->SynchronizeVisualProperties(); } } void WebContents::ExitFullscreenModeForTab(content::WebContents* source) { if (!owner_window_) return; // This needs to be called before we exit fullscreen on the native window, // or the controller will incorrectly think we weren't fullscreen and bail. exclusive_access_manager_->fullscreen_controller()->ExitFullscreenModeForTab( source); SetHtmlApiFullscreen(false); if (native_fullscreen_) { // Explicitly trigger a view resize, as the size is not actually changing if // the browser is fullscreened, too. Chrome does this indirectly from // `chrome/browser/ui/exclusive_access/fullscreen_controller.cc`. source->GetRenderViewHost()->GetWidget()->SynchronizeVisualProperties(); } } void WebContents::RendererUnresponsive( content::WebContents* source, content::RenderWidgetHost* render_widget_host, base::RepeatingClosure hang_monitor_restarter) { Emit("unresponsive"); } void WebContents::RendererResponsive( content::WebContents* source, content::RenderWidgetHost* render_widget_host) { Emit("responsive"); } bool WebContents::HandleContextMenu(content::RenderFrameHost& render_frame_host, const content::ContextMenuParams& params) { Emit("context-menu", std::make_pair(params, &render_frame_host)); return true; } bool WebContents::OnGoToEntryOffset(int offset) { GoToOffset(offset); return false; } void WebContents::FindReply(content::WebContents* web_contents, int request_id, int number_of_matches, const gfx::Rect& selection_rect, int active_match_ordinal, bool final_update) { if (!final_update) return; v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); gin_helper::Dictionary result = gin::Dictionary::CreateEmpty(isolate); result.Set("requestId", request_id); result.Set("matches", number_of_matches); result.Set("selectionArea", selection_rect); result.Set("activeMatchOrdinal", active_match_ordinal); result.Set("finalUpdate", final_update); // Deprecate after 2.0 Emit("found-in-page", result.GetHandle()); } void WebContents::RequestExclusivePointerAccess( content::WebContents* web_contents, bool user_gesture, bool last_unlocked_by_target, bool allowed) { if (allowed) { exclusive_access_manager_->mouse_lock_controller()->RequestToLockMouse( web_contents, user_gesture, last_unlocked_by_target); } else { web_contents->GotResponseToLockMouseRequest( blink::mojom::PointerLockResult::kPermissionDenied); } } void WebContents::RequestToLockMouse(content::WebContents* web_contents, bool user_gesture, bool last_unlocked_by_target) { auto* permission_helper = WebContentsPermissionHelper::FromWebContents(web_contents); permission_helper->RequestPointerLockPermission( user_gesture, last_unlocked_by_target, base::BindOnce(&WebContents::RequestExclusivePointerAccess, base::Unretained(this))); } void WebContents::LostMouseLock() { exclusive_access_manager_->mouse_lock_controller()->LostMouseLock(); } void WebContents::RequestKeyboardLock(content::WebContents* web_contents, bool esc_key_locked) { exclusive_access_manager_->keyboard_lock_controller()->RequestKeyboardLock( web_contents, esc_key_locked); } void WebContents::CancelKeyboardLockRequest( content::WebContents* web_contents) { exclusive_access_manager_->keyboard_lock_controller() ->CancelKeyboardLockRequest(web_contents); } bool WebContents::CheckMediaAccessPermission( content::RenderFrameHost* render_frame_host, const GURL& security_origin, blink::mojom::MediaStreamType type) { auto* web_contents = content::WebContents::FromRenderFrameHost(render_frame_host); auto* permission_helper = WebContentsPermissionHelper::FromWebContents(web_contents); return permission_helper->CheckMediaAccessPermission(security_origin, type); } void WebContents::RequestMediaAccessPermission( content::WebContents* web_contents, const content::MediaStreamRequest& request, content::MediaResponseCallback callback) { auto* permission_helper = WebContentsPermissionHelper::FromWebContents(web_contents); permission_helper->RequestMediaAccessPermission(request, std::move(callback)); } content::JavaScriptDialogManager* WebContents::GetJavaScriptDialogManager( content::WebContents* source) { if (!dialog_manager_) dialog_manager_ = std::make_unique<ElectronJavaScriptDialogManager>(); return dialog_manager_.get(); } void WebContents::OnAudioStateChanged(bool audible) { Emit("-audio-state-changed", audible); } void WebContents::BeforeUnloadFired(bool proceed, const base::TimeTicks& proceed_time) { // Do nothing, we override this method just to avoid compilation error since // there are two virtual functions named BeforeUnloadFired. } void WebContents::HandleNewRenderFrame( content::RenderFrameHost* render_frame_host) { auto* rwhv = render_frame_host->GetView(); if (!rwhv) return; // Set the background color of RenderWidgetHostView. auto* web_preferences = WebContentsPreferences::From(web_contents()); if (web_preferences) { absl::optional<SkColor> maybe_color = web_preferences->GetBackgroundColor(); web_contents()->SetPageBaseBackgroundColor(maybe_color); bool guest = IsGuest() || type_ == Type::kBrowserView; SkColor color = maybe_color.value_or(guest ? SK_ColorTRANSPARENT : SK_ColorWHITE); SetBackgroundColor(rwhv, color); } if (!background_throttling_) render_frame_host->GetRenderViewHost()->SetSchedulerThrottling(false); auto* rwh_impl = static_cast<content::RenderWidgetHostImpl*>(rwhv->GetRenderWidgetHost()); if (rwh_impl) rwh_impl->disable_hidden_ = !background_throttling_; auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host); if (web_frame) web_frame->Connect(); } void WebContents::OnBackgroundColorChanged() { absl::optional<SkColor> color = web_contents()->GetBackgroundColor(); if (color.has_value()) { auto* const view = web_contents()->GetRenderWidgetHostView(); static_cast<content::RenderWidgetHostViewBase*>(view) ->SetContentBackgroundColor(color.value()); } } void WebContents::RenderFrameCreated( content::RenderFrameHost* render_frame_host) { HandleNewRenderFrame(render_frame_host); // RenderFrameCreated is called for speculative frames which may not be // used in certain cross-origin navigations. Invoking // RenderFrameHost::GetLifecycleState currently crashes when called for // speculative frames so we need to filter it out for now. Check // https://crbug.com/1183639 for details on when this can be removed. auto* rfh_impl = static_cast<content::RenderFrameHostImpl*>(render_frame_host); if (rfh_impl->lifecycle_state() == content::RenderFrameHostImpl::LifecycleStateImpl::kSpeculative) { return; } content::RenderFrameHost::LifecycleState lifecycle_state = render_frame_host->GetLifecycleState(); if (lifecycle_state == content::RenderFrameHost::LifecycleState::kActive) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); gin_helper::Dictionary details = gin_helper::Dictionary::CreateEmpty(isolate); details.SetGetter("frame", render_frame_host); Emit("frame-created", details); } } void WebContents::RenderFrameDeleted( content::RenderFrameHost* render_frame_host) { // A RenderFrameHost can be deleted when: // - A WebContents is removed and its containing frames are disposed. // - An <iframe> is removed from the DOM. // - Cross-origin navigation creates a new RFH in a separate process which // is swapped by content::RenderFrameHostManager. // // clear out objects that have been granted permissions if (!granted_devices_.empty()) { granted_devices_.erase(render_frame_host->GetFrameTreeNodeId()); } // WebFrameMain::FromRenderFrameHost(rfh) will use the RFH's FrameTreeNode ID // to find an existing instance of WebFrameMain. During a cross-origin // navigation, the deleted RFH will be the old host which was swapped out. In // this special case, we need to also ensure that WebFrameMain's internal RFH // matches before marking it as disposed. auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host); if (web_frame && web_frame->render_frame_host() == render_frame_host) web_frame->MarkRenderFrameDisposed(); } void WebContents::RenderFrameHostChanged(content::RenderFrameHost* old_host, content::RenderFrameHost* new_host) { // During cross-origin navigation, a FrameTreeNode will swap out its RFH. // If an instance of WebFrameMain exists, it will need to have its RFH // swapped as well. // // |old_host| can be a nullptr so we use |new_host| for looking up the // WebFrameMain instance. auto* web_frame = WebFrameMain::FromFrameTreeNodeId(new_host->GetFrameTreeNodeId()); if (web_frame) { web_frame->UpdateRenderFrameHost(new_host); } } void WebContents::FrameDeleted(int frame_tree_node_id) { auto* web_frame = WebFrameMain::FromFrameTreeNodeId(frame_tree_node_id); if (web_frame) web_frame->Destroyed(); } void WebContents::RenderViewDeleted(content::RenderViewHost* render_view_host) { // This event is necessary for tracking any states with respect to // intermediate render view hosts aka speculative render view hosts. Currently // used by object-registry.js to ref count remote objects. Emit("render-view-deleted", render_view_host->GetProcess()->GetID()); if (web_contents()->GetRenderViewHost() == render_view_host) { // When the RVH that has been deleted is the current RVH it means that the // the web contents are being closed. This is communicated by this event. // Currently tracked by guest-window-manager.ts to destroy the // BrowserWindow. Emit("current-render-view-deleted", render_view_host->GetProcess()->GetID()); } } void WebContents::PrimaryMainFrameRenderProcessGone( base::TerminationStatus status) { auto weak_this = GetWeakPtr(); Emit("crashed", status == base::TERMINATION_STATUS_PROCESS_WAS_KILLED); // User might destroy WebContents in the crashed event. if (!weak_this || !web_contents()) return; v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); gin_helper::Dictionary details = gin_helper::Dictionary::CreateEmpty(isolate); details.Set("reason", status); details.Set("exitCode", web_contents()->GetCrashedErrorCode()); Emit("render-process-gone", details); } void WebContents::PluginCrashed(const base::FilePath& plugin_path, base::ProcessId plugin_pid) { #if BUILDFLAG(ENABLE_PLUGINS) content::WebPluginInfo info; auto* plugin_service = content::PluginService::GetInstance(); plugin_service->GetPluginInfoByPath(plugin_path, &info); Emit("plugin-crashed", info.name, info.version); #endif // BUILDFLAG(ENABLE_PLUGINS) } void WebContents::MediaStartedPlaying(const MediaPlayerInfo& video_type, const content::MediaPlayerId& id) { Emit("media-started-playing"); } void WebContents::MediaStoppedPlaying( const MediaPlayerInfo& video_type, const content::MediaPlayerId& id, content::WebContentsObserver::MediaStoppedReason reason) { Emit("media-paused"); } void WebContents::DidChangeThemeColor() { auto theme_color = web_contents()->GetThemeColor(); if (theme_color) { Emit("did-change-theme-color", electron::ToRGBHex(theme_color.value())); } else { Emit("did-change-theme-color", nullptr); } } void WebContents::DidAcquireFullscreen(content::RenderFrameHost* rfh) { set_fullscreen_frame(rfh); } void WebContents::OnWebContentsFocused( content::RenderWidgetHost* render_widget_host) { Emit("focus"); } void WebContents::OnWebContentsLostFocus( content::RenderWidgetHost* render_widget_host) { Emit("blur"); } void WebContents::DOMContentLoaded( content::RenderFrameHost* render_frame_host) { auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host); if (web_frame) web_frame->DOMContentLoaded(); if (!render_frame_host->GetParent()) Emit("dom-ready"); } void WebContents::DidFinishLoad(content::RenderFrameHost* render_frame_host, const GURL& validated_url) { bool is_main_frame = !render_frame_host->GetParent(); int frame_process_id = render_frame_host->GetProcess()->GetID(); int frame_routing_id = render_frame_host->GetRoutingID(); auto weak_this = GetWeakPtr(); Emit("did-frame-finish-load", is_main_frame, frame_process_id, frame_routing_id); // ⚠️WARNING!⚠️ // Emit() triggers JS which can call destroy() on |this|. It's not safe to // assume that |this| points to valid memory at this point. if (is_main_frame && weak_this && web_contents()) Emit("did-finish-load"); } void WebContents::DidFailLoad(content::RenderFrameHost* render_frame_host, const GURL& url, int error_code) { bool is_main_frame = !render_frame_host->GetParent(); int frame_process_id = render_frame_host->GetProcess()->GetID(); int frame_routing_id = render_frame_host->GetRoutingID(); Emit("did-fail-load", error_code, "", url, is_main_frame, frame_process_id, frame_routing_id); } void WebContents::DidStartLoading() { Emit("did-start-loading"); } void WebContents::DidStopLoading() { auto* web_preferences = WebContentsPreferences::From(web_contents()); if (web_preferences && web_preferences->ShouldUsePreferredSizeMode()) web_contents()->GetRenderViewHost()->EnablePreferredSizeMode(); Emit("did-stop-loading"); } bool WebContents::EmitNavigationEvent( const std::string& event, content::NavigationHandle* navigation_handle) { bool is_main_frame = navigation_handle->IsInMainFrame(); int frame_tree_node_id = navigation_handle->GetFrameTreeNodeId(); content::FrameTreeNode* frame_tree_node = content::FrameTreeNode::GloballyFindByID(frame_tree_node_id); content::RenderFrameHostManager* render_manager = frame_tree_node->render_manager(); content::RenderFrameHost* frame_host = nullptr; if (render_manager) { frame_host = render_manager->speculative_frame_host(); if (!frame_host) frame_host = render_manager->current_frame_host(); } int frame_process_id = -1, frame_routing_id = -1; if (frame_host) { frame_process_id = frame_host->GetProcess()->GetID(); frame_routing_id = frame_host->GetRoutingID(); } bool is_same_document = navigation_handle->IsSameDocument(); auto url = navigation_handle->GetURL(); return Emit(event, url, is_same_document, is_main_frame, frame_process_id, frame_routing_id); } void WebContents::Message(bool internal, const std::string& channel, blink::CloneableMessage arguments, content::RenderFrameHost* render_frame_host) { TRACE_EVENT1("electron", "WebContents::Message", "channel", channel); // webContents.emit('-ipc-message', new Event(), internal, channel, // arguments); EmitWithSender("-ipc-message", render_frame_host, electron::mojom::ElectronApiIPC::InvokeCallback(), internal, channel, std::move(arguments)); } void WebContents::Invoke( bool internal, const std::string& channel, blink::CloneableMessage arguments, electron::mojom::ElectronApiIPC::InvokeCallback callback, content::RenderFrameHost* render_frame_host) { TRACE_EVENT1("electron", "WebContents::Invoke", "channel", channel); // webContents.emit('-ipc-invoke', new Event(), internal, channel, arguments); EmitWithSender("-ipc-invoke", render_frame_host, std::move(callback), internal, channel, std::move(arguments)); } void WebContents::OnFirstNonEmptyLayout( content::RenderFrameHost* render_frame_host) { if (render_frame_host == web_contents()->GetMainFrame()) { Emit("ready-to-show"); } } void WebContents::ReceivePostMessage( const std::string& channel, blink::TransferableMessage message, content::RenderFrameHost* render_frame_host) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); auto wrapped_ports = MessagePort::EntanglePorts(isolate, std::move(message.ports)); v8::Local<v8::Value> message_value = electron::DeserializeV8Value(isolate, message); EmitWithSender("-ipc-ports", render_frame_host, electron::mojom::ElectronApiIPC::InvokeCallback(), false, channel, message_value, std::move(wrapped_ports)); } void WebContents::MessageSync( bool internal, const std::string& channel, blink::CloneableMessage arguments, electron::mojom::ElectronApiIPC::MessageSyncCallback callback, content::RenderFrameHost* render_frame_host) { TRACE_EVENT1("electron", "WebContents::MessageSync", "channel", channel); // webContents.emit('-ipc-message-sync', new Event(sender, message), internal, // channel, arguments); EmitWithSender("-ipc-message-sync", render_frame_host, std::move(callback), internal, channel, std::move(arguments)); } void WebContents::MessageTo(int32_t web_contents_id, const std::string& channel, blink::CloneableMessage arguments) { TRACE_EVENT1("electron", "WebContents::MessageTo", "channel", channel); auto* target_web_contents = FromID(web_contents_id); if (target_web_contents) { content::RenderFrameHost* frame = target_web_contents->MainFrame(); DCHECK(frame); v8::HandleScope handle_scope(JavascriptEnvironment::GetIsolate()); gin::Handle<WebFrameMain> web_frame_main = WebFrameMain::From(JavascriptEnvironment::GetIsolate(), frame); if (!web_frame_main->CheckRenderFrame()) return; int32_t sender_id = ID(); web_frame_main->GetRendererApi()->Message(false /* internal */, channel, std::move(arguments), sender_id); } } void WebContents::MessageHost(const std::string& channel, blink::CloneableMessage arguments, content::RenderFrameHost* render_frame_host) { TRACE_EVENT1("electron", "WebContents::MessageHost", "channel", channel); // webContents.emit('ipc-message-host', new Event(), channel, args); EmitWithSender("ipc-message-host", render_frame_host, electron::mojom::ElectronApiIPC::InvokeCallback(), channel, std::move(arguments)); } void WebContents::UpdateDraggableRegions( std::vector<mojom::DraggableRegionPtr> regions) { for (ExtendedWebContentsObserver& observer : observers_) observer.OnDraggableRegionsUpdated(regions); } void WebContents::DidStartNavigation( content::NavigationHandle* navigation_handle) { EmitNavigationEvent("did-start-navigation", navigation_handle); } void WebContents::DidRedirectNavigation( content::NavigationHandle* navigation_handle) { EmitNavigationEvent("did-redirect-navigation", navigation_handle); } void WebContents::ReadyToCommitNavigation( content::NavigationHandle* navigation_handle) { // Don't focus content in an inactive window. if (!owner_window()) return; #if BUILDFLAG(IS_MAC) if (!owner_window()->IsActive()) return; #else if (!owner_window()->widget()->IsActive()) return; #endif // Don't focus content after subframe navigations. if (!navigation_handle->IsInMainFrame()) return; // Only focus for top-level contents. if (type_ != Type::kBrowserWindow) return; web_contents()->SetInitialFocus(); } void WebContents::DidFinishNavigation( content::NavigationHandle* navigation_handle) { if (owner_window_) { owner_window_->NotifyLayoutWindowControlsOverlay(); } if (!navigation_handle->HasCommitted()) return; bool is_main_frame = navigation_handle->IsInMainFrame(); content::RenderFrameHost* frame_host = navigation_handle->GetRenderFrameHost(); int frame_process_id = -1, frame_routing_id = -1; if (frame_host) { frame_process_id = frame_host->GetProcess()->GetID(); frame_routing_id = frame_host->GetRoutingID(); } if (!navigation_handle->IsErrorPage()) { // FIXME: All the Emit() calls below could potentially result in |this| // being destroyed (by JS listening for the event and calling // webContents.destroy()). auto url = navigation_handle->GetURL(); bool is_same_document = navigation_handle->IsSameDocument(); if (is_same_document) { Emit("did-navigate-in-page", url, is_main_frame, frame_process_id, frame_routing_id); } else { const net::HttpResponseHeaders* http_response = navigation_handle->GetResponseHeaders(); std::string http_status_text; int http_response_code = -1; if (http_response) { http_status_text = http_response->GetStatusText(); http_response_code = http_response->response_code(); } Emit("did-frame-navigate", url, http_response_code, http_status_text, is_main_frame, frame_process_id, frame_routing_id); if (is_main_frame) { Emit("did-navigate", url, http_response_code, http_status_text); } } if (IsGuest()) Emit("load-commit", url, is_main_frame); } else { auto url = navigation_handle->GetURL(); int code = navigation_handle->GetNetErrorCode(); auto description = net::ErrorToShortString(code); Emit("did-fail-provisional-load", code, description, url, is_main_frame, frame_process_id, frame_routing_id); // Do not emit "did-fail-load" for canceled requests. if (code != net::ERR_ABORTED) { EmitWarning( node::Environment::GetCurrent(JavascriptEnvironment::GetIsolate()), "Failed to load URL: " + url.possibly_invalid_spec() + " with error: " + description, "electron"); Emit("did-fail-load", code, description, url, is_main_frame, frame_process_id, frame_routing_id); } } content::NavigationEntry* entry = navigation_handle->GetNavigationEntry(); // This check is needed due to an issue in Chromium // Check the Chromium issue to keep updated: // https://bugs.chromium.org/p/chromium/issues/detail?id=1178663 // If a history entry has been made and the forward/back call has been made, // proceed with setting the new title if (entry && (entry->GetTransitionType() & ui::PAGE_TRANSITION_FORWARD_BACK)) WebContents::TitleWasSet(entry); } void WebContents::TitleWasSet(content::NavigationEntry* entry) { std::u16string final_title; bool explicit_set = true; if (entry) { auto title = entry->GetTitle(); auto url = entry->GetURL(); if (url.SchemeIsFile() && title.empty()) { final_title = base::UTF8ToUTF16(url.ExtractFileName()); explicit_set = false; } else { final_title = title; } } else { final_title = web_contents()->GetTitle(); } for (ExtendedWebContentsObserver& observer : observers_) observer.OnPageTitleUpdated(final_title, explicit_set); Emit("page-title-updated", final_title, explicit_set); } void WebContents::DidUpdateFaviconURL( content::RenderFrameHost* render_frame_host, const std::vector<blink::mojom::FaviconURLPtr>& urls) { std::set<GURL> unique_urls; for (const auto& iter : urls) { if (iter->icon_type != blink::mojom::FaviconIconType::kFavicon) continue; const GURL& url = iter->icon_url; if (url.is_valid()) unique_urls.insert(url); } Emit("page-favicon-updated", unique_urls); } void WebContents::DevToolsReloadPage() { Emit("devtools-reload-page"); } void WebContents::DevToolsFocused() { Emit("devtools-focused"); } void WebContents::DevToolsOpened() { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); DCHECK(inspectable_web_contents_); DCHECK(inspectable_web_contents_->GetDevToolsWebContents()); auto handle = FromOrCreate( isolate, inspectable_web_contents_->GetDevToolsWebContents()); devtools_web_contents_.Reset(isolate, handle.ToV8()); // Set inspected tabID. base::Value tab_id(ID()); inspectable_web_contents_->CallClientFunction("DevToolsAPI.setInspectedTabId", &tab_id, nullptr, nullptr); // Inherit owner window in devtools when it doesn't have one. auto* devtools = inspectable_web_contents_->GetDevToolsWebContents(); bool has_window = devtools->GetUserData(NativeWindowRelay::UserDataKey()); if (owner_window() && !has_window) handle->SetOwnerWindow(devtools, owner_window()); Emit("devtools-opened"); } void WebContents::DevToolsClosed() { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); devtools_web_contents_.Reset(); Emit("devtools-closed"); } void WebContents::DevToolsResized() { for (ExtendedWebContentsObserver& observer : observers_) observer.OnDevToolsResized(); } void WebContents::SetOwnerWindow(NativeWindow* owner_window) { SetOwnerWindow(GetWebContents(), owner_window); } void WebContents::SetOwnerWindow(content::WebContents* web_contents, NativeWindow* owner_window) { if (owner_window) { owner_window_ = owner_window->GetWeakPtr(); NativeWindowRelay::CreateForWebContents(web_contents, owner_window->GetWeakPtr()); } else { owner_window_ = nullptr; web_contents->RemoveUserData(NativeWindowRelay::UserDataKey()); } #if BUILDFLAG(ENABLE_OSR) auto* osr_wcv = GetOffScreenWebContentsView(); if (osr_wcv) osr_wcv->SetNativeWindow(owner_window); #endif } content::WebContents* WebContents::GetWebContents() const { if (!inspectable_web_contents_) return nullptr; return inspectable_web_contents_->GetWebContents(); } content::WebContents* WebContents::GetDevToolsWebContents() const { if (!inspectable_web_contents_) return nullptr; return inspectable_web_contents_->GetDevToolsWebContents(); } void WebContents::WebContentsDestroyed() { // Clear the pointer stored in wrapper. if (GetAllWebContents().Lookup(id_)) GetAllWebContents().Remove(id_); v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); v8::Local<v8::Object> wrapper; if (!GetWrapper(isolate).ToLocal(&wrapper)) return; wrapper->SetAlignedPointerInInternalField(0, nullptr); // Tell WebViewGuestDelegate that the WebContents has been destroyed. if (guest_delegate_) guest_delegate_->WillDestroy(); Observe(nullptr); Emit("destroyed"); } void WebContents::NavigationEntryCommitted( const content::LoadCommittedDetails& details) { Emit("navigation-entry-committed", details.entry->GetURL(), details.is_same_document, details.did_replace_entry); } bool WebContents::GetBackgroundThrottling() const { return background_throttling_; } void WebContents::SetBackgroundThrottling(bool allowed) { background_throttling_ = allowed; auto* rfh = web_contents()->GetMainFrame(); if (!rfh) return; auto* rwhv = rfh->GetView(); if (!rwhv) return; auto* rwh_impl = static_cast<content::RenderWidgetHostImpl*>(rwhv->GetRenderWidgetHost()); if (!rwh_impl) return; rwh_impl->disable_hidden_ = !background_throttling_; web_contents()->GetRenderViewHost()->SetSchedulerThrottling(allowed); if (rwh_impl->is_hidden()) { rwh_impl->WasShown({}); } } int WebContents::GetProcessID() const { return web_contents()->GetMainFrame()->GetProcess()->GetID(); } base::ProcessId WebContents::GetOSProcessID() const { base::ProcessHandle process_handle = web_contents()->GetMainFrame()->GetProcess()->GetProcess().Handle(); return base::GetProcId(process_handle); } WebContents::Type WebContents::GetType() const { return type_; } bool WebContents::Equal(const WebContents* web_contents) const { return ID() == web_contents->ID(); } GURL WebContents::GetURL() const { return web_contents()->GetLastCommittedURL(); } void WebContents::LoadURL(const GURL& url, const gin_helper::Dictionary& options) { if (!url.is_valid() || url.spec().size() > url::kMaxURLChars) { Emit("did-fail-load", static_cast<int>(net::ERR_INVALID_URL), net::ErrorToShortString(net::ERR_INVALID_URL), url.possibly_invalid_spec(), true); return; } content::NavigationController::LoadURLParams params(url); if (!options.Get("httpReferrer", &params.referrer)) { GURL http_referrer; if (options.Get("httpReferrer", &http_referrer)) params.referrer = content::Referrer(http_referrer.GetAsReferrer(), network::mojom::ReferrerPolicy::kDefault); } std::string user_agent; if (options.Get("userAgent", &user_agent)) web_contents()->SetUserAgentOverride( blink::UserAgentOverride::UserAgentOnly(user_agent), false); std::string extra_headers; if (options.Get("extraHeaders", &extra_headers)) params.extra_headers = extra_headers; scoped_refptr<network::ResourceRequestBody> body; if (options.Get("postData", &body)) { params.post_data = body; params.load_type = content::NavigationController::LOAD_TYPE_HTTP_POST; } GURL base_url_for_data_url; if (options.Get("baseURLForDataURL", &base_url_for_data_url)) { params.base_url_for_data_url = base_url_for_data_url; params.load_type = content::NavigationController::LOAD_TYPE_DATA; } bool reload_ignoring_cache = false; if (options.Get("reloadIgnoringCache", &reload_ignoring_cache) && reload_ignoring_cache) { params.reload_type = content::ReloadType::BYPASSING_CACHE; } // Calling LoadURLWithParams() can trigger JS which destroys |this|. auto weak_this = GetWeakPtr(); params.transition_type = ui::PageTransitionFromInt( ui::PAGE_TRANSITION_TYPED | ui::PAGE_TRANSITION_FROM_ADDRESS_BAR); params.override_user_agent = content::NavigationController::UA_OVERRIDE_TRUE; // Discord non-committed entries to ensure that we don't re-use a pending // entry web_contents()->GetController().DiscardNonCommittedEntries(); web_contents()->GetController().LoadURLWithParams(params); // ⚠️WARNING!⚠️ // LoadURLWithParams() triggers JS events which can call destroy() on |this|. // It's not safe to assume that |this| points to valid memory at this point. if (!weak_this || !web_contents()) return; // Required to make beforeunload handler work. NotifyUserActivation(); } // TODO(MarshallOfSound): Figure out what we need to do with post data here, I // believe the default behavior when we pass "true" is to phone out to the // delegate and then the controller expects this method to be called again with // "false" if the user approves the reload. For now this would result in // ".reload()" calls on POST data domains failing silently. Passing false would // result in them succeeding, but reposting which although more correct could be // considering a breaking change. void WebContents::Reload() { web_contents()->GetController().Reload(content::ReloadType::NORMAL, /* check_for_repost */ true); } void WebContents::ReloadIgnoringCache() { web_contents()->GetController().Reload(content::ReloadType::BYPASSING_CACHE, /* check_for_repost */ true); } void WebContents::DownloadURL(const GURL& url) { auto* browser_context = web_contents()->GetBrowserContext(); auto* download_manager = browser_context->GetDownloadManager(); std::unique_ptr<download::DownloadUrlParameters> download_params( content::DownloadRequestUtils::CreateDownloadForWebContentsMainFrame( web_contents(), url, MISSING_TRAFFIC_ANNOTATION)); download_manager->DownloadUrl(std::move(download_params)); } std::u16string WebContents::GetTitle() const { return web_contents()->GetTitle(); } bool WebContents::IsLoading() const { return web_contents()->IsLoading(); } bool WebContents::IsLoadingMainFrame() const { return web_contents()->ShouldShowLoadingUI(); } bool WebContents::IsWaitingForResponse() const { return web_contents()->IsWaitingForResponse(); } void WebContents::Stop() { web_contents()->Stop(); } bool WebContents::CanGoBack() const { return web_contents()->GetController().CanGoBack(); } void WebContents::GoBack() { if (CanGoBack()) web_contents()->GetController().GoBack(); } bool WebContents::CanGoForward() const { return web_contents()->GetController().CanGoForward(); } void WebContents::GoForward() { if (CanGoForward()) web_contents()->GetController().GoForward(); } bool WebContents::CanGoToOffset(int offset) const { return web_contents()->GetController().CanGoToOffset(offset); } void WebContents::GoToOffset(int offset) { if (CanGoToOffset(offset)) web_contents()->GetController().GoToOffset(offset); } bool WebContents::CanGoToIndex(int index) const { return index >= 0 && index < GetHistoryLength(); } void WebContents::GoToIndex(int index) { if (CanGoToIndex(index)) web_contents()->GetController().GoToIndex(index); } int WebContents::GetActiveIndex() const { return web_contents()->GetController().GetCurrentEntryIndex(); } void WebContents::ClearHistory() { // In some rare cases (normally while there is no real history) we are in a // state where we can't prune navigation entries if (web_contents()->GetController().CanPruneAllButLastCommitted()) { web_contents()->GetController().PruneAllButLastCommitted(); } } int WebContents::GetHistoryLength() const { return web_contents()->GetController().GetEntryCount(); } const std::string WebContents::GetWebRTCIPHandlingPolicy() const { return web_contents()->GetMutableRendererPrefs()->webrtc_ip_handling_policy; } void WebContents::SetWebRTCIPHandlingPolicy( const std::string& webrtc_ip_handling_policy) { if (GetWebRTCIPHandlingPolicy() == webrtc_ip_handling_policy) return; web_contents()->GetMutableRendererPrefs()->webrtc_ip_handling_policy = webrtc_ip_handling_policy; web_contents()->SyncRendererPrefs(); } std::string WebContents::GetMediaSourceID( content::WebContents* request_web_contents) { auto* frame_host = web_contents()->GetMainFrame(); if (!frame_host) return std::string(); content::DesktopMediaID media_id( content::DesktopMediaID::TYPE_WEB_CONTENTS, content::DesktopMediaID::kNullId, content::WebContentsMediaCaptureId(frame_host->GetProcess()->GetID(), frame_host->GetRoutingID())); auto* request_frame_host = request_web_contents->GetMainFrame(); if (!request_frame_host) return std::string(); std::string id = content::DesktopStreamsRegistry::GetInstance()->RegisterStream( request_frame_host->GetProcess()->GetID(), request_frame_host->GetRoutingID(), url::Origin::Create(request_frame_host->GetLastCommittedURL() .DeprecatedGetOriginAsURL()), media_id, "", content::kRegistryStreamTypeTab); return id; } bool WebContents::IsCrashed() const { return web_contents()->IsCrashed(); } void WebContents::ForcefullyCrashRenderer() { content::RenderWidgetHostView* view = web_contents()->GetRenderWidgetHostView(); if (!view) return; content::RenderWidgetHost* rwh = view->GetRenderWidgetHost(); if (!rwh) return; content::RenderProcessHost* rph = rwh->GetProcess(); if (rph) { #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) // A generic |CrashDumpHungChildProcess()| is not implemented for Linux. // Instead we send an explicit IPC to crash on the renderer's IO thread. rph->ForceCrash(); #else // Try to generate a crash report for the hung process. #ifndef MAS_BUILD CrashDumpHungChildProcess(rph->GetProcess().Handle()); #endif rph->Shutdown(content::RESULT_CODE_HUNG); #endif } } void WebContents::SetUserAgent(const std::string& user_agent) { web_contents()->SetUserAgentOverride( blink::UserAgentOverride::UserAgentOnly(user_agent), false); } std::string WebContents::GetUserAgent() { return web_contents()->GetUserAgentOverride().ua_string_override; } v8::Local<v8::Promise> WebContents::SavePage( const base::FilePath& full_file_path, const content::SavePageType& save_type) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); gin_helper::Promise<void> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); if (!full_file_path.IsAbsolute()) { promise.RejectWithErrorMessage("Path must be absolute"); return handle; } auto* handler = new SavePageHandler(web_contents(), std::move(promise)); handler->Handle(full_file_path, save_type); return handle; } void WebContents::OpenDevTools(gin::Arguments* args) { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; std::string state; if (type_ == Type::kWebView || type_ == Type::kBackgroundPage || !owner_window()) { state = "detach"; } bool activate = true; if (args && args->Length() == 1) { gin_helper::Dictionary options; if (args->GetNext(&options)) { options.Get("mode", &state); options.Get("activate", &activate); } } DCHECK(inspectable_web_contents_); inspectable_web_contents_->SetDockState(state); inspectable_web_contents_->ShowDevTools(activate); } void WebContents::CloseDevTools() { if (type_ == Type::kRemote) return; DCHECK(inspectable_web_contents_); inspectable_web_contents_->CloseDevTools(); } bool WebContents::IsDevToolsOpened() { if (type_ == Type::kRemote) return false; DCHECK(inspectable_web_contents_); return inspectable_web_contents_->IsDevToolsViewShowing(); } bool WebContents::IsDevToolsFocused() { if (type_ == Type::kRemote) return false; DCHECK(inspectable_web_contents_); return inspectable_web_contents_->GetView()->IsDevToolsViewFocused(); } void WebContents::EnableDeviceEmulation( const blink::DeviceEmulationParams& params) { if (type_ == Type::kRemote) return; DCHECK(web_contents()); auto* frame_host = web_contents()->GetMainFrame(); if (frame_host) { auto* widget_host_impl = static_cast<content::RenderWidgetHostImpl*>( frame_host->GetView()->GetRenderWidgetHost()); if (widget_host_impl) { auto& frame_widget = widget_host_impl->GetAssociatedFrameWidget(); frame_widget->EnableDeviceEmulation(params); } } } void WebContents::DisableDeviceEmulation() { if (type_ == Type::kRemote) return; DCHECK(web_contents()); auto* frame_host = web_contents()->GetMainFrame(); if (frame_host) { auto* widget_host_impl = static_cast<content::RenderWidgetHostImpl*>( frame_host->GetView()->GetRenderWidgetHost()); if (widget_host_impl) { auto& frame_widget = widget_host_impl->GetAssociatedFrameWidget(); frame_widget->DisableDeviceEmulation(); } } } void WebContents::ToggleDevTools() { if (IsDevToolsOpened()) CloseDevTools(); else OpenDevTools(nullptr); } void WebContents::InspectElement(int x, int y) { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; DCHECK(inspectable_web_contents_); if (!inspectable_web_contents_->GetDevToolsWebContents()) OpenDevTools(nullptr); inspectable_web_contents_->InspectElement(x, y); } void WebContents::InspectSharedWorkerById(const std::string& workerId) { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) { if (agent_host->GetType() == content::DevToolsAgentHost::kTypeSharedWorker) { if (agent_host->GetId() == workerId) { OpenDevTools(nullptr); inspectable_web_contents_->AttachTo(agent_host); break; } } } } std::vector<scoped_refptr<content::DevToolsAgentHost>> WebContents::GetAllSharedWorkers() { std::vector<scoped_refptr<content::DevToolsAgentHost>> shared_workers; if (type_ == Type::kRemote) return shared_workers; if (!enable_devtools_) return shared_workers; for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) { if (agent_host->GetType() == content::DevToolsAgentHost::kTypeSharedWorker) { shared_workers.push_back(agent_host); } } return shared_workers; } void WebContents::InspectSharedWorker() { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) { if (agent_host->GetType() == content::DevToolsAgentHost::kTypeSharedWorker) { OpenDevTools(nullptr); inspectable_web_contents_->AttachTo(agent_host); break; } } } void WebContents::InspectServiceWorker() { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) { if (agent_host->GetType() == content::DevToolsAgentHost::kTypeServiceWorker) { OpenDevTools(nullptr); inspectable_web_contents_->AttachTo(agent_host); break; } } } void WebContents::SetIgnoreMenuShortcuts(bool ignore) { auto* web_preferences = WebContentsPreferences::From(web_contents()); DCHECK(web_preferences); web_preferences->SetIgnoreMenuShortcuts(ignore); } void WebContents::SetAudioMuted(bool muted) { web_contents()->SetAudioMuted(muted); } bool WebContents::IsAudioMuted() { return web_contents()->IsAudioMuted(); } bool WebContents::IsCurrentlyAudible() { return web_contents()->IsCurrentlyAudible(); } #if BUILDFLAG(ENABLE_PRINTING) void WebContents::OnGetDefaultPrinter( base::Value print_settings, printing::CompletionCallback print_callback, std::u16string device_name, bool silent, // <error, default_printer> std::pair<std::string, std::u16string> info) { // The content::WebContents might be already deleted at this point, and the // PrintViewManagerElectron class does not do null check. if (!web_contents()) { if (print_callback) std::move(print_callback).Run(false, "failed"); return; } if (!info.first.empty()) { if (print_callback) std::move(print_callback).Run(false, info.first); return; } // If the user has passed a deviceName use it, otherwise use default printer. std::u16string printer_name = device_name.empty() ? info.second : device_name; // If there are no valid printers available on the network, we bail. if (printer_name.empty() || !IsDeviceNameValid(printer_name)) { if (print_callback) std::move(print_callback).Run(false, "no valid printers available"); return; } print_settings.SetStringKey(printing::kSettingDeviceName, printer_name); auto* print_view_manager = PrintViewManagerElectron::FromWebContents(web_contents()); if (!print_view_manager) return; auto* focused_frame = web_contents()->GetFocusedFrame(); auto* rfh = focused_frame && focused_frame->HasSelection() ? focused_frame : web_contents()->GetMainFrame(); print_view_manager->PrintNow(rfh, silent, std::move(print_settings), std::move(print_callback)); } void WebContents::Print(gin::Arguments* args) { gin_helper::Dictionary options = gin::Dictionary::CreateEmpty(args->isolate()); base::Value settings(base::Value::Type::DICTIONARY); if (args->Length() >= 1 && !args->GetNext(&options)) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("webContents.print(): Invalid print settings specified."); return; } printing::CompletionCallback callback; if (args->Length() == 2 && !args->GetNext(&callback)) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("webContents.print(): Invalid optional callback provided."); return; } // Set optional silent printing bool silent = false; options.Get("silent", &silent); bool print_background = false; options.Get("printBackground", &print_background); settings.SetBoolKey(printing::kSettingShouldPrintBackgrounds, print_background); // Set custom margin settings gin_helper::Dictionary margins = gin::Dictionary::CreateEmpty(args->isolate()); if (options.Get("margins", &margins)) { printing::mojom::MarginType margin_type = printing::mojom::MarginType::kDefaultMargins; margins.Get("marginType", &margin_type); settings.SetIntKey(printing::kSettingMarginsType, static_cast<int>(margin_type)); if (margin_type == printing::mojom::MarginType::kCustomMargins) { base::Value custom_margins(base::Value::Type::DICTIONARY); int top = 0; margins.Get("top", &top); custom_margins.SetIntKey(printing::kSettingMarginTop, top); int bottom = 0; margins.Get("bottom", &bottom); custom_margins.SetIntKey(printing::kSettingMarginBottom, bottom); int left = 0; margins.Get("left", &left); custom_margins.SetIntKey(printing::kSettingMarginLeft, left); int right = 0; margins.Get("right", &right); custom_margins.SetIntKey(printing::kSettingMarginRight, right); settings.SetPath(printing::kSettingMarginsCustom, std::move(custom_margins)); } } else { settings.SetIntKey( printing::kSettingMarginsType, static_cast<int>(printing::mojom::MarginType::kDefaultMargins)); } // Set whether to print color or greyscale bool print_color = true; options.Get("color", &print_color); auto const color_model = print_color ? printing::mojom::ColorModel::kColor : printing::mojom::ColorModel::kGray; settings.SetIntKey(printing::kSettingColor, static_cast<int>(color_model)); // Is the orientation landscape or portrait. bool landscape = false; options.Get("landscape", &landscape); settings.SetBoolKey(printing::kSettingLandscape, landscape); // We set the default to the system's default printer and only update // if at the Chromium level if the user overrides. // Printer device name as opened by the OS. std::u16string device_name; options.Get("deviceName", &device_name); if (!device_name.empty() && !IsDeviceNameValid(device_name)) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("webContents.print(): Invalid deviceName provided."); return; } int scale_factor = 100; options.Get("scaleFactor", &scale_factor); settings.SetIntKey(printing::kSettingScaleFactor, scale_factor); int pages_per_sheet = 1; options.Get("pagesPerSheet", &pages_per_sheet); settings.SetIntKey(printing::kSettingPagesPerSheet, pages_per_sheet); // True if the user wants to print with collate. bool collate = true; options.Get("collate", &collate); settings.SetBoolKey(printing::kSettingCollate, collate); // The number of individual copies to print int copies = 1; options.Get("copies", &copies); settings.SetIntKey(printing::kSettingCopies, copies); // Strings to be printed as headers and footers if requested by the user. std::string header; options.Get("header", &header); std::string footer; options.Get("footer", &footer); if (!(header.empty() && footer.empty())) { settings.SetBoolKey(printing::kSettingHeaderFooterEnabled, true); settings.SetStringKey(printing::kSettingHeaderFooterTitle, header); settings.SetStringKey(printing::kSettingHeaderFooterURL, footer); } else { settings.SetBoolKey(printing::kSettingHeaderFooterEnabled, false); } // We don't want to allow the user to enable these settings // but we need to set them or a CHECK is hit. settings.SetIntKey(printing::kSettingPrinterType, static_cast<int>(printing::mojom::PrinterType::kLocal)); settings.SetBoolKey(printing::kSettingShouldPrintSelectionOnly, false); settings.SetBoolKey(printing::kSettingRasterizePdf, false); // Set custom page ranges to print std::vector<gin_helper::Dictionary> page_ranges; if (options.Get("pageRanges", &page_ranges)) { base::Value page_range_list(base::Value::Type::LIST); for (auto& range : page_ranges) { int from, to; if (range.Get("from", &from) && range.Get("to", &to)) { base::Value range(base::Value::Type::DICTIONARY); // Chromium uses 1-based page ranges, so increment each by 1. range.SetIntKey(printing::kSettingPageRangeFrom, from + 1); range.SetIntKey(printing::kSettingPageRangeTo, to + 1); page_range_list.Append(std::move(range)); } else { continue; } } if (!page_range_list.GetListDeprecated().empty()) settings.SetPath(printing::kSettingPageRange, std::move(page_range_list)); } // Duplex type user wants to use. printing::mojom::DuplexMode duplex_mode = printing::mojom::DuplexMode::kSimplex; options.Get("duplexMode", &duplex_mode); settings.SetIntKey(printing::kSettingDuplexMode, static_cast<int>(duplex_mode)); // We've already done necessary parameter sanitization at the // JS level, so we can simply pass this through. base::Value media_size(base::Value::Type::DICTIONARY); if (options.Get("mediaSize", &media_size)) settings.SetKey(printing::kSettingMediaSize, std::move(media_size)); // Set custom dots per inch (dpi) gin_helper::Dictionary dpi_settings; int dpi = 72; if (options.Get("dpi", &dpi_settings)) { int horizontal = 72; dpi_settings.Get("horizontal", &horizontal); settings.SetIntKey(printing::kSettingDpiHorizontal, horizontal); int vertical = 72; dpi_settings.Get("vertical", &vertical); settings.SetIntKey(printing::kSettingDpiVertical, vertical); } else { settings.SetIntKey(printing::kSettingDpiHorizontal, dpi); settings.SetIntKey(printing::kSettingDpiVertical, dpi); } print_task_runner_->PostTaskAndReplyWithResult( FROM_HERE, base::BindOnce(&GetDefaultPrinterAsync), base::BindOnce(&WebContents::OnGetDefaultPrinter, weak_factory_.GetWeakPtr(), std::move(settings), std::move(callback), device_name, silent)); } v8::Local<v8::Promise> WebContents::PrintToPDF(base::DictionaryValue settings) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); gin_helper::Promise<v8::Local<v8::Value>> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); PrintPreviewMessageHandler::FromWebContents(web_contents()) ->PrintToPDF(std::move(settings), std::move(promise)); return handle; } #endif void WebContents::AddWorkSpace(gin::Arguments* args, const base::FilePath& path) { if (path.empty()) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("path cannot be empty"); return; } DevToolsAddFileSystem(std::string(), path); } void WebContents::RemoveWorkSpace(gin::Arguments* args, const base::FilePath& path) { if (path.empty()) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("path cannot be empty"); return; } DevToolsRemoveFileSystem(path); } void WebContents::Undo() { web_contents()->Undo(); } void WebContents::Redo() { web_contents()->Redo(); } void WebContents::Cut() { web_contents()->Cut(); } void WebContents::Copy() { web_contents()->Copy(); } void WebContents::Paste() { web_contents()->Paste(); } void WebContents::PasteAndMatchStyle() { web_contents()->PasteAndMatchStyle(); } void WebContents::Delete() { web_contents()->Delete(); } void WebContents::SelectAll() { web_contents()->SelectAll(); } void WebContents::Unselect() { web_contents()->CollapseSelection(); } void WebContents::Replace(const std::u16string& word) { web_contents()->Replace(word); } void WebContents::ReplaceMisspelling(const std::u16string& word) { web_contents()->ReplaceMisspelling(word); } uint32_t WebContents::FindInPage(gin::Arguments* args) { std::u16string search_text; if (!args->GetNext(&search_text) || search_text.empty()) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("Must provide a non-empty search content"); return 0; } uint32_t request_id = ++find_in_page_request_id_; gin_helper::Dictionary dict; auto options = blink::mojom::FindOptions::New(); if (args->GetNext(&dict)) { dict.Get("forward", &options->forward); dict.Get("matchCase", &options->match_case); dict.Get("findNext", &options->new_session); } web_contents()->Find(request_id, search_text, std::move(options)); return request_id; } void WebContents::StopFindInPage(content::StopFindAction action) { web_contents()->StopFinding(action); } void WebContents::ShowDefinitionForSelection() { #if BUILDFLAG(IS_MAC) auto* const view = web_contents()->GetRenderWidgetHostView(); if (view) view->ShowDefinitionForSelection(); #endif } void WebContents::CopyImageAt(int x, int y) { auto* const host = web_contents()->GetMainFrame(); if (host) host->CopyImageAt(x, y); } void WebContents::Focus() { // Focusing on WebContents does not automatically focus the window on macOS // and Linux, do it manually to match the behavior on Windows. #if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX) if (owner_window()) owner_window()->Focus(true); #endif web_contents()->Focus(); } #if !BUILDFLAG(IS_MAC) bool WebContents::IsFocused() const { auto* view = web_contents()->GetRenderWidgetHostView(); if (!view) return false; if (GetType() != Type::kBackgroundPage) { auto* window = web_contents()->GetNativeView()->GetToplevelWindow(); if (window && !window->IsVisible()) return false; } return view->HasFocus(); } #endif void WebContents::SendInputEvent(v8::Isolate* isolate, v8::Local<v8::Value> input_event) { content::RenderWidgetHostView* view = web_contents()->GetRenderWidgetHostView(); if (!view) return; content::RenderWidgetHost* rwh = view->GetRenderWidgetHost(); blink::WebInputEvent::Type type = gin::GetWebInputEventType(isolate, input_event); if (blink::WebInputEvent::IsMouseEventType(type)) { blink::WebMouseEvent mouse_event; if (gin::ConvertFromV8(isolate, input_event, &mouse_event)) { if (IsOffScreen()) { #if BUILDFLAG(ENABLE_OSR) GetOffScreenRenderWidgetHostView()->SendMouseEvent(mouse_event); #endif } else { rwh->ForwardMouseEvent(mouse_event); } return; } } else if (blink::WebInputEvent::IsKeyboardEventType(type)) { content::NativeWebKeyboardEvent keyboard_event( blink::WebKeyboardEvent::Type::kRawKeyDown, blink::WebInputEvent::Modifiers::kNoModifiers, ui::EventTimeForNow()); if (gin::ConvertFromV8(isolate, input_event, &keyboard_event)) { rwh->ForwardKeyboardEvent(keyboard_event); return; } } else if (type == blink::WebInputEvent::Type::kMouseWheel) { blink::WebMouseWheelEvent mouse_wheel_event; if (gin::ConvertFromV8(isolate, input_event, &mouse_wheel_event)) { if (IsOffScreen()) { #if BUILDFLAG(ENABLE_OSR) GetOffScreenRenderWidgetHostView()->SendMouseWheelEvent( mouse_wheel_event); #endif } else { // Chromium expects phase info in wheel events (and applies a // DCHECK to verify it). See: https://crbug.com/756524. mouse_wheel_event.phase = blink::WebMouseWheelEvent::kPhaseBegan; mouse_wheel_event.dispatch_type = blink::WebInputEvent::DispatchType::kBlocking; rwh->ForwardWheelEvent(mouse_wheel_event); // Send a synthetic wheel event with phaseEnded to finish scrolling. mouse_wheel_event.has_synthetic_phase = true; mouse_wheel_event.delta_x = 0; mouse_wheel_event.delta_y = 0; mouse_wheel_event.phase = blink::WebMouseWheelEvent::kPhaseEnded; mouse_wheel_event.dispatch_type = blink::WebInputEvent::DispatchType::kEventNonBlocking; rwh->ForwardWheelEvent(mouse_wheel_event); } return; } } isolate->ThrowException( v8::Exception::Error(gin::StringToV8(isolate, "Invalid event object"))); } void WebContents::BeginFrameSubscription(gin::Arguments* args) { bool only_dirty = false; FrameSubscriber::FrameCaptureCallback callback; if (args->Length() > 1) { if (!args->GetNext(&only_dirty)) { args->ThrowError(); return; } } if (!args->GetNext(&callback)) { args->ThrowError(); return; } frame_subscriber_ = std::make_unique<FrameSubscriber>(web_contents(), callback, only_dirty); } void WebContents::EndFrameSubscription() { frame_subscriber_.reset(); } void WebContents::StartDrag(const gin_helper::Dictionary& item, gin::Arguments* args) { base::FilePath file; std::vector<base::FilePath> files; if (!item.Get("files", &files) && item.Get("file", &file)) { files.push_back(file); } v8::Local<v8::Value> icon_value; if (!item.Get("icon", &icon_value)) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("'icon' parameter is required"); return; } NativeImage* icon = nullptr; if (!NativeImage::TryConvertNativeImage(args->isolate(), icon_value, &icon) || icon->image().IsEmpty()) { return; } // Start dragging. if (!files.empty()) { base::CurrentThread::ScopedNestableTaskAllower allow; DragFileItems(files, icon->image(), web_contents()->GetNativeView()); } else { gin_helper::ErrorThrower(args->isolate()) .ThrowError("Must specify either 'file' or 'files' option"); } } v8::Local<v8::Promise> WebContents::CapturePage(gin::Arguments* args) { gfx::Rect rect; gin_helper::Promise<gfx::Image> promise(args->isolate()); v8::Local<v8::Promise> handle = promise.GetHandle(); // get rect arguments if they exist args->GetNext(&rect); auto* const view = web_contents()->GetRenderWidgetHostView(); if (!view) { promise.Resolve(gfx::Image()); return handle; } #if !BUILDFLAG(IS_MAC) // If the view's renderer is suspended this may fail on Windows/Linux - // bail if so. See CopyFromSurface in // content/public/browser/render_widget_host_view.h. auto* rfh = web_contents()->GetMainFrame(); if (rfh && rfh->GetVisibilityState() == blink::mojom::PageVisibilityState::kHidden) { promise.Resolve(gfx::Image()); return handle; } #endif // BUILDFLAG(IS_MAC) // Capture full page if user doesn't specify a |rect|. const gfx::Size view_size = rect.IsEmpty() ? view->GetViewBounds().size() : rect.size(); // By default, the requested bitmap size is the view size in screen // coordinates. However, if there's more pixel detail available on the // current system, increase the requested bitmap size to capture it all. gfx::Size bitmap_size = view_size; const gfx::NativeView native_view = view->GetNativeView(); const float scale = display::Screen::GetScreen() ->GetDisplayNearestView(native_view) .device_scale_factor(); if (scale > 1.0f) bitmap_size = gfx::ScaleToCeiledSize(view_size, scale); view->CopyFromSurface(gfx::Rect(rect.origin(), view_size), bitmap_size, base::BindOnce(&OnCapturePageDone, std::move(promise))); return handle; } void WebContents::IncrementCapturerCount(gin::Arguments* args) { gfx::Size size; bool stay_hidden = false; bool stay_awake = false; // get size arguments if they exist args->GetNext(&size); // get stayHidden arguments if they exist args->GetNext(&stay_hidden); // get stayAwake arguments if they exist args->GetNext(&stay_awake); std::ignore = web_contents() ->IncrementCapturerCount(size, stay_hidden, stay_awake) .Release(); } void WebContents::DecrementCapturerCount(gin::Arguments* args) { bool stay_hidden = false; bool stay_awake = false; // get stayHidden arguments if they exist args->GetNext(&stay_hidden); // get stayAwake arguments if they exist args->GetNext(&stay_awake); web_contents()->DecrementCapturerCount(stay_hidden, stay_awake); } bool WebContents::IsBeingCaptured() { return web_contents()->IsBeingCaptured(); } void WebContents::OnCursorChanged(const content::WebCursor& webcursor) { const ui::Cursor& cursor = webcursor.cursor(); if (cursor.type() == ui::mojom::CursorType::kCustom) { Emit("cursor-changed", CursorTypeToString(cursor), gfx::Image::CreateFrom1xBitmap(cursor.custom_bitmap()), cursor.image_scale_factor(), gfx::Size(cursor.custom_bitmap().width(), cursor.custom_bitmap().height()), cursor.custom_hotspot()); } else { Emit("cursor-changed", CursorTypeToString(cursor)); } } bool WebContents::IsGuest() const { return type_ == Type::kWebView; } void WebContents::AttachToIframe(content::WebContents* embedder_web_contents, int embedder_frame_id) { attached_ = true; if (guest_delegate_) guest_delegate_->AttachToIframe(embedder_web_contents, embedder_frame_id); } bool WebContents::IsOffScreen() const { #if BUILDFLAG(ENABLE_OSR) return type_ == Type::kOffScreen; #else return false; #endif } #if BUILDFLAG(ENABLE_OSR) void WebContents::OnPaint(const gfx::Rect& dirty_rect, const SkBitmap& bitmap) { Emit("paint", dirty_rect, gfx::Image::CreateFrom1xBitmap(bitmap)); } void WebContents::StartPainting() { auto* osr_wcv = GetOffScreenWebContentsView(); if (osr_wcv) osr_wcv->SetPainting(true); } void WebContents::StopPainting() { auto* osr_wcv = GetOffScreenWebContentsView(); if (osr_wcv) osr_wcv->SetPainting(false); } bool WebContents::IsPainting() const { auto* osr_wcv = GetOffScreenWebContentsView(); return osr_wcv && osr_wcv->IsPainting(); } void WebContents::SetFrameRate(int frame_rate) { auto* osr_wcv = GetOffScreenWebContentsView(); if (osr_wcv) osr_wcv->SetFrameRate(frame_rate); } int WebContents::GetFrameRate() const { auto* osr_wcv = GetOffScreenWebContentsView(); return osr_wcv ? osr_wcv->GetFrameRate() : 0; } #endif void WebContents::Invalidate() { if (IsOffScreen()) { #if BUILDFLAG(ENABLE_OSR) auto* osr_rwhv = GetOffScreenRenderWidgetHostView(); if (osr_rwhv) osr_rwhv->Invalidate(); #endif } else { auto* const window = owner_window(); if (window) window->Invalidate(); } } gfx::Size WebContents::GetSizeForNewRenderView(content::WebContents* wc) { if (IsOffScreen() && wc == web_contents()) { auto* relay = NativeWindowRelay::FromWebContents(web_contents()); if (relay) { auto* owner_window = relay->GetNativeWindow(); return owner_window ? owner_window->GetSize() : gfx::Size(); } } return gfx::Size(); } void WebContents::SetZoomLevel(double level) { zoom_controller_->SetZoomLevel(level); } double WebContents::GetZoomLevel() const { return zoom_controller_->GetZoomLevel(); } void WebContents::SetZoomFactor(gin_helper::ErrorThrower thrower, double factor) { if (factor < std::numeric_limits<double>::epsilon()) { thrower.ThrowError("'zoomFactor' must be a double greater than 0.0"); return; } auto level = blink::PageZoomFactorToZoomLevel(factor); SetZoomLevel(level); } double WebContents::GetZoomFactor() const { auto level = GetZoomLevel(); return blink::PageZoomLevelToZoomFactor(level); } void WebContents::SetTemporaryZoomLevel(double level) { zoom_controller_->SetTemporaryZoomLevel(level); } void WebContents::DoGetZoomLevel( electron::mojom::ElectronWebContentsUtility::DoGetZoomLevelCallback callback) { std::move(callback).Run(GetZoomLevel()); } std::vector<base::FilePath> WebContents::GetPreloadPaths() const { auto result = SessionPreferences::GetValidPreloads(GetBrowserContext()); if (auto* web_preferences = WebContentsPreferences::From(web_contents())) { base::FilePath preload; if (web_preferences->GetPreloadPath(&preload)) { result.emplace_back(preload); } } return result; } v8::Local<v8::Value> WebContents::GetLastWebPreferences( v8::Isolate* isolate) const { auto* web_preferences = WebContentsPreferences::From(web_contents()); if (!web_preferences) return v8::Null(isolate); return gin::ConvertToV8(isolate, *web_preferences->last_preference()); } v8::Local<v8::Value> WebContents::GetOwnerBrowserWindow( v8::Isolate* isolate) const { if (owner_window()) return BrowserWindow::From(isolate, owner_window()); else return v8::Null(isolate); } v8::Local<v8::Value> WebContents::Session(v8::Isolate* isolate) { return v8::Local<v8::Value>::New(isolate, session_); } content::WebContents* WebContents::HostWebContents() const { if (!embedder_) return nullptr; return embedder_->web_contents(); } void WebContents::SetEmbedder(const WebContents* embedder) { if (embedder) { NativeWindow* owner_window = nullptr; auto* relay = NativeWindowRelay::FromWebContents(embedder->web_contents()); if (relay) { owner_window = relay->GetNativeWindow(); } if (owner_window) SetOwnerWindow(owner_window); content::RenderWidgetHostView* rwhv = web_contents()->GetRenderWidgetHostView(); if (rwhv) { rwhv->Hide(); rwhv->Show(); } } } void WebContents::SetDevToolsWebContents(const WebContents* devtools) { if (inspectable_web_contents_) inspectable_web_contents_->SetDevToolsWebContents(devtools->web_contents()); } v8::Local<v8::Value> WebContents::GetNativeView(v8::Isolate* isolate) const { gfx::NativeView ptr = web_contents()->GetNativeView(); auto buffer = node::Buffer::Copy(isolate, reinterpret_cast<char*>(&ptr), sizeof(gfx::NativeView)); if (buffer.IsEmpty()) return v8::Null(isolate); else return buffer.ToLocalChecked(); } v8::Local<v8::Value> WebContents::DevToolsWebContents(v8::Isolate* isolate) { if (devtools_web_contents_.IsEmpty()) return v8::Null(isolate); else return v8::Local<v8::Value>::New(isolate, devtools_web_contents_); } v8::Local<v8::Value> WebContents::Debugger(v8::Isolate* isolate) { if (debugger_.IsEmpty()) { auto handle = electron::api::Debugger::Create(isolate, web_contents()); debugger_.Reset(isolate, handle.ToV8()); } return v8::Local<v8::Value>::New(isolate, debugger_); } content::RenderFrameHost* WebContents::MainFrame() { return web_contents()->GetMainFrame(); } void WebContents::NotifyUserActivation() { content::RenderFrameHost* frame = web_contents()->GetMainFrame(); if (frame) frame->NotifyUserActivation( blink::mojom::UserActivationNotificationType::kInteraction); } void WebContents::SetImageAnimationPolicy(const std::string& new_policy) { auto* web_preferences = WebContentsPreferences::From(web_contents()); web_preferences->SetImageAnimationPolicy(new_policy); web_contents()->OnWebPreferencesChanged(); } v8::Local<v8::Promise> WebContents::GetProcessMemoryInfo(v8::Isolate* isolate) { gin_helper::Promise<gin_helper::Dictionary> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); auto* frame_host = web_contents()->GetMainFrame(); if (!frame_host) { promise.RejectWithErrorMessage("Failed to create memory dump"); return handle; } auto pid = frame_host->GetProcess()->GetProcess().Pid(); v8::Global<v8::Context> context(isolate, isolate->GetCurrentContext()); memory_instrumentation::MemoryInstrumentation::GetInstance() ->RequestGlobalDumpForPid( pid, std::vector<std::string>(), base::BindOnce(&ElectronBindings::DidReceiveMemoryDump, std::move(context), std::move(promise), pid)); return handle; } v8::Local<v8::Promise> WebContents::TakeHeapSnapshot( v8::Isolate* isolate, const base::FilePath& file_path) { gin_helper::Promise<void> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); base::ThreadRestrictions::ScopedAllowIO allow_io; base::File file(file_path, base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE); if (!file.IsValid()) { promise.RejectWithErrorMessage("takeHeapSnapshot failed"); return handle; } auto* frame_host = web_contents()->GetMainFrame(); if (!frame_host) { promise.RejectWithErrorMessage("takeHeapSnapshot failed"); return handle; } if (!frame_host->IsRenderFrameCreated()) { promise.RejectWithErrorMessage("takeHeapSnapshot failed"); return handle; } // This dance with `base::Owned` is to ensure that the interface stays alive // until the callback is called. Otherwise it would be closed at the end of // this function. auto electron_renderer = std::make_unique<mojo::Remote<mojom::ElectronRenderer>>(); frame_host->GetRemoteInterfaces()->GetInterface( electron_renderer->BindNewPipeAndPassReceiver()); auto* raw_ptr = electron_renderer.get(); (*raw_ptr)->TakeHeapSnapshot( mojo::WrapPlatformFile(base::ScopedPlatformFile(file.TakePlatformFile())), base::BindOnce( [](mojo::Remote<mojom::ElectronRenderer>* ep, gin_helper::Promise<void> promise, bool success) { if (success) { promise.Resolve(); } else { promise.RejectWithErrorMessage("takeHeapSnapshot failed"); } }, base::Owned(std::move(electron_renderer)), std::move(promise))); return handle; } void WebContents::GrantDevicePermission( const url::Origin& origin, const base::Value* device, blink::PermissionType permissionType, content::RenderFrameHost* render_frame_host) { granted_devices_[render_frame_host->GetFrameTreeNodeId()][permissionType] [origin] .push_back( std::make_unique<base::Value>(device->Clone())); } std::vector<base::Value> WebContents::GetGrantedDevices( const url::Origin& origin, blink::PermissionType permissionType, content::RenderFrameHost* render_frame_host) { const auto& devices_for_frame_host_it = granted_devices_.find(render_frame_host->GetFrameTreeNodeId()); if (devices_for_frame_host_it == granted_devices_.end()) return {}; const auto& current_devices_it = devices_for_frame_host_it->second.find(permissionType); if (current_devices_it == devices_for_frame_host_it->second.end()) return {}; const auto& origin_devices_it = current_devices_it->second.find(origin); if (origin_devices_it == current_devices_it->second.end()) return {}; std::vector<base::Value> results; for (const auto& object : origin_devices_it->second) results.push_back(object->Clone()); return results; } void WebContents::UpdatePreferredSize(content::WebContents* web_contents, const gfx::Size& pref_size) { Emit("preferred-size-changed", pref_size); } bool WebContents::CanOverscrollContent() { return false; } std::unique_ptr<content::EyeDropper> WebContents::OpenEyeDropper( content::RenderFrameHost* frame, content::EyeDropperListener* listener) { return ShowEyeDropper(frame, listener); } void WebContents::RunFileChooser( content::RenderFrameHost* render_frame_host, scoped_refptr<content::FileSelectListener> listener, const blink::mojom::FileChooserParams& params) { FileSelectHelper::RunFileChooser(render_frame_host, std::move(listener), params); } void WebContents::EnumerateDirectory( content::WebContents* web_contents, scoped_refptr<content::FileSelectListener> listener, const base::FilePath& path) { FileSelectHelper::EnumerateDirectory(web_contents, std::move(listener), path); } bool WebContents::IsFullscreenForTabOrPending( const content::WebContents* source) { return html_fullscreen_; } bool WebContents::TakeFocus(content::WebContents* source, bool reverse) { if (source && source->GetOutermostWebContents() == source) { // If this is the outermost web contents and the user has tabbed or // shift + tabbed through all the elements, reset the focus back to // the first or last element so that it doesn't stay in the body. source->FocusThroughTabTraversal(reverse); return true; } return false; } content::PictureInPictureResult WebContents::EnterPictureInPicture( content::WebContents* web_contents) { #if BUILDFLAG(ENABLE_PICTURE_IN_PICTURE) return PictureInPictureWindowManager::GetInstance() ->EnterVideoPictureInPicture(web_contents); #else return content::PictureInPictureResult::kNotSupported; #endif } void WebContents::ExitPictureInPicture() { #if BUILDFLAG(ENABLE_PICTURE_IN_PICTURE) PictureInPictureWindowManager::GetInstance()->ExitPictureInPicture(); #endif } void WebContents::DevToolsSaveToFile(const std::string& url, const std::string& content, bool save_as) { base::FilePath path; auto it = saved_files_.find(url); if (it != saved_files_.end() && !save_as) { path = it->second; } else { file_dialog::DialogSettings settings; settings.parent_window = owner_window(); settings.force_detached = offscreen_; settings.title = url; settings.default_path = base::FilePath::FromUTF8Unsafe(url); if (!file_dialog::ShowSaveDialogSync(settings, &path)) { base::Value url_value(url); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.canceledSaveURL", &url_value, nullptr, nullptr); return; } } saved_files_[url] = path; // Notify DevTools. base::Value url_value(url); base::Value file_system_path_value(path.AsUTF8Unsafe()); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.savedURL", &url_value, &file_system_path_value, nullptr); file_task_runner_->PostTask(FROM_HERE, base::BindOnce(&WriteToFile, path, content)); } void WebContents::DevToolsAppendToFile(const std::string& url, const std::string& content) { auto it = saved_files_.find(url); if (it == saved_files_.end()) return; // Notify DevTools. base::Value url_value(url); inspectable_web_contents_->CallClientFunction("DevToolsAPI.appendedToURL", &url_value, nullptr, nullptr); file_task_runner_->PostTask( FROM_HERE, base::BindOnce(&AppendToFile, it->second, content)); } void WebContents::DevToolsRequestFileSystems() { auto file_system_paths = GetAddedFileSystemPaths(GetDevToolsWebContents()); if (file_system_paths.empty()) { base::ListValue empty_file_system_value; inspectable_web_contents_->CallClientFunction( "DevToolsAPI.fileSystemsLoaded", &empty_file_system_value, nullptr, nullptr); return; } std::vector<FileSystem> file_systems; for (const auto& file_system_path : file_system_paths) { base::FilePath path = base::FilePath::FromUTF8Unsafe(file_system_path.first); std::string file_system_id = RegisterFileSystem(GetDevToolsWebContents(), path); FileSystem file_system = CreateFileSystemStruct(GetDevToolsWebContents(), file_system_id, file_system_path.first, file_system_path.second); file_systems.push_back(file_system); } base::ListValue file_system_value; for (const auto& file_system : file_systems) file_system_value.Append(CreateFileSystemValue(file_system)); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.fileSystemsLoaded", &file_system_value, nullptr, nullptr); } void WebContents::DevToolsAddFileSystem( const std::string& type, const base::FilePath& file_system_path) { base::FilePath path = file_system_path; if (path.empty()) { std::vector<base::FilePath> paths; file_dialog::DialogSettings settings; settings.parent_window = owner_window(); settings.force_detached = offscreen_; settings.properties = file_dialog::OPEN_DIALOG_OPEN_DIRECTORY; if (!file_dialog::ShowOpenDialogSync(settings, &paths)) return; path = paths[0]; } std::string file_system_id = RegisterFileSystem(GetDevToolsWebContents(), path); if (IsDevToolsFileSystemAdded(GetDevToolsWebContents(), path.AsUTF8Unsafe())) return; FileSystem file_system = CreateFileSystemStruct( GetDevToolsWebContents(), file_system_id, path.AsUTF8Unsafe(), type); std::unique_ptr<base::DictionaryValue> file_system_value( CreateFileSystemValue(file_system)); auto* pref_service = GetPrefService(GetDevToolsWebContents()); DictionaryPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths); update.Get()->SetKey(path.AsUTF8Unsafe(), base::Value(type)); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.fileSystemAdded", nullptr, file_system_value.get(), nullptr); } void WebContents::DevToolsRemoveFileSystem( const base::FilePath& file_system_path) { if (!inspectable_web_contents_) return; std::string path = file_system_path.AsUTF8Unsafe(); storage::IsolatedContext::GetInstance()->RevokeFileSystemByPath( file_system_path); auto* pref_service = GetPrefService(GetDevToolsWebContents()); DictionaryPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths); update.Get()->RemoveKey(path); base::Value file_system_path_value(path); inspectable_web_contents_->CallClientFunction("DevToolsAPI.fileSystemRemoved", &file_system_path_value, nullptr, nullptr); } void WebContents::DevToolsIndexPath( int request_id, const std::string& file_system_path, const std::string& excluded_folders_message) { if (!IsDevToolsFileSystemAdded(GetDevToolsWebContents(), file_system_path)) { OnDevToolsIndexingDone(request_id, file_system_path); return; } if (devtools_indexing_jobs_.count(request_id) != 0) return; std::vector<std::string> excluded_folders; std::unique_ptr<base::Value> parsed_excluded_folders = base::JSONReader::ReadDeprecated(excluded_folders_message); if (parsed_excluded_folders && parsed_excluded_folders->is_list()) { for (const base::Value& folder_path : parsed_excluded_folders->GetListDeprecated()) { if (folder_path.is_string()) excluded_folders.push_back(folder_path.GetString()); } } devtools_indexing_jobs_[request_id] = scoped_refptr<DevToolsFileSystemIndexer::FileSystemIndexingJob>( devtools_file_system_indexer_->IndexPath( file_system_path, excluded_folders, base::BindRepeating( &WebContents::OnDevToolsIndexingWorkCalculated, weak_factory_.GetWeakPtr(), request_id, file_system_path), base::BindRepeating(&WebContents::OnDevToolsIndexingWorked, weak_factory_.GetWeakPtr(), request_id, file_system_path), base::BindRepeating(&WebContents::OnDevToolsIndexingDone, weak_factory_.GetWeakPtr(), request_id, file_system_path))); } void WebContents::DevToolsStopIndexing(int request_id) { auto it = devtools_indexing_jobs_.find(request_id); if (it == devtools_indexing_jobs_.end()) return; it->second->Stop(); devtools_indexing_jobs_.erase(it); } void WebContents::DevToolsSearchInPath(int request_id, const std::string& file_system_path, const std::string& query) { if (!IsDevToolsFileSystemAdded(GetDevToolsWebContents(), file_system_path)) { OnDevToolsSearchCompleted(request_id, file_system_path, std::vector<std::string>()); return; } devtools_file_system_indexer_->SearchInPath( file_system_path, query, base::BindRepeating(&WebContents::OnDevToolsSearchCompleted, weak_factory_.GetWeakPtr(), request_id, file_system_path)); } void WebContents::DevToolsSetEyeDropperActive(bool active) { auto* web_contents = GetWebContents(); if (!web_contents) return; if (active) { eye_dropper_ = std::make_unique<DevToolsEyeDropper>( web_contents, base::BindRepeating(&WebContents::ColorPickedInEyeDropper, base::Unretained(this))); } else { eye_dropper_.reset(); } } void WebContents::ColorPickedInEyeDropper(int r, int g, int b, int a) { base::DictionaryValue color; color.SetInteger("r", r); color.SetInteger("g", g); color.SetInteger("b", b); color.SetInteger("a", a); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.eyeDropperPickedColor", &color, nullptr, nullptr); } #if defined(TOOLKIT_VIEWS) && !BUILDFLAG(IS_MAC) ui::ImageModel WebContents::GetDevToolsWindowIcon() { return owner_window() ? owner_window()->GetWindowAppIcon() : ui::ImageModel{}; } #endif #if BUILDFLAG(IS_LINUX) void WebContents::GetDevToolsWindowWMClass(std::string* name, std::string* class_name) { *class_name = Browser::Get()->GetName(); *name = base::ToLowerASCII(*class_name); } #endif void WebContents::OnDevToolsIndexingWorkCalculated( int request_id, const std::string& file_system_path, int total_work) { base::Value request_id_value(request_id); base::Value file_system_path_value(file_system_path); base::Value total_work_value(total_work); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.indexingTotalWorkCalculated", &request_id_value, &file_system_path_value, &total_work_value); } void WebContents::OnDevToolsIndexingWorked(int request_id, const std::string& file_system_path, int worked) { base::Value request_id_value(request_id); base::Value file_system_path_value(file_system_path); base::Value worked_value(worked); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.indexingWorked", &request_id_value, &file_system_path_value, &worked_value); } void WebContents::OnDevToolsIndexingDone(int request_id, const std::string& file_system_path) { devtools_indexing_jobs_.erase(request_id); base::Value request_id_value(request_id); base::Value file_system_path_value(file_system_path); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.indexingDone", &request_id_value, &file_system_path_value, nullptr); } void WebContents::OnDevToolsSearchCompleted( int request_id, const std::string& file_system_path, const std::vector<std::string>& file_paths) { base::ListValue file_paths_value; for (const auto& file_path : file_paths) { file_paths_value.Append(file_path); } base::Value request_id_value(request_id); base::Value file_system_path_value(file_system_path); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.searchCompleted", &request_id_value, &file_system_path_value, &file_paths_value); } void WebContents::SetHtmlApiFullscreen(bool enter_fullscreen) { // Window is already in fullscreen mode, save the state. if (enter_fullscreen && owner_window_->IsFullscreen()) { native_fullscreen_ = true; UpdateHtmlApiFullscreen(true); return; } // Exit html fullscreen state but not window's fullscreen mode. if (!enter_fullscreen && native_fullscreen_) { UpdateHtmlApiFullscreen(false); return; } // Set fullscreen on window if allowed. auto* web_preferences = WebContentsPreferences::From(GetWebContents()); bool html_fullscreenable = web_preferences ? !web_preferences->ShouldDisableHtmlFullscreenWindowResize() : true; if (html_fullscreenable) { owner_window_->SetFullScreen(enter_fullscreen); } UpdateHtmlApiFullscreen(enter_fullscreen); native_fullscreen_ = false; } void WebContents::UpdateHtmlApiFullscreen(bool fullscreen) { if (fullscreen == is_html_fullscreen()) return; html_fullscreen_ = fullscreen; // Notify renderer of the html fullscreen change. web_contents() ->GetRenderViewHost() ->GetWidget() ->SynchronizeVisualProperties(); // The embedder WebContents is separated from the frame tree of webview, so // we must manually sync their fullscreen states. if (embedder_) embedder_->SetHtmlApiFullscreen(fullscreen); if (fullscreen) { Emit("enter-html-full-screen"); owner_window_->NotifyWindowEnterHtmlFullScreen(); } else { Emit("leave-html-full-screen"); owner_window_->NotifyWindowLeaveHtmlFullScreen(); } // Make sure all child webviews quit html fullscreen. if (!fullscreen && !IsGuest()) { auto* manager = WebViewManager::GetWebViewManager(web_contents()); manager->ForEachGuest( web_contents(), base::BindRepeating([](content::WebContents* guest) { WebContents* api_web_contents = WebContents::From(guest); api_web_contents->SetHtmlApiFullscreen(false); return false; })); } } // static v8::Local<v8::ObjectTemplate> WebContents::FillObjectTemplate( v8::Isolate* isolate, v8::Local<v8::ObjectTemplate> templ) { gin::InvokerOptions options; options.holder_is_first_argument = true; options.holder_type = "WebContents"; templ->Set( gin::StringToSymbol(isolate, "isDestroyed"), gin::CreateFunctionTemplate( isolate, base::BindRepeating(&gin_helper::Destroyable::IsDestroyed), options)); // We use gin_helper::ObjectTemplateBuilder instead of // gin::ObjectTemplateBuilder here to handle the fact that WebContents is // destroyable. return gin_helper::ObjectTemplateBuilder(isolate, templ) .SetMethod("destroy", &WebContents::Destroy) .SetMethod("getBackgroundThrottling", &WebContents::GetBackgroundThrottling) .SetMethod("setBackgroundThrottling", &WebContents::SetBackgroundThrottling) .SetMethod("getProcessId", &WebContents::GetProcessID) .SetMethod("getOSProcessId", &WebContents::GetOSProcessID) .SetMethod("equal", &WebContents::Equal) .SetMethod("_loadURL", &WebContents::LoadURL) .SetMethod("reload", &WebContents::Reload) .SetMethod("reloadIgnoringCache", &WebContents::ReloadIgnoringCache) .SetMethod("downloadURL", &WebContents::DownloadURL) .SetMethod("getURL", &WebContents::GetURL) .SetMethod("getTitle", &WebContents::GetTitle) .SetMethod("isLoading", &WebContents::IsLoading) .SetMethod("isLoadingMainFrame", &WebContents::IsLoadingMainFrame) .SetMethod("isWaitingForResponse", &WebContents::IsWaitingForResponse) .SetMethod("stop", &WebContents::Stop) .SetMethod("canGoBack", &WebContents::CanGoBack) .SetMethod("goBack", &WebContents::GoBack) .SetMethod("canGoForward", &WebContents::CanGoForward) .SetMethod("goForward", &WebContents::GoForward) .SetMethod("canGoToOffset", &WebContents::CanGoToOffset) .SetMethod("goToOffset", &WebContents::GoToOffset) .SetMethod("canGoToIndex", &WebContents::CanGoToIndex) .SetMethod("goToIndex", &WebContents::GoToIndex) .SetMethod("getActiveIndex", &WebContents::GetActiveIndex) .SetMethod("clearHistory", &WebContents::ClearHistory) .SetMethod("length", &WebContents::GetHistoryLength) .SetMethod("isCrashed", &WebContents::IsCrashed) .SetMethod("forcefullyCrashRenderer", &WebContents::ForcefullyCrashRenderer) .SetMethod("setUserAgent", &WebContents::SetUserAgent) .SetMethod("getUserAgent", &WebContents::GetUserAgent) .SetMethod("savePage", &WebContents::SavePage) .SetMethod("openDevTools", &WebContents::OpenDevTools) .SetMethod("closeDevTools", &WebContents::CloseDevTools) .SetMethod("isDevToolsOpened", &WebContents::IsDevToolsOpened) .SetMethod("isDevToolsFocused", &WebContents::IsDevToolsFocused) .SetMethod("enableDeviceEmulation", &WebContents::EnableDeviceEmulation) .SetMethod("disableDeviceEmulation", &WebContents::DisableDeviceEmulation) .SetMethod("toggleDevTools", &WebContents::ToggleDevTools) .SetMethod("inspectElement", &WebContents::InspectElement) .SetMethod("setIgnoreMenuShortcuts", &WebContents::SetIgnoreMenuShortcuts) .SetMethod("setAudioMuted", &WebContents::SetAudioMuted) .SetMethod("isAudioMuted", &WebContents::IsAudioMuted) .SetMethod("isCurrentlyAudible", &WebContents::IsCurrentlyAudible) .SetMethod("undo", &WebContents::Undo) .SetMethod("redo", &WebContents::Redo) .SetMethod("cut", &WebContents::Cut) .SetMethod("copy", &WebContents::Copy) .SetMethod("paste", &WebContents::Paste) .SetMethod("pasteAndMatchStyle", &WebContents::PasteAndMatchStyle) .SetMethod("delete", &WebContents::Delete) .SetMethod("selectAll", &WebContents::SelectAll) .SetMethod("unselect", &WebContents::Unselect) .SetMethod("replace", &WebContents::Replace) .SetMethod("replaceMisspelling", &WebContents::ReplaceMisspelling) .SetMethod("findInPage", &WebContents::FindInPage) .SetMethod("stopFindInPage", &WebContents::StopFindInPage) .SetMethod("focus", &WebContents::Focus) .SetMethod("isFocused", &WebContents::IsFocused) .SetMethod("sendInputEvent", &WebContents::SendInputEvent) .SetMethod("beginFrameSubscription", &WebContents::BeginFrameSubscription) .SetMethod("endFrameSubscription", &WebContents::EndFrameSubscription) .SetMethod("startDrag", &WebContents::StartDrag) .SetMethod("attachToIframe", &WebContents::AttachToIframe) .SetMethod("detachFromOuterFrame", &WebContents::DetachFromOuterFrame) .SetMethod("isOffscreen", &WebContents::IsOffScreen) #if BUILDFLAG(ENABLE_OSR) .SetMethod("startPainting", &WebContents::StartPainting) .SetMethod("stopPainting", &WebContents::StopPainting) .SetMethod("isPainting", &WebContents::IsPainting) .SetMethod("setFrameRate", &WebContents::SetFrameRate) .SetMethod("getFrameRate", &WebContents::GetFrameRate) #endif .SetMethod("invalidate", &WebContents::Invalidate) .SetMethod("setZoomLevel", &WebContents::SetZoomLevel) .SetMethod("getZoomLevel", &WebContents::GetZoomLevel) .SetMethod("setZoomFactor", &WebContents::SetZoomFactor) .SetMethod("getZoomFactor", &WebContents::GetZoomFactor) .SetMethod("getType", &WebContents::GetType) .SetMethod("_getPreloadPaths", &WebContents::GetPreloadPaths) .SetMethod("getLastWebPreferences", &WebContents::GetLastWebPreferences) .SetMethod("getOwnerBrowserWindow", &WebContents::GetOwnerBrowserWindow) .SetMethod("inspectServiceWorker", &WebContents::InspectServiceWorker) .SetMethod("inspectSharedWorker", &WebContents::InspectSharedWorker) .SetMethod("inspectSharedWorkerById", &WebContents::InspectSharedWorkerById) .SetMethod("getAllSharedWorkers", &WebContents::GetAllSharedWorkers) #if BUILDFLAG(ENABLE_PRINTING) .SetMethod("_print", &WebContents::Print) .SetMethod("_printToPDF", &WebContents::PrintToPDF) #endif .SetMethod("_setNextChildWebPreferences", &WebContents::SetNextChildWebPreferences) .SetMethod("addWorkSpace", &WebContents::AddWorkSpace) .SetMethod("removeWorkSpace", &WebContents::RemoveWorkSpace) .SetMethod("showDefinitionForSelection", &WebContents::ShowDefinitionForSelection) .SetMethod("copyImageAt", &WebContents::CopyImageAt) .SetMethod("capturePage", &WebContents::CapturePage) .SetMethod("setEmbedder", &WebContents::SetEmbedder) .SetMethod("setDevToolsWebContents", &WebContents::SetDevToolsWebContents) .SetMethod("getNativeView", &WebContents::GetNativeView) .SetMethod("incrementCapturerCount", &WebContents::IncrementCapturerCount) .SetMethod("decrementCapturerCount", &WebContents::DecrementCapturerCount) .SetMethod("isBeingCaptured", &WebContents::IsBeingCaptured) .SetMethod("setWebRTCIPHandlingPolicy", &WebContents::SetWebRTCIPHandlingPolicy) .SetMethod("getMediaSourceId", &WebContents::GetMediaSourceID) .SetMethod("getWebRTCIPHandlingPolicy", &WebContents::GetWebRTCIPHandlingPolicy) .SetMethod("takeHeapSnapshot", &WebContents::TakeHeapSnapshot) .SetMethod("setImageAnimationPolicy", &WebContents::SetImageAnimationPolicy) .SetMethod("_getProcessMemoryInfo", &WebContents::GetProcessMemoryInfo) .SetProperty("id", &WebContents::ID) .SetProperty("session", &WebContents::Session) .SetProperty("hostWebContents", &WebContents::HostWebContents) .SetProperty("devToolsWebContents", &WebContents::DevToolsWebContents) .SetProperty("debugger", &WebContents::Debugger) .SetProperty("mainFrame", &WebContents::MainFrame) .Build(); } const char* WebContents::GetTypeName() { return "WebContents"; } ElectronBrowserContext* WebContents::GetBrowserContext() const { return static_cast<ElectronBrowserContext*>( web_contents()->GetBrowserContext()); } // static gin::Handle<WebContents> WebContents::New( v8::Isolate* isolate, const gin_helper::Dictionary& options) { gin::Handle<WebContents> handle = gin::CreateHandle(isolate, new WebContents(isolate, options)); v8::TryCatch try_catch(isolate); gin_helper::CallMethod(isolate, handle.get(), "_init"); if (try_catch.HasCaught()) { node::errors::TriggerUncaughtException(isolate, try_catch); } return handle; } // static gin::Handle<WebContents> WebContents::CreateAndTake( v8::Isolate* isolate, std::unique_ptr<content::WebContents> web_contents, Type type) { gin::Handle<WebContents> handle = gin::CreateHandle( isolate, new WebContents(isolate, std::move(web_contents), type)); v8::TryCatch try_catch(isolate); gin_helper::CallMethod(isolate, handle.get(), "_init"); if (try_catch.HasCaught()) { node::errors::TriggerUncaughtException(isolate, try_catch); } return handle; } // static WebContents* WebContents::From(content::WebContents* web_contents) { if (!web_contents) return nullptr; auto* data = static_cast<UserDataLink*>( web_contents->GetUserData(kElectronApiWebContentsKey)); return data ? data->web_contents.get() : nullptr; } // static gin::Handle<WebContents> WebContents::FromOrCreate( v8::Isolate* isolate, content::WebContents* web_contents) { WebContents* api_web_contents = From(web_contents); if (!api_web_contents) { api_web_contents = new WebContents(isolate, web_contents); v8::TryCatch try_catch(isolate); gin_helper::CallMethod(isolate, api_web_contents, "_init"); if (try_catch.HasCaught()) { node::errors::TriggerUncaughtException(isolate, try_catch); } } return gin::CreateHandle(isolate, api_web_contents); } // static gin::Handle<WebContents> WebContents::CreateFromWebPreferences( v8::Isolate* isolate, const gin_helper::Dictionary& web_preferences) { // Check if webPreferences has |webContents| option. gin::Handle<WebContents> web_contents; if (web_preferences.GetHidden("webContents", &web_contents) && !web_contents.IsEmpty()) { // Set webPreferences from options if using an existing webContents. // These preferences will be used when the webContent launches new // render processes. auto* existing_preferences = WebContentsPreferences::From(web_contents->web_contents()); gin_helper::Dictionary web_preferences_dict; if (gin::ConvertFromV8(isolate, web_preferences.GetHandle(), &web_preferences_dict)) { existing_preferences->SetFromDictionary(web_preferences_dict); absl::optional<SkColor> color = existing_preferences->GetBackgroundColor(); web_contents->web_contents()->SetPageBaseBackgroundColor(color); // Because web preferences don't recognize transparency, // only set rwhv background color if a color exists auto* rwhv = web_contents->web_contents()->GetRenderWidgetHostView(); if (rwhv && color.has_value()) SetBackgroundColor(rwhv, color.value()); } } else { // Create one if not. web_contents = WebContents::New(isolate, web_preferences); } return web_contents; } // static WebContents* WebContents::FromID(int32_t id) { return GetAllWebContents().Lookup(id); } // static gin::WrapperInfo WebContents::kWrapperInfo = {gin::kEmbedderNativeGin}; } // namespace api } // namespace electron namespace { using electron::api::GetAllWebContents; using electron::api::WebContents; gin::Handle<WebContents> WebContentsFromID(v8::Isolate* isolate, int32_t id) { WebContents* contents = WebContents::FromID(id); return contents ? gin::CreateHandle(isolate, contents) : gin::Handle<WebContents>(); } gin::Handle<WebContents> WebContentsFromDevToolsTargetID( v8::Isolate* isolate, std::string target_id) { auto agent_host = content::DevToolsAgentHost::GetForId(target_id); WebContents* contents = agent_host ? WebContents::From(agent_host->GetWebContents()) : nullptr; return contents ? gin::CreateHandle(isolate, contents) : gin::Handle<WebContents>(); } std::vector<gin::Handle<WebContents>> GetAllWebContentsAsV8( v8::Isolate* isolate) { std::vector<gin::Handle<WebContents>> list; for (auto iter = base::IDMap<WebContents*>::iterator(&GetAllWebContents()); !iter.IsAtEnd(); iter.Advance()) { list.push_back(gin::CreateHandle(isolate, iter.GetCurrentValue())); } return list; } void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused, v8::Local<v8::Context> context, void* priv) { v8::Isolate* isolate = context->GetIsolate(); gin_helper::Dictionary dict(isolate, exports); dict.Set("WebContents", WebContents::GetConstructor(context)); dict.SetMethod("fromId", &WebContentsFromID); dict.SetMethod("fromDevToolsTargetId", &WebContentsFromDevToolsTargetID); dict.SetMethod("getAllWebContents", &GetAllWebContentsAsV8); } } // namespace NODE_LINKED_MODULE_CONTEXT_AWARE(electron_browser_web_contents, Initialize)
closed
electron/electron
https://github.com/electron/electron
34,270
DCHECK on `webContents.print()`
Introduced by https://github.com/electron/electron/pull/33906. Root Cause: https://chromium-review.googlesource.com/c/chromium/src/+/3579297 <details> <summary> Stacktrace </summary> ``` [46358:0518/110313.131061:FATAL:values_mojom_traits.h(100)] Check failed: value.is_dict(). 0 Electron Framework 0x000000012ef92ba9 base::debug::CollectStackTrace(void**, unsigned long) + 9 1 Electron Framework 0x000000012eeb3ac3 base::debug::StackTrace::StackTrace() + 19 2 Electron Framework 0x000000012eecccdf logging::LogMessage::~LogMessage() + 175 3 Electron Framework 0x000000012eecdd2e logging::LogMessage::~LogMessage() + 14 4 Electron Framework 0x000000012a9ed02a mojo::internal::Serializer<mojo_base::mojom::DeprecatedDictionaryValueDataView, base::Value>::Serialize(base::Value&, mojo::internal::MessageFragment<mojo_base::mojom::internal::DeprecatedDictionaryValue_Data>&) + 90 5 Electron Framework 0x000000012e7582da printing::mojom::PrintRenderFrameProxy::PrintRequestedPages(bool, base::Value) + 362 6 Electron Framework 0x0000000133f15232 printing::PrintViewManagerBase::CompletePrintNow(content::RenderFrameHost*) + 146 7 Electron Framework 0x0000000133f14f3b printing::PrintViewManagerBase::PrintNow(content::RenderFrameHost*, bool, base::Value, base::OnceCallback<void (bool, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)>) + 395 8 Electron Framework 0x000000012a56ed16 electron::api::WebContents::OnGetDefaultPrinter(base::Value, base::OnceCallback<void (bool, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)>, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> >, bool, std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > >) + 1686 9 Electron Framework 0x000000012a580b93 void base::internal::FunctorTraits<void (electron::api::WebContents::*)(base::Value, base::OnceCallback<void (bool, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)>, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> >, bool, std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > >), void>::Invoke<void (electron::api::WebContents::*)(base::Value, base::OnceCallback<void (bool, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)>, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> >, bool, std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > >), base::WeakPtr<electron::api::WebContents>, base::Value, base::OnceCallback<void (bool, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)>, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> >, bool, std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > > >(void (electron::api::WebContents::*)(base::Value, base::OnceCallback<void (bool, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)>, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> >, bool, std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > >), base::WeakPtr<electron::api::WebContents>&&, base::Value&&, base::OnceCallback<void (bool, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)>&&, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> >&&, bool&&, std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > >&&) + 291 10 Electron Framework 0x000000012a58099d base::internal::Invoker<base::internal::BindState<void (electron::api::WebContents::*)(base::Value, base::OnceCallback<void (bool, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)>, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> >, bool, std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > >), base::WeakPtr<electron::api::WebContents>, base::Value, base::OnceCallback<void (bool, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)>, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> >, bool>, void (std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > >)>::RunOnce(base::internal::BindStateBase*, std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > >&&) + 77 11 Electron Framework 0x000000012a581102 void base::internal::ReplyAdapter<std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > >, std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > > >(base::OnceCallback<void (std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > >)>, std::__1::unique_ptr<std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > >, std::__1::default_delete<std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > > > >*) + 210 12 Electron Framework 0x000000012a4f9627 base::internal::Invoker<base::internal::BindState<void (*)(base::OnceCallback<(anonymous namespace)::CloseFileResult ()>, std::__1::unique_ptr<(anonymous namespace)::CloseFileResult, std::__1::default_delete<(anonymous namespace)::CloseFileResult> >*), base::OnceCallback<(anonymous namespace)::CloseFileResult ()>, base::internal::UnretainedWrapper<std::__1::unique_ptr<(anonymous namespace)::CloseFileResult, std::__1::default_delete<(anonymous namespace)::CloseFileResult> > > >, void ()>::RunOnce(base::internal::BindStateBase*) + 39 13 Electron Framework 0x000000012ef74403 base::(anonymous namespace)::PostTaskAndReplyRelay::RunReply(base::(anonymous namespace)::PostTaskAndReplyRelay) + 211 14 Electron Framework 0x000000012ef74499 base::internal::Invoker<base::internal::BindState<void (*)(base::(anonymous namespace)::PostTaskAndReplyRelay), base::(anonymous namespace)::PostTaskAndReplyRelay>, void ()>::RunOnce(base::internal::BindStateBase*) + 73 15 Electron Framework 0x000000012ef261f9 base::TaskAnnotator::RunTaskImpl(base::PendingTask&) + 313 16 Electron Framework 0x000000012ef4e1ca base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::DoWorkImpl(base::sequence_manager::LazyNow*) + 1066 17 Electron Framework 0x000000012ef4d88e base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::DoWork() + 126 18 Electron Framework 0x000000012ef4e9e2 non-virtual thunk to base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::DoWork() + 18 19 Electron Framework 0x000000012efa83e1 base::MessagePumpCFRunLoopBase::RunWork() + 97 20 Electron Framework 0x000000012efa78c2 base::mac::CallWithEHFrame(void () block_pointer) + 10 21 Electron Framework 0x000000012efa7e0f base::MessagePumpCFRunLoopBase::RunWorkSource(void*) + 63 22 CoreFoundation 0x00007ff80b673aeb __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17 23 CoreFoundation 0x00007ff80b673a53 __CFRunLoopDoSource0 + 180 24 CoreFoundation 0x00007ff80b6737cd __CFRunLoopDoSources0 + 242 25 CoreFoundation 0x00007ff80b6721e8 __CFRunLoopRun + 892 26 CoreFoundation 0x00007ff80b6717ac CFRunLoopRunSpecific + 562 27 HIToolbox 0x00007ff8142f8ce6 RunCurrentEventLoopInMode + 292 28 HIToolbox 0x00007ff8142f8a4a ReceiveNextEventCommon + 594 29 HIToolbox 0x00007ff8142f87e5 _BlockUntilNextEventMatchingListInModeWithFilter + 70 30 AppKit 0x00007ff80e09853d _DPSNextEvent + 927 31 AppKit 0x00007ff80e096bfa -[NSApplication(NSEvent) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] + 1394 32 AppKit 0x00007ff80e0892a9 -[NSApplication run] + 586 33 Electron Framework 0x000000012efa8e7c base::MessagePumpNSApplication::DoRun(base::MessagePump::Delegate*) + 348 34 Electron Framework 0x000000012efa796b base::MessagePumpCFRunLoopBase::Run(base::MessagePump::Delegate*) + 155 35 Electron Framework 0x000000012ef4ef97 base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::Run(bool, base::TimeDelta) + 695 36 Electron Framework 0x000000012ef01dc6 base::RunLoop::Run(base::Location const&) + 726 37 Electron Framework 0x000000012dac4c83 content::BrowserMainLoop::RunMainMessageLoop() + 243 38 Electron Framework 0x000000012dac6822 content::BrowserMainRunnerImpl::Run() + 82 39 Electron Framework 0x000000012dac1fce content::BrowserMain(content::MainFunctionParams) + 270 40 Electron Framework 0x000000012a90bd12 content::RunBrowserProcessMain(content::MainFunctionParams, content::ContentMainDelegate*) + 258 41 Electron Framework 0x000000012a90d28b content::ContentMainRunnerImpl::RunBrowser(content::MainFunctionParams, bool) + 1403 42 Electron Framework 0x000000012a90cc90 content::ContentMainRunnerImpl::Run() + 736 43 Electron Framework 0x000000012a90b637 content::RunContentProcess(content::ContentMainParams, content::ContentMainRunner*) + 2679 44 Electron Framework 0x000000012a90b752 content::ContentMain(content::ContentMainParams) + 98 45 Electron Framework 0x000000012a4b883d ElectronMain + 157 46 dyld 0x0000000114aee51e start + 462 Task trace: 0 Electron Framework 0x000000012a56f8b0 electron::api::WebContents::Print(gin::Arguments*) + 2832 1 Electron Framework 0x000000012a56f8b0 electron::api::WebContents::Print(gin::Arguments*) + 2832 2 Electron Framework 0x000000012f718430 IPC::(anonymous namespace)::ChannelAssociatedGroupController::Accept(mojo::Message*) + 784 3 Electron Framework 0x000000012f2f4f9e mojo::SimpleWatcher::Context::Notify(unsigned int, MojoHandleSignalsState, unsigned int) + 430 Crash keys: "ui_scheduler_async_stack" = "0x12A56F8B0 0x12A56F8B0" "io_scheduler_async_stack" = "0x12BEBEDDB 0x0" "platform" = "darwin" "process_type" = "browser" ``` </details>
https://github.com/electron/electron/issues/34270
https://github.com/electron/electron/pull/34271
73e0bf973d2b7835290d61cab6638309a21a2719
588005a9d5a74b953961605579cf4ad6f8dc2b20
2022-05-18T09:05:02Z
c++
2022-05-19T08:05:07Z
shell/browser/api/electron_api_web_contents.h
// Copyright (c) 2014 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #ifndef ELECTRON_SHELL_BROWSER_API_ELECTRON_API_WEB_CONTENTS_H_ #define ELECTRON_SHELL_BROWSER_API_ELECTRON_API_WEB_CONTENTS_H_ #include <map> #include <memory> #include <string> #include <utility> #include <vector> #include "base/memory/weak_ptr.h" #include "base/observer_list.h" #include "base/observer_list_types.h" #include "chrome/browser/devtools/devtools_eye_dropper.h" #include "chrome/browser/devtools/devtools_file_system_indexer.h" #include "chrome/browser/ui/exclusive_access/exclusive_access_context.h" // nogncheck #include "content/common/cursors/webcursor.h" #include "content/common/frame.mojom.h" #include "content/public/browser/devtools_agent_host.h" #include "content/public/browser/keyboard_event_processing_result.h" #include "content/public/browser/render_widget_host.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_contents_delegate.h" #include "content/public/browser/web_contents_observer.h" #include "electron/buildflags/buildflags.h" #include "electron/shell/common/api/api.mojom.h" #include "gin/handle.h" #include "gin/wrappable.h" #include "mojo/public/cpp/bindings/receiver_set.h" #include "printing/buildflags/buildflags.h" #include "shell/browser/api/frame_subscriber.h" #include "shell/browser/api/save_page_handler.h" #include "shell/browser/event_emitter_mixin.h" #include "shell/browser/extended_web_contents_observer.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/ui/inspectable_web_contents_delegate.h" #include "shell/browser/ui/inspectable_web_contents_view_delegate.h" #include "shell/common/gin_helper/cleaned_up_at_exit.h" #include "shell/common/gin_helper/constructible.h" #include "shell/common/gin_helper/error_thrower.h" #include "shell/common/gin_helper/pinnable.h" #include "third_party/blink/public/common/permissions/permission_utils.h" #include "ui/base/models/image_model.h" #include "ui/gfx/image/image.h" #if BUILDFLAG(ENABLE_PRINTING) #include "shell/browser/printing/print_preview_message_handler.h" #include "shell/browser/printing/print_view_manager_electron.h" #endif #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #include "extensions/common/mojom/view_type.mojom.h" namespace extensions { class ScriptExecutor; } #endif namespace blink { struct DeviceEmulationParams; // enum class PermissionType; } // namespace blink namespace gin_helper { class Dictionary; } namespace network { class ResourceRequestBody; } namespace gin { class Arguments; } class ExclusiveAccessManager; namespace electron { class ElectronBrowserContext; class ElectronJavaScriptDialogManager; class InspectableWebContents; class WebContentsZoomController; class WebViewGuestDelegate; class FrameSubscriber; class WebDialogHelper; class NativeWindow; #if BUILDFLAG(ENABLE_OSR) class OffScreenRenderWidgetHostView; class OffScreenWebContentsView; #endif namespace api { using DevicePermissionMap = std::map< int, std::map<blink::PermissionType, std::map<url::Origin, std::vector<std::unique_ptr<base::Value>>>>>; // Wrapper around the content::WebContents. class WebContents : public ExclusiveAccessContext, public gin::Wrappable<WebContents>, public gin_helper::EventEmitterMixin<WebContents>, public gin_helper::Constructible<WebContents>, public gin_helper::Pinnable<WebContents>, public gin_helper::CleanedUpAtExit, public content::WebContentsObserver, public content::WebContentsDelegate, public InspectableWebContentsDelegate, public InspectableWebContentsViewDelegate { public: enum class Type { kBackgroundPage, // An extension background page. kBrowserWindow, // Used by BrowserWindow. kBrowserView, // Used by BrowserView. kRemote, // Thin wrap around an existing WebContents. kWebView, // Used by <webview>. kOffScreen, // Used for offscreen rendering }; // Create a new WebContents and return the V8 wrapper of it. static gin::Handle<WebContents> New(v8::Isolate* isolate, const gin_helper::Dictionary& options); // Create a new V8 wrapper for an existing |web_content|. // // The lifetime of |web_contents| will be managed by this class. static gin::Handle<WebContents> CreateAndTake( v8::Isolate* isolate, std::unique_ptr<content::WebContents> web_contents, Type type); // Get the api::WebContents associated with |web_contents|. Returns nullptr // if there is no associated wrapper. static WebContents* From(content::WebContents* web_contents); static WebContents* FromID(int32_t id); // Get the V8 wrapper of the |web_contents|, or create one if not existed. // // The lifetime of |web_contents| is NOT managed by this class, and the type // of this wrapper is always REMOTE. static gin::Handle<WebContents> FromOrCreate( v8::Isolate* isolate, content::WebContents* web_contents); static gin::Handle<WebContents> CreateFromWebPreferences( v8::Isolate* isolate, const gin_helper::Dictionary& web_preferences); // gin::Wrappable static gin::WrapperInfo kWrapperInfo; static v8::Local<v8::ObjectTemplate> FillObjectTemplate( v8::Isolate*, v8::Local<v8::ObjectTemplate>); const char* GetTypeName() override; void Destroy(); base::WeakPtr<WebContents> GetWeakPtr() { return weak_factory_.GetWeakPtr(); } bool GetBackgroundThrottling() const; void SetBackgroundThrottling(bool allowed); int GetProcessID() const; base::ProcessId GetOSProcessID() const; Type GetType() const; bool Equal(const WebContents* web_contents) const; void LoadURL(const GURL& url, const gin_helper::Dictionary& options); void Reload(); void ReloadIgnoringCache(); void DownloadURL(const GURL& url); GURL GetURL() const; std::u16string GetTitle() const; bool IsLoading() const; bool IsLoadingMainFrame() const; bool IsWaitingForResponse() const; void Stop(); bool CanGoBack() const; void GoBack(); bool CanGoForward() const; void GoForward(); bool CanGoToOffset(int offset) const; void GoToOffset(int offset); bool CanGoToIndex(int index) const; void GoToIndex(int index); int GetActiveIndex() const; void ClearHistory(); int GetHistoryLength() const; const std::string GetWebRTCIPHandlingPolicy() const; void SetWebRTCIPHandlingPolicy(const std::string& webrtc_ip_handling_policy); std::string GetMediaSourceID(content::WebContents* request_web_contents); bool IsCrashed() const; void ForcefullyCrashRenderer(); void SetUserAgent(const std::string& user_agent); std::string GetUserAgent(); void InsertCSS(const std::string& css); v8::Local<v8::Promise> SavePage(const base::FilePath& full_file_path, const content::SavePageType& save_type); void OpenDevTools(gin::Arguments* args); void CloseDevTools(); bool IsDevToolsOpened(); bool IsDevToolsFocused(); void ToggleDevTools(); void EnableDeviceEmulation(const blink::DeviceEmulationParams& params); void DisableDeviceEmulation(); void InspectElement(int x, int y); void InspectSharedWorker(); void InspectSharedWorkerById(const std::string& workerId); std::vector<scoped_refptr<content::DevToolsAgentHost>> GetAllSharedWorkers(); void InspectServiceWorker(); void SetIgnoreMenuShortcuts(bool ignore); void SetAudioMuted(bool muted); bool IsAudioMuted(); bool IsCurrentlyAudible(); void SetEmbedder(const WebContents* embedder); void SetDevToolsWebContents(const WebContents* devtools); v8::Local<v8::Value> GetNativeView(v8::Isolate* isolate) const; void IncrementCapturerCount(gin::Arguments* args); void DecrementCapturerCount(gin::Arguments* args); bool IsBeingCaptured(); void HandleNewRenderFrame(content::RenderFrameHost* render_frame_host); #if BUILDFLAG(ENABLE_PRINTING) void OnGetDefaultPrinter(base::Value print_settings, printing::CompletionCallback print_callback, std::u16string device_name, bool silent, // <error, default_printer_name> std::pair<std::string, std::u16string> info); void Print(gin::Arguments* args); // Print current page as PDF. v8::Local<v8::Promise> PrintToPDF(base::DictionaryValue settings); #endif void SetNextChildWebPreferences(const gin_helper::Dictionary); // DevTools workspace api. void AddWorkSpace(gin::Arguments* args, const base::FilePath& path); void RemoveWorkSpace(gin::Arguments* args, const base::FilePath& path); // Editing commands. void Undo(); void Redo(); void Cut(); void Copy(); void Paste(); void PasteAndMatchStyle(); void Delete(); void SelectAll(); void Unselect(); void Replace(const std::u16string& word); void ReplaceMisspelling(const std::u16string& word); uint32_t FindInPage(gin::Arguments* args); void StopFindInPage(content::StopFindAction action); void ShowDefinitionForSelection(); void CopyImageAt(int x, int y); // Focus. void Focus(); bool IsFocused() const; // Send WebInputEvent to the page. void SendInputEvent(v8::Isolate* isolate, v8::Local<v8::Value> input_event); // Subscribe to the frame updates. void BeginFrameSubscription(gin::Arguments* args); void EndFrameSubscription(); // Dragging native items. void StartDrag(const gin_helper::Dictionary& item, gin::Arguments* args); // Captures the page with |rect|, |callback| would be called when capturing is // done. v8::Local<v8::Promise> CapturePage(gin::Arguments* args); // Methods for creating <webview>. bool IsGuest() const; void AttachToIframe(content::WebContents* embedder_web_contents, int embedder_frame_id); void DetachFromOuterFrame(); // Methods for offscreen rendering bool IsOffScreen() const; #if BUILDFLAG(ENABLE_OSR) void OnPaint(const gfx::Rect& dirty_rect, const SkBitmap& bitmap); void StartPainting(); void StopPainting(); bool IsPainting() const; void SetFrameRate(int frame_rate); int GetFrameRate() const; #endif void Invalidate(); gfx::Size GetSizeForNewRenderView(content::WebContents*) override; // Methods for zoom handling. void SetZoomLevel(double level); double GetZoomLevel() const; void SetZoomFactor(gin_helper::ErrorThrower thrower, double factor); double GetZoomFactor() const; // Callback triggered on permission response. void OnEnterFullscreenModeForTab( content::RenderFrameHost* requesting_frame, const blink::mojom::FullscreenOptions& options, bool allowed); // Create window with the given disposition. void OnCreateWindow(const GURL& target_url, const content::Referrer& referrer, const std::string& frame_name, WindowOpenDisposition disposition, const std::string& features, const scoped_refptr<network::ResourceRequestBody>& body); // Returns the preload script path of current WebContents. std::vector<base::FilePath> GetPreloadPaths() const; // Returns the web preferences of current WebContents. v8::Local<v8::Value> GetLastWebPreferences(v8::Isolate* isolate) const; // Returns the owner window. v8::Local<v8::Value> GetOwnerBrowserWindow(v8::Isolate* isolate) const; // Notifies the web page that there is user interaction. void NotifyUserActivation(); v8::Local<v8::Promise> TakeHeapSnapshot(v8::Isolate* isolate, const base::FilePath& file_path); v8::Local<v8::Promise> GetProcessMemoryInfo(v8::Isolate* isolate); // Properties. int32_t ID() const { return id_; } v8::Local<v8::Value> Session(v8::Isolate* isolate); content::WebContents* HostWebContents() const; v8::Local<v8::Value> DevToolsWebContents(v8::Isolate* isolate); v8::Local<v8::Value> Debugger(v8::Isolate* isolate); content::RenderFrameHost* MainFrame(); WebContentsZoomController* GetZoomController() { return zoom_controller_; } void AddObserver(ExtendedWebContentsObserver* obs) { observers_.AddObserver(obs); } void RemoveObserver(ExtendedWebContentsObserver* obs) { // Trying to remove from an empty collection leads to an access violation if (!observers_.empty()) observers_.RemoveObserver(obs); } bool EmitNavigationEvent(const std::string& event, content::NavigationHandle* navigation_handle); // this.emit(name, new Event(sender, message), args...); template <typename... Args> bool EmitWithSender(base::StringPiece name, content::RenderFrameHost* sender, electron::mojom::ElectronApiIPC::InvokeCallback callback, Args&&... args) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); v8::Local<v8::Object> wrapper; if (!GetWrapper(isolate).ToLocal(&wrapper)) return false; v8::Local<v8::Object> event = gin_helper::internal::CreateNativeEvent( isolate, wrapper, sender, std::move(callback)); return EmitCustomEvent(name, event, std::forward<Args>(args)...); } WebContents* embedder() { return embedder_; } #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) extensions::ScriptExecutor* script_executor() { return script_executor_.get(); } #endif // Set the window as owner window. void SetOwnerWindow(NativeWindow* owner_window); void SetOwnerWindow(content::WebContents* web_contents, NativeWindow* owner_window); // Returns the WebContents managed by this delegate. content::WebContents* GetWebContents() const; // Returns the WebContents of devtools. content::WebContents* GetDevToolsWebContents() const; InspectableWebContents* inspectable_web_contents() const { return inspectable_web_contents_.get(); } NativeWindow* owner_window() const { return owner_window_.get(); } bool is_html_fullscreen() const { return html_fullscreen_; } void set_fullscreen_frame(content::RenderFrameHost* rfh) { fullscreen_frame_ = rfh; } // mojom::ElectronApiIPC void Message(bool internal, const std::string& channel, blink::CloneableMessage arguments, content::RenderFrameHost* render_frame_host); void Invoke(bool internal, const std::string& channel, blink::CloneableMessage arguments, electron::mojom::ElectronApiIPC::InvokeCallback callback, content::RenderFrameHost* render_frame_host); void ReceivePostMessage(const std::string& channel, blink::TransferableMessage message, content::RenderFrameHost* render_frame_host); void MessageSync( bool internal, const std::string& channel, blink::CloneableMessage arguments, electron::mojom::ElectronApiIPC::MessageSyncCallback callback, content::RenderFrameHost* render_frame_host); void MessageTo(int32_t web_contents_id, const std::string& channel, blink::CloneableMessage arguments); void MessageHost(const std::string& channel, blink::CloneableMessage arguments, content::RenderFrameHost* render_frame_host); // mojom::ElectronWebContentsUtility void OnFirstNonEmptyLayout(content::RenderFrameHost* render_frame_host); void UpdateDraggableRegions(std::vector<mojom::DraggableRegionPtr> regions); void SetTemporaryZoomLevel(double level); void DoGetZoomLevel( electron::mojom::ElectronWebContentsUtility::DoGetZoomLevelCallback callback); void SetImageAnimationPolicy(const std::string& new_policy); // Grants |origin| access to |device|. // To be used in place of ObjectPermissionContextBase::GrantObjectPermission. void GrantDevicePermission(const url::Origin& origin, const base::Value* device, blink::PermissionType permissionType, content::RenderFrameHost* render_frame_host); // Returns the list of devices that |origin| has been granted permission to // access. To be used in place of // ObjectPermissionContextBase::GetGrantedObjects. std::vector<base::Value> GetGrantedDevices( const url::Origin& origin, blink::PermissionType permissionType, content::RenderFrameHost* render_frame_host); // disable copy WebContents(const WebContents&) = delete; WebContents& operator=(const WebContents&) = delete; private: // Does not manage lifetime of |web_contents|. WebContents(v8::Isolate* isolate, content::WebContents* web_contents); // Takes over ownership of |web_contents|. WebContents(v8::Isolate* isolate, std::unique_ptr<content::WebContents> web_contents, Type type); // Creates a new content::WebContents. WebContents(v8::Isolate* isolate, const gin_helper::Dictionary& options); ~WebContents() override; // Delete this if garbage collection has not started. void DeleteThisIfAlive(); // Creates a InspectableWebContents object and takes ownership of // |web_contents|. void InitWithWebContents(std::unique_ptr<content::WebContents> web_contents, ElectronBrowserContext* browser_context, bool is_guest); void InitWithSessionAndOptions( v8::Isolate* isolate, std::unique_ptr<content::WebContents> web_contents, gin::Handle<class Session> session, const gin_helper::Dictionary& options); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) void InitWithExtensionView(v8::Isolate* isolate, content::WebContents* web_contents, extensions::mojom::ViewType view_type); #endif // content::WebContentsDelegate: bool DidAddMessageToConsole(content::WebContents* source, blink::mojom::ConsoleMessageLevel level, const std::u16string& message, int32_t line_no, const std::u16string& source_id) override; bool IsWebContentsCreationOverridden( content::SiteInstance* source_site_instance, content::mojom::WindowContainerType window_container_type, const GURL& opener_url, const content::mojom::CreateNewWindowParams& params) override; content::WebContents* CreateCustomWebContents( content::RenderFrameHost* opener, content::SiteInstance* source_site_instance, bool is_new_browsing_instance, const GURL& opener_url, const std::string& frame_name, const GURL& target_url, const content::StoragePartitionConfig& partition_config, content::SessionStorageNamespace* session_storage_namespace) override; void WebContentsCreatedWithFullParams( content::WebContents* source_contents, int opener_render_process_id, int opener_render_frame_id, const content::mojom::CreateNewWindowParams& params, content::WebContents* new_contents) override; void AddNewContents(content::WebContents* source, std::unique_ptr<content::WebContents> new_contents, const GURL& target_url, WindowOpenDisposition disposition, const gfx::Rect& initial_rect, bool user_gesture, bool* was_blocked) override; content::WebContents* OpenURLFromTab( content::WebContents* source, const content::OpenURLParams& params) override; void BeforeUnloadFired(content::WebContents* tab, bool proceed, bool* proceed_to_fire_unload) override; void SetContentsBounds(content::WebContents* source, const gfx::Rect& pos) override; void CloseContents(content::WebContents* source) override; void ActivateContents(content::WebContents* contents) override; void UpdateTargetURL(content::WebContents* source, const GURL& url) override; bool HandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) override; bool PlatformHandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event); content::KeyboardEventProcessingResult PreHandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) override; void ContentsZoomChange(bool zoom_in) override; void EnterFullscreenModeForTab( content::RenderFrameHost* requesting_frame, const blink::mojom::FullscreenOptions& options) override; void ExitFullscreenModeForTab(content::WebContents* source) override; void RendererUnresponsive( content::WebContents* source, content::RenderWidgetHost* render_widget_host, base::RepeatingClosure hang_monitor_restarter) override; void RendererResponsive( content::WebContents* source, content::RenderWidgetHost* render_widget_host) override; bool HandleContextMenu(content::RenderFrameHost& render_frame_host, const content::ContextMenuParams& params) override; bool OnGoToEntryOffset(int offset) override; void FindReply(content::WebContents* web_contents, int request_id, int number_of_matches, const gfx::Rect& selection_rect, int active_match_ordinal, bool final_update) override; void RequestExclusivePointerAccess(content::WebContents* web_contents, bool user_gesture, bool last_unlocked_by_target, bool allowed); void RequestToLockMouse(content::WebContents* web_contents, bool user_gesture, bool last_unlocked_by_target) override; void LostMouseLock() override; void RequestKeyboardLock(content::WebContents* web_contents, bool esc_key_locked) override; void CancelKeyboardLockRequest(content::WebContents* web_contents) override; bool CheckMediaAccessPermission(content::RenderFrameHost* render_frame_host, const GURL& security_origin, blink::mojom::MediaStreamType type) override; void RequestMediaAccessPermission( content::WebContents* web_contents, const content::MediaStreamRequest& request, content::MediaResponseCallback callback) override; content::JavaScriptDialogManager* GetJavaScriptDialogManager( content::WebContents* source) override; void OnAudioStateChanged(bool audible) override; void UpdatePreferredSize(content::WebContents* web_contents, const gfx::Size& pref_size) override; // content::WebContentsObserver: void BeforeUnloadFired(bool proceed, const base::TimeTicks& proceed_time) override; void OnBackgroundColorChanged() override; void RenderFrameCreated(content::RenderFrameHost* render_frame_host) override; void RenderFrameDeleted(content::RenderFrameHost* render_frame_host) override; void RenderFrameHostChanged(content::RenderFrameHost* old_host, content::RenderFrameHost* new_host) override; void FrameDeleted(int frame_tree_node_id) override; void RenderViewDeleted(content::RenderViewHost*) override; void PrimaryMainFrameRenderProcessGone( base::TerminationStatus status) override; void DOMContentLoaded(content::RenderFrameHost* render_frame_host) override; void DidFinishLoad(content::RenderFrameHost* render_frame_host, const GURL& validated_url) override; void DidFailLoad(content::RenderFrameHost* render_frame_host, const GURL& validated_url, int error_code) override; void DidStartLoading() override; void DidStopLoading() override; void DidStartNavigation( content::NavigationHandle* navigation_handle) override; void DidRedirectNavigation( content::NavigationHandle* navigation_handle) override; void ReadyToCommitNavigation( content::NavigationHandle* navigation_handle) override; void DidFinishNavigation( content::NavigationHandle* navigation_handle) override; void WebContentsDestroyed() override; void NavigationEntryCommitted( const content::LoadCommittedDetails& load_details) override; void TitleWasSet(content::NavigationEntry* entry) override; void DidUpdateFaviconURL( content::RenderFrameHost* render_frame_host, const std::vector<blink::mojom::FaviconURLPtr>& urls) override; void PluginCrashed(const base::FilePath& plugin_path, base::ProcessId plugin_pid) override; void MediaStartedPlaying(const MediaPlayerInfo& video_type, const content::MediaPlayerId& id) override; void MediaStoppedPlaying( const MediaPlayerInfo& video_type, const content::MediaPlayerId& id, content::WebContentsObserver::MediaStoppedReason reason) override; void DidChangeThemeColor() override; void OnCursorChanged(const content::WebCursor& cursor) override; void DidAcquireFullscreen(content::RenderFrameHost* rfh) override; void OnWebContentsFocused( content::RenderWidgetHost* render_widget_host) override; void OnWebContentsLostFocus( content::RenderWidgetHost* render_widget_host) override; // InspectableWebContentsDelegate: void DevToolsReloadPage() override; // InspectableWebContentsViewDelegate: void DevToolsFocused() override; void DevToolsOpened() override; void DevToolsClosed() override; void DevToolsResized() override; ElectronBrowserContext* GetBrowserContext() const; void OnElectronBrowserConnectionError(); #if BUILDFLAG(ENABLE_OSR) OffScreenWebContentsView* GetOffScreenWebContentsView() const; OffScreenRenderWidgetHostView* GetOffScreenRenderWidgetHostView() const; #endif // Called when received a synchronous message from renderer to // get the zoom level. void OnGetZoomLevel(content::RenderFrameHost* frame_host, IPC::Message* reply_msg); void InitZoomController(content::WebContents* web_contents, const gin_helper::Dictionary& options); // content::WebContentsDelegate: bool CanOverscrollContent() override; std::unique_ptr<content::EyeDropper> OpenEyeDropper( content::RenderFrameHost* frame, content::EyeDropperListener* listener) override; void RunFileChooser(content::RenderFrameHost* render_frame_host, scoped_refptr<content::FileSelectListener> listener, const blink::mojom::FileChooserParams& params) override; void EnumerateDirectory(content::WebContents* web_contents, scoped_refptr<content::FileSelectListener> listener, const base::FilePath& path) override; // ExclusiveAccessContext: Profile* GetProfile() override; bool IsFullscreen() const override; void EnterFullscreen(const GURL& url, ExclusiveAccessBubbleType bubble_type, const int64_t display_id) override; void ExitFullscreen() override; void UpdateExclusiveAccessExitBubbleContent( const GURL& url, ExclusiveAccessBubbleType bubble_type, ExclusiveAccessBubbleHideCallback bubble_first_hide_callback, bool force_update) override; void OnExclusiveAccessUserInput() override; content::WebContents* GetActiveWebContents() override; bool CanUserExitFullscreen() const override; bool IsExclusiveAccessBubbleDisplayed() const override; bool IsFullscreenForTabOrPending(const content::WebContents* source) override; bool TakeFocus(content::WebContents* source, bool reverse) override; content::PictureInPictureResult EnterPictureInPicture( content::WebContents* web_contents) override; void ExitPictureInPicture() override; // InspectableWebContentsDelegate: void DevToolsSaveToFile(const std::string& url, const std::string& content, bool save_as) override; void DevToolsAppendToFile(const std::string& url, const std::string& content) override; void DevToolsRequestFileSystems() override; void DevToolsAddFileSystem(const std::string& type, const base::FilePath& file_system_path) override; void DevToolsRemoveFileSystem( const base::FilePath& file_system_path) override; void DevToolsIndexPath(int request_id, const std::string& file_system_path, const std::string& excluded_folders_message) override; void DevToolsStopIndexing(int request_id) override; void DevToolsSearchInPath(int request_id, const std::string& file_system_path, const std::string& query) override; void DevToolsSetEyeDropperActive(bool active) override; // InspectableWebContentsViewDelegate: #if defined(TOOLKIT_VIEWS) && !BUILDFLAG(IS_MAC) ui::ImageModel GetDevToolsWindowIcon() override; #endif #if BUILDFLAG(IS_LINUX) void GetDevToolsWindowWMClass(std::string* name, std::string* class_name) override; #endif void ColorPickedInEyeDropper(int r, int g, int b, int a); // DevTools index event callbacks. void OnDevToolsIndexingWorkCalculated(int request_id, const std::string& file_system_path, int total_work); void OnDevToolsIndexingWorked(int request_id, const std::string& file_system_path, int worked); void OnDevToolsIndexingDone(int request_id, const std::string& file_system_path); void OnDevToolsSearchCompleted(int request_id, const std::string& file_system_path, const std::vector<std::string>& file_paths); // Set fullscreen mode triggered by html api. void SetHtmlApiFullscreen(bool enter_fullscreen); // Update the html fullscreen flag in both browser and renderer. void UpdateHtmlApiFullscreen(bool fullscreen); v8::Global<v8::Value> session_; v8::Global<v8::Value> devtools_web_contents_; v8::Global<v8::Value> debugger_; std::unique_ptr<ElectronJavaScriptDialogManager> dialog_manager_; std::unique_ptr<WebViewGuestDelegate> guest_delegate_; std::unique_ptr<FrameSubscriber> frame_subscriber_; #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) std::unique_ptr<extensions::ScriptExecutor> script_executor_; #endif // The host webcontents that may contain this webcontents. WebContents* embedder_ = nullptr; // Whether the guest view has been attached. bool attached_ = false; // The zoom controller for this webContents. WebContentsZoomController* zoom_controller_ = nullptr; // The type of current WebContents. Type type_ = Type::kBrowserWindow; int32_t id_; // Request id used for findInPage request. uint32_t find_in_page_request_id_ = 0; // Whether background throttling is disabled. bool background_throttling_ = true; // Whether to enable devtools. bool enable_devtools_ = true; // Observers of this WebContents. base::ObserverList<ExtendedWebContentsObserver> observers_; v8::Global<v8::Value> pending_child_web_preferences_; // The window that this WebContents belongs to. base::WeakPtr<NativeWindow> owner_window_; bool offscreen_ = false; // Whether window is fullscreened by HTML5 api. bool html_fullscreen_ = false; // Whether window is fullscreened by window api. bool native_fullscreen_ = false; scoped_refptr<DevToolsFileSystemIndexer> devtools_file_system_indexer_; std::unique_ptr<ExclusiveAccessManager> exclusive_access_manager_; std::unique_ptr<DevToolsEyeDropper> eye_dropper_; ElectronBrowserContext* browser_context_; // The stored InspectableWebContents object. // Notice that inspectable_web_contents_ must be placed after // dialog_manager_, so we can make sure inspectable_web_contents_ is // destroyed before dialog_manager_, otherwise a crash would happen. std::unique_ptr<InspectableWebContents> inspectable_web_contents_; // Maps url to file path, used by the file requests sent from devtools. typedef std::map<std::string, base::FilePath> PathsMap; PathsMap saved_files_; // Map id to index job, used for file system indexing requests from devtools. typedef std:: map<int, scoped_refptr<DevToolsFileSystemIndexer::FileSystemIndexingJob>> DevToolsIndexingJobsMap; DevToolsIndexingJobsMap devtools_indexing_jobs_; scoped_refptr<base::SequencedTaskRunner> file_task_runner_; #if BUILDFLAG(ENABLE_PRINTING) scoped_refptr<base::TaskRunner> print_task_runner_; #endif // Stores the frame thats currently in fullscreen, nullptr if there is none. content::RenderFrameHost* fullscreen_frame_ = nullptr; // In-memory cache that holds objects that have been granted permissions. DevicePermissionMap granted_devices_; base::WeakPtrFactory<WebContents> weak_factory_{this}; }; } // namespace api } // namespace electron #endif // ELECTRON_SHELL_BROWSER_API_ELECTRON_API_WEB_CONTENTS_H_
closed
electron/electron
https://github.com/electron/electron
34,270
DCHECK on `webContents.print()`
Introduced by https://github.com/electron/electron/pull/33906. Root Cause: https://chromium-review.googlesource.com/c/chromium/src/+/3579297 <details> <summary> Stacktrace </summary> ``` [46358:0518/110313.131061:FATAL:values_mojom_traits.h(100)] Check failed: value.is_dict(). 0 Electron Framework 0x000000012ef92ba9 base::debug::CollectStackTrace(void**, unsigned long) + 9 1 Electron Framework 0x000000012eeb3ac3 base::debug::StackTrace::StackTrace() + 19 2 Electron Framework 0x000000012eecccdf logging::LogMessage::~LogMessage() + 175 3 Electron Framework 0x000000012eecdd2e logging::LogMessage::~LogMessage() + 14 4 Electron Framework 0x000000012a9ed02a mojo::internal::Serializer<mojo_base::mojom::DeprecatedDictionaryValueDataView, base::Value>::Serialize(base::Value&, mojo::internal::MessageFragment<mojo_base::mojom::internal::DeprecatedDictionaryValue_Data>&) + 90 5 Electron Framework 0x000000012e7582da printing::mojom::PrintRenderFrameProxy::PrintRequestedPages(bool, base::Value) + 362 6 Electron Framework 0x0000000133f15232 printing::PrintViewManagerBase::CompletePrintNow(content::RenderFrameHost*) + 146 7 Electron Framework 0x0000000133f14f3b printing::PrintViewManagerBase::PrintNow(content::RenderFrameHost*, bool, base::Value, base::OnceCallback<void (bool, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)>) + 395 8 Electron Framework 0x000000012a56ed16 electron::api::WebContents::OnGetDefaultPrinter(base::Value, base::OnceCallback<void (bool, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)>, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> >, bool, std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > >) + 1686 9 Electron Framework 0x000000012a580b93 void base::internal::FunctorTraits<void (electron::api::WebContents::*)(base::Value, base::OnceCallback<void (bool, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)>, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> >, bool, std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > >), void>::Invoke<void (electron::api::WebContents::*)(base::Value, base::OnceCallback<void (bool, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)>, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> >, bool, std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > >), base::WeakPtr<electron::api::WebContents>, base::Value, base::OnceCallback<void (bool, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)>, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> >, bool, std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > > >(void (electron::api::WebContents::*)(base::Value, base::OnceCallback<void (bool, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)>, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> >, bool, std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > >), base::WeakPtr<electron::api::WebContents>&&, base::Value&&, base::OnceCallback<void (bool, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)>&&, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> >&&, bool&&, std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > >&&) + 291 10 Electron Framework 0x000000012a58099d base::internal::Invoker<base::internal::BindState<void (electron::api::WebContents::*)(base::Value, base::OnceCallback<void (bool, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)>, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> >, bool, std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > >), base::WeakPtr<electron::api::WebContents>, base::Value, base::OnceCallback<void (bool, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)>, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> >, bool>, void (std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > >)>::RunOnce(base::internal::BindStateBase*, std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > >&&) + 77 11 Electron Framework 0x000000012a581102 void base::internal::ReplyAdapter<std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > >, std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > > >(base::OnceCallback<void (std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > >)>, std::__1::unique_ptr<std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > >, std::__1::default_delete<std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > > > >*) + 210 12 Electron Framework 0x000000012a4f9627 base::internal::Invoker<base::internal::BindState<void (*)(base::OnceCallback<(anonymous namespace)::CloseFileResult ()>, std::__1::unique_ptr<(anonymous namespace)::CloseFileResult, std::__1::default_delete<(anonymous namespace)::CloseFileResult> >*), base::OnceCallback<(anonymous namespace)::CloseFileResult ()>, base::internal::UnretainedWrapper<std::__1::unique_ptr<(anonymous namespace)::CloseFileResult, std::__1::default_delete<(anonymous namespace)::CloseFileResult> > > >, void ()>::RunOnce(base::internal::BindStateBase*) + 39 13 Electron Framework 0x000000012ef74403 base::(anonymous namespace)::PostTaskAndReplyRelay::RunReply(base::(anonymous namespace)::PostTaskAndReplyRelay) + 211 14 Electron Framework 0x000000012ef74499 base::internal::Invoker<base::internal::BindState<void (*)(base::(anonymous namespace)::PostTaskAndReplyRelay), base::(anonymous namespace)::PostTaskAndReplyRelay>, void ()>::RunOnce(base::internal::BindStateBase*) + 73 15 Electron Framework 0x000000012ef261f9 base::TaskAnnotator::RunTaskImpl(base::PendingTask&) + 313 16 Electron Framework 0x000000012ef4e1ca base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::DoWorkImpl(base::sequence_manager::LazyNow*) + 1066 17 Electron Framework 0x000000012ef4d88e base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::DoWork() + 126 18 Electron Framework 0x000000012ef4e9e2 non-virtual thunk to base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::DoWork() + 18 19 Electron Framework 0x000000012efa83e1 base::MessagePumpCFRunLoopBase::RunWork() + 97 20 Electron Framework 0x000000012efa78c2 base::mac::CallWithEHFrame(void () block_pointer) + 10 21 Electron Framework 0x000000012efa7e0f base::MessagePumpCFRunLoopBase::RunWorkSource(void*) + 63 22 CoreFoundation 0x00007ff80b673aeb __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17 23 CoreFoundation 0x00007ff80b673a53 __CFRunLoopDoSource0 + 180 24 CoreFoundation 0x00007ff80b6737cd __CFRunLoopDoSources0 + 242 25 CoreFoundation 0x00007ff80b6721e8 __CFRunLoopRun + 892 26 CoreFoundation 0x00007ff80b6717ac CFRunLoopRunSpecific + 562 27 HIToolbox 0x00007ff8142f8ce6 RunCurrentEventLoopInMode + 292 28 HIToolbox 0x00007ff8142f8a4a ReceiveNextEventCommon + 594 29 HIToolbox 0x00007ff8142f87e5 _BlockUntilNextEventMatchingListInModeWithFilter + 70 30 AppKit 0x00007ff80e09853d _DPSNextEvent + 927 31 AppKit 0x00007ff80e096bfa -[NSApplication(NSEvent) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] + 1394 32 AppKit 0x00007ff80e0892a9 -[NSApplication run] + 586 33 Electron Framework 0x000000012efa8e7c base::MessagePumpNSApplication::DoRun(base::MessagePump::Delegate*) + 348 34 Electron Framework 0x000000012efa796b base::MessagePumpCFRunLoopBase::Run(base::MessagePump::Delegate*) + 155 35 Electron Framework 0x000000012ef4ef97 base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::Run(bool, base::TimeDelta) + 695 36 Electron Framework 0x000000012ef01dc6 base::RunLoop::Run(base::Location const&) + 726 37 Electron Framework 0x000000012dac4c83 content::BrowserMainLoop::RunMainMessageLoop() + 243 38 Electron Framework 0x000000012dac6822 content::BrowserMainRunnerImpl::Run() + 82 39 Electron Framework 0x000000012dac1fce content::BrowserMain(content::MainFunctionParams) + 270 40 Electron Framework 0x000000012a90bd12 content::RunBrowserProcessMain(content::MainFunctionParams, content::ContentMainDelegate*) + 258 41 Electron Framework 0x000000012a90d28b content::ContentMainRunnerImpl::RunBrowser(content::MainFunctionParams, bool) + 1403 42 Electron Framework 0x000000012a90cc90 content::ContentMainRunnerImpl::Run() + 736 43 Electron Framework 0x000000012a90b637 content::RunContentProcess(content::ContentMainParams, content::ContentMainRunner*) + 2679 44 Electron Framework 0x000000012a90b752 content::ContentMain(content::ContentMainParams) + 98 45 Electron Framework 0x000000012a4b883d ElectronMain + 157 46 dyld 0x0000000114aee51e start + 462 Task trace: 0 Electron Framework 0x000000012a56f8b0 electron::api::WebContents::Print(gin::Arguments*) + 2832 1 Electron Framework 0x000000012a56f8b0 electron::api::WebContents::Print(gin::Arguments*) + 2832 2 Electron Framework 0x000000012f718430 IPC::(anonymous namespace)::ChannelAssociatedGroupController::Accept(mojo::Message*) + 784 3 Electron Framework 0x000000012f2f4f9e mojo::SimpleWatcher::Context::Notify(unsigned int, MojoHandleSignalsState, unsigned int) + 430 Crash keys: "ui_scheduler_async_stack" = "0x12A56F8B0 0x12A56F8B0" "io_scheduler_async_stack" = "0x12BEBEDDB 0x0" "platform" = "darwin" "process_type" = "browser" ``` </details>
https://github.com/electron/electron/issues/34270
https://github.com/electron/electron/pull/34271
73e0bf973d2b7835290d61cab6638309a21a2719
588005a9d5a74b953961605579cf4ad6f8dc2b20
2022-05-18T09:05:02Z
c++
2022-05-19T08:05:07Z
patches/chromium/printing.patch
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: Shelley Vohr <[email protected]> Date: Fri, 7 Jun 2019 13:59:37 -0700 Subject: printing.patch Add changeset that was previously applied to sources in chromium_src. The majority of changes originally come from these PRs: * https://github.com/electron/electron/pull/1835 * https://github.com/electron/electron/pull/8596 This patch also fixes callback for manual user cancellation and success. diff --git a/chrome/browser/printing/print_job.cc b/chrome/browser/printing/print_job.cc index 331a084371402b5a2440b5d60feac8f0189e84b9..6755d1f497cef4deea6b83df1d8720dcf54817e9 100644 --- a/chrome/browser/printing/print_job.cc +++ b/chrome/browser/printing/print_job.cc @@ -90,6 +90,7 @@ bool PrintWithReducedRasterization(PrefService* prefs) { return base::FeatureList::IsEnabled(features::kPrintWithReducedRasterization); } +#if 0 PrefService* GetPrefsForWebContents(content::WebContents* web_contents) { // TODO(thestig): Figure out why crbug.com/1083911 occurred, which is likely // because `web_contents` was null. As a result, this section has many more @@ -98,6 +99,7 @@ PrefService* GetPrefsForWebContents(content::WebContents* web_contents) { web_contents ? web_contents->GetBrowserContext() : nullptr; return context ? Profile::FromBrowserContext(context)->GetPrefs() : nullptr; } +#endif #endif // BUILDFLAG(IS_WIN) @@ -351,8 +353,10 @@ void PrintJob::StartPdfToEmfConversion( const PrintSettings& settings = document()->settings(); +#if 0 PrefService* prefs = GetPrefsForWebContents(worker_->GetWebContents()); - bool print_with_reduced_rasterization = PrintWithReducedRasterization(prefs); +#endif + bool print_with_reduced_rasterization = PrintWithReducedRasterization(nullptr); using RenderMode = PdfRenderSettings::Mode; RenderMode mode = print_with_reduced_rasterization @@ -442,8 +446,10 @@ void PrintJob::StartPdfToPostScriptConversion( if (ps_level2) { mode = PdfRenderSettings::Mode::POSTSCRIPT_LEVEL2; } else { +#if 0 PrefService* prefs = GetPrefsForWebContents(worker_->GetWebContents()); - mode = PrintWithPostScriptType42Fonts(prefs) +#endif + mode = PrintWithPostScriptType42Fonts(nullptr) ? PdfRenderSettings::Mode::POSTSCRIPT_LEVEL3_WITH_TYPE42_FONTS : PdfRenderSettings::Mode::POSTSCRIPT_LEVEL3; } diff --git a/chrome/browser/printing/print_job_worker.cc b/chrome/browser/printing/print_job_worker.cc index ee713c5686d4ea8a5d73cebf74e67381b685cff6..375ce3294727b84bf0071681c7bc35c772e4e3b9 100644 --- a/chrome/browser/printing/print_job_worker.cc +++ b/chrome/browser/printing/print_job_worker.cc @@ -20,7 +20,6 @@ #include "build/build_config.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/printing/print_job.h" -#include "chrome/grit/generated_resources.h" #include "components/crash/core/common/crash_keys.h" #include "components/device_event_log/device_event_log.h" #include "content/public/browser/browser_task_traits.h" @@ -28,6 +27,7 @@ #include "content/public/browser/global_routing_id.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/web_contents.h" +#include "chrome/grit/generated_resources.h" #include "printing/backend/print_backend.h" #include "printing/buildflags/buildflags.h" #include "printing/mojom/print.mojom.h" @@ -229,16 +229,21 @@ void PrintJobWorker::UpdatePrintSettings(base::Value::Dict new_settings, #endif // BUILDFLAG(IS_LINUX) && defined(USE_CUPS) } - mojom::ResultCode result; { #if BUILDFLAG(IS_WIN) // Blocking is needed here because Windows printer drivers are oftentimes // not thread-safe and have to be accessed on the UI thread. base::ScopedAllowBlocking allow_blocking; #endif - result = printing_context_->UpdatePrintSettings(std::move(new_settings)); + // Reset settings from previous print job + printing_context_->ResetSettings(); + mojom::ResultCode get_default_result = printing_context_->UseDefaultSettings(); + if (get_default_result == mojom::ResultCode::kSuccess) { + mojom::ResultCode update_result = + printing_context_->UpdatePrintSettings(std::move(new_settings)); + GetSettingsDone(std::move(callback), update_result); + } } - GetSettingsDone(std::move(callback), result); } #if BUILDFLAG(IS_CHROMEOS) diff --git a/chrome/browser/printing/print_job_worker_oop.cc b/chrome/browser/printing/print_job_worker_oop.cc index dd27bbf387718d6abda5080e7d2c609cd0eaff17..8837cf2aeaa2f87d51be8d00aa356c8a2c5e15c7 100644 --- a/chrome/browser/printing/print_job_worker_oop.cc +++ b/chrome/browser/printing/print_job_worker_oop.cc @@ -345,7 +345,7 @@ void PrintJobWorkerOop::OnFailure() { } void PrintJobWorkerOop::ShowErrorDialog() { - ShowPrintErrorDialog(); + // [electron]: removed. } void PrintJobWorkerOop::UnregisterServiceManagerClient() { diff --git a/chrome/browser/printing/print_view_manager_base.cc b/chrome/browser/printing/print_view_manager_base.cc index 3701853ada7f0ffe3cc8a798496f9f48541b4f47..a082dd9ee23b6d4918c194161386b973039d3ff6 100644 --- a/chrome/browser/printing/print_view_manager_base.cc +++ b/chrome/browser/printing/print_view_manager_base.cc @@ -30,10 +30,10 @@ #include "chrome/browser/printing/print_view_manager_common.h" #include "chrome/browser/printing/printer_query.h" #include "chrome/browser/profiles/profile.h" -#include "chrome/browser/ui/simple_message_box.h" -#include "chrome/browser/ui/webui/print_preview/printer_handler.h" #include "chrome/common/pref_names.h" +#if 0 #include "chrome/grit/generated_resources.h" +#endif #include "components/prefs/pref_service.h" #include "components/printing/browser/print_composite_client.h" #include "components/printing/browser/print_manager_utils.h" @@ -48,6 +48,7 @@ #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/web_contents.h" +#include "chrome/grit/generated_resources.h" #include "mojo/public/cpp/system/buffer.h" #include "printing/buildflags/buildflags.h" #include "printing/metafile_skia.h" @@ -87,6 +88,8 @@ using PrintSettingsCallback = base::OnceCallback<void(std::unique_ptr<PrinterQuery>)>; void ShowWarningMessageBox(const std::u16string& message) { + LOG(ERROR) << "Invalid printer settings " << message; +#if 0 // Runs always on the UI thread. static bool is_dialog_shown = false; if (is_dialog_shown) @@ -95,6 +98,7 @@ void ShowWarningMessageBox(const std::u16string& message) { base::AutoReset<bool> auto_reset(&is_dialog_shown, true); chrome::ShowWarningMessageBox(nullptr, std::u16string(), message); +#endif } #if BUILDFLAG(ENABLE_PRINT_PREVIEW) @@ -192,7 +196,9 @@ void UpdatePrintSettingsReplyOnIO( DCHECK_CURRENTLY_ON(content::BrowserThread::IO); DCHECK(printer_query); mojom::PrintPagesParamsPtr params = CreateEmptyPrintPagesParamsPtr(); - if (printer_query->last_status() == mojom::ResultCode::kSuccess) { + // We call update without first printing from defaults, + // so the last printer status will still be defaulted to PrintingContext::FAILED + if (printer_query) { RenderParamsFromPrintSettings(printer_query->settings(), params->params.get()); params->params->document_cookie = printer_query->cookie(); @@ -245,6 +251,7 @@ void ScriptedPrintReplyOnIO( mojom::PrintManagerHost::ScriptedPrintCallback callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); mojom::PrintPagesParamsPtr params = CreateEmptyPrintPagesParamsPtr(); + if (printer_query->last_status() == mojom::ResultCode::kSuccess && printer_query->settings().dpi()) { RenderParamsFromPrintSettings(printer_query->settings(), @@ -254,8 +261,9 @@ void ScriptedPrintReplyOnIO( } bool has_valid_cookie = params->params->document_cookie; bool has_dpi = !params->params->dpi.IsEmpty(); + bool canceled = printer_query->last_status() == mojom::ResultCode::kCanceled; content::GetUIThreadTaskRunner({})->PostTask( - FROM_HERE, base::BindOnce(std::move(callback), std::move(params))); + FROM_HERE, base::BindOnce(std::move(callback), std::move(params), canceled)); if (has_dpi && has_valid_cookie) { queue->QueuePrinterQuery(std::move(printer_query)); @@ -293,12 +301,14 @@ PrintViewManagerBase::PrintViewManagerBase(content::WebContents* web_contents) : PrintManager(web_contents), queue_(g_browser_process->print_job_manager()->queue()) { DCHECK(queue_); +#if 0 // Printing is always enabled. Profile* profile = Profile::FromBrowserContext(web_contents->GetBrowserContext()); printing_enabled_.Init( prefs::kPrintingEnabled, profile->GetPrefs(), base::BindRepeating(&PrintViewManagerBase::UpdatePrintingEnabled, weak_ptr_factory_.GetWeakPtr())); +#endif } PrintViewManagerBase::~PrintViewManagerBase() { @@ -306,7 +316,10 @@ PrintViewManagerBase::~PrintViewManagerBase() { DisconnectFromCurrentPrintJob(); } -bool PrintViewManagerBase::PrintNow(content::RenderFrameHost* rfh) { +bool PrintViewManagerBase::PrintNow(content::RenderFrameHost* rfh, + bool silent, + base::Value settings, + CompletionCallback callback) { // Remember the ID for `rfh`, to enable checking that the `RenderFrameHost` // is still valid after a possible inner message loop runs in // `DisconnectFromCurrentPrintJob()`. @@ -332,6 +345,9 @@ bool PrintViewManagerBase::PrintNow(content::RenderFrameHost* rfh) { #endif SetPrintingRFH(rfh); + callback_ = std::move(callback); + + GetPrintRenderFrame(rfh)->PrintRequestedPages(silent, std::move(settings)); #if BUILDFLAG(ENABLE_PRINT_CONTENT_ANALYSIS) enterprise_connectors::ContentAnalysisDelegate::Data scanning_data; @@ -500,7 +516,8 @@ void PrintViewManagerBase::GetDefaultPrintSettingsReply( void PrintViewManagerBase::ScriptedPrintReply( ScriptedPrintCallback callback, int process_id, - mojom::PrintPagesParamsPtr params) { + mojom::PrintPagesParamsPtr params, + bool canceled) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); #if BUILDFLAG(ENABLE_OOP_PRINTING) @@ -513,16 +530,19 @@ void PrintViewManagerBase::ScriptedPrintReply( return; } + if (canceled) + UserInitCanceled(); + set_cookie(params->params->document_cookie); - std::move(callback).Run(std::move(params)); + std::move(callback).Run(std::move(params), canceled); } void PrintViewManagerBase::UpdatePrintingEnabled() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); // The Unretained() is safe because ForEachRenderFrameHost() is synchronous. - web_contents()->GetMainFrame()->ForEachRenderFrameHost(base::BindRepeating( - &PrintViewManagerBase::SendPrintingEnabled, base::Unretained(this), - printing_enabled_.GetValue())); + web_contents()->GetMainFrame()->ForEachRenderFrameHost( + base::BindRepeating(&PrintViewManagerBase::SendPrintingEnabled, + base::Unretained(this), true)); } void PrintViewManagerBase::NavigationStopped() { @@ -638,11 +658,14 @@ void PrintViewManagerBase::DidPrintDocument( void PrintViewManagerBase::GetDefaultPrintSettings( GetDefaultPrintSettingsCallback callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); +#if 0 // Printing is always enabled. + if (!printing_enabled_.GetValue()) { GetDefaultPrintSettingsReply(std::move(callback), mojom::PrintParams::New()); return; } +#endif #if BUILDFLAG(ENABLE_OOP_PRINTING) if (printing::features::kEnableOopPrintDriversJobPrint.Get() && !service_manager_client_id_.has_value()) { @@ -672,18 +695,20 @@ void PrintViewManagerBase::UpdatePrintSettings( base::Value::Dict job_settings, UpdatePrintSettingsCallback callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); +#if 0 // Printing is always enabled. if (!printing_enabled_.GetValue()) { UpdatePrintSettingsReply(std::move(callback), CreateEmptyPrintPagesParamsPtr(), false); return; } - +#endif if (!job_settings.FindInt(kSettingPrinterType)) { UpdatePrintSettingsReply(std::move(callback), CreateEmptyPrintPagesParamsPtr(), false); return; } +#if 0 content::BrowserContext* context = web_contents() ? web_contents()->GetBrowserContext() : nullptr; PrefService* prefs = @@ -693,6 +718,7 @@ void PrintViewManagerBase::UpdatePrintSettings( if (value > 0) job_settings.Set(kSettingRasterizePdfDpi, value); } +#endif auto callback_wrapper = base::BindOnce(&PrintViewManagerBase::UpdatePrintSettingsReply, @@ -718,14 +744,14 @@ void PrintViewManagerBase::ScriptedPrint(mojom::ScriptedPrintParamsPtr params, // didn't happen for some reason. bad_message::ReceivedBadMessage( render_process_host, bad_message::PVMB_SCRIPTED_PRINT_FENCED_FRAME); - std::move(callback).Run(CreateEmptyPrintPagesParamsPtr()); + std::move(callback).Run(CreateEmptyPrintPagesParamsPtr(), false); return; } #if BUILDFLAG(ENABLE_OOP_PRINTING) if (printing::features::kEnableOopPrintDriversJobPrint.Get() && !service_manager_client_id_.has_value()) { // Renderer process has requested settings outside of the expected setup. - std::move(callback).Run(CreateEmptyPrintPagesParamsPtr()); + std::move(callback).Run(CreateEmptyPrintPagesParamsPtr(), false); return; } #endif @@ -763,7 +789,6 @@ void PrintViewManagerBase::PrintingFailed(int32_t cookie, PrintManager::PrintingFailed(cookie, reason); #if !BUILDFLAG(IS_ANDROID) // Android does not implement this function. - ShowPrintErrorDialog(); #endif ReleasePrinterQuery(); @@ -778,6 +803,11 @@ void PrintViewManagerBase::RemoveObserver(Observer& observer) { } void PrintViewManagerBase::ShowInvalidPrinterSettingsError() { + if (!callback_.is_null()) { + std::string cb_str = "Invalid printer settings"; + std::move(callback_).Run(printing_succeeded_, cb_str); + } + base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(&ShowWarningMessageBox, l10n_util::GetStringUTF16( @@ -788,10 +818,12 @@ void PrintViewManagerBase::RenderFrameHostStateChanged( content::RenderFrameHost* render_frame_host, content::RenderFrameHost::LifecycleState /*old_state*/, content::RenderFrameHost::LifecycleState new_state) { +#if 0 if (new_state == content::RenderFrameHost::LifecycleState::kActive && render_frame_host->GetProcess()->IsPdf()) { SendPrintingEnabled(printing_enabled_.GetValue(), render_frame_host); } +#endif } void PrintViewManagerBase::DidStartLoading() { @@ -851,6 +883,11 @@ void PrintViewManagerBase::OnJobDone() { ReleasePrintJob(); } +void PrintViewManagerBase::UserInitCanceled() { + printing_canceled_ = true; + ReleasePrintJob(); +} + void PrintViewManagerBase::OnFailed() { TerminatePrintJob(true); } @@ -908,7 +945,10 @@ bool PrintViewManagerBase::CreateNewPrintJob( // Disconnect the current |print_job_|. auto weak_this = weak_ptr_factory_.GetWeakPtr(); - DisconnectFromCurrentPrintJob(); + if (callback_.is_null()) { + // Disconnect the current |print_job_| only when calling window.print() + DisconnectFromCurrentPrintJob(); + } if (!weak_this) return false; @@ -987,6 +1027,13 @@ void PrintViewManagerBase::ReleasePrintJob() { UnregisterSystemPrintClient(); #endif + if (!callback_.is_null()) { + std::string cb_str = ""; + if (!printing_succeeded_) + cb_str = printing_canceled_ ? "canceled" : "failed"; + std::move(callback_).Run(printing_succeeded_, cb_str); + } + if (!print_job_) return; @@ -1036,7 +1083,7 @@ bool PrintViewManagerBase::RunInnerMessageLoop() { } bool PrintViewManagerBase::OpportunisticallyCreatePrintJob(int cookie) { - if (print_job_) + if (print_job_ && print_job_->document()) return true; if (!cookie) { @@ -1144,7 +1191,7 @@ void PrintViewManagerBase::SendPrintingEnabled(bool enabled, } void PrintViewManagerBase::CompletePrintNow(content::RenderFrameHost* rfh) { - GetPrintRenderFrame(rfh)->PrintRequestedPages(); + GetPrintRenderFrame(rfh)->PrintRequestedPages(true/*silent*/, base::Value{}/*job_settings*/); for (auto& observer : GetObservers()) observer.OnPrintNow(rfh); diff --git a/chrome/browser/printing/print_view_manager_base.h b/chrome/browser/printing/print_view_manager_base.h index 746df417a23f7760818ba265d4a7d589dec8bf34..5566e7dc2929a2542c599fed91fb1eeeb866e7bb 100644 --- a/chrome/browser/printing/print_view_manager_base.h +++ b/chrome/browser/printing/print_view_manager_base.h @@ -41,6 +41,8 @@ namespace printing { class PrintQueriesQueue; class PrinterQuery; +using CompletionCallback = base::OnceCallback<void(bool, const std::string&)>; + // Base class for managing the print commands for a WebContents. class PrintViewManagerBase : public PrintManager, public PrintJob::Observer { public: @@ -64,7 +66,10 @@ class PrintViewManagerBase : public PrintManager, public PrintJob::Observer { // Prints the current document immediately. Since the rendering is // asynchronous, the actual printing will not be completed on the return of // this function. Returns false if printing is impossible at the moment. - virtual bool PrintNow(content::RenderFrameHost* rfh); + virtual bool PrintNow(content::RenderFrameHost* rfh, + bool silent = true, + base::Value settings = {}, + CompletionCallback callback = {}); #if BUILDFLAG(ENABLE_PRINT_PREVIEW) // Prints the document in `print_data` with settings specified in @@ -113,6 +118,7 @@ class PrintViewManagerBase : public PrintManager, public PrintJob::Observer { void ShowInvalidPrinterSettingsError() override; void PrintingFailed(int32_t cookie, mojom::PrintFailureReason reason) override; + void UserInitCanceled(); // Adds and removes observers for `PrintViewManagerBase` events. The order in // which notifications are sent to observers is undefined. Observers must be @@ -241,7 +247,8 @@ class PrintViewManagerBase : public PrintManager, public PrintJob::Observer { // Runs `callback` with `params` to reply to ScriptedPrint(). void ScriptedPrintReply(ScriptedPrintCallback callback, int process_id, - mojom::PrintPagesParamsPtr params); + mojom::PrintPagesParamsPtr params, + bool canceled); // Requests the RenderView to render all the missing pages for the print job. // No-op if no print job is pending. Returns true if at least one page has @@ -314,9 +321,15 @@ class PrintViewManagerBase : public PrintManager, public PrintJob::Observer { // The current RFH that is printing with a system printing dialog. raw_ptr<content::RenderFrameHost> printing_rfh_ = nullptr; + // Respond with success of the print job. + CompletionCallback callback_; + // Indication of success of the print job. bool printing_succeeded_ = false; + // Indication of whether the print job was manually canceled + bool printing_canceled_ = false; + // Set while running an inner message loop inside RenderAllMissingPagesNow(). // This means we are _blocking_ until all the necessary pages have been // rendered or the print settings are being loaded. diff --git a/chrome/browser/ui/webui/print_preview/fake_print_render_frame.cc b/chrome/browser/ui/webui/print_preview/fake_print_render_frame.cc index aa727261738698610fab5abd3618d0d0f0d29792..8f95dae637ce25a073872ecdf229f14cc6d0614c 100644 --- a/chrome/browser/ui/webui/print_preview/fake_print_render_frame.cc +++ b/chrome/browser/ui/webui/print_preview/fake_print_render_frame.cc @@ -21,7 +21,7 @@ FakePrintRenderFrame::FakePrintRenderFrame( FakePrintRenderFrame::~FakePrintRenderFrame() = default; -void FakePrintRenderFrame::PrintRequestedPages() {} +void FakePrintRenderFrame::PrintRequestedPages(bool /*silent*/, ::base::Value /*settings*/) {} void FakePrintRenderFrame::PrintWithParams(mojom::PrintPagesParamsPtr params) { NOTREACHED(); diff --git a/chrome/browser/ui/webui/print_preview/fake_print_render_frame.h b/chrome/browser/ui/webui/print_preview/fake_print_render_frame.h index 5f4d6e314b21351e3e5912e3a43ef87774343085..2a93fe0139025d1a40b3f8e81378ee4213ac27c1 100644 --- a/chrome/browser/ui/webui/print_preview/fake_print_render_frame.h +++ b/chrome/browser/ui/webui/print_preview/fake_print_render_frame.h @@ -25,7 +25,7 @@ class FakePrintRenderFrame : public mojom::PrintRenderFrame { private: // printing::mojom::PrintRenderFrame: - void PrintRequestedPages() override; + void PrintRequestedPages(bool silent, ::base::Value settings) override; void PrintWithParams(mojom::PrintPagesParamsPtr params) override; void PrintForSystemDialog() override; void SetPrintPreviewUI( diff --git a/components/printing/browser/print_to_pdf/pdf_print_manager.cc b/components/printing/browser/print_to_pdf/pdf_print_manager.cc index 82591f8c2abbc1a180ef62f7264a68ca279e9b9c..ad27a15ba3028af1046482192dec789df5dda7b2 100644 --- a/components/printing/browser/print_to_pdf/pdf_print_manager.cc +++ b/components/printing/browser/print_to_pdf/pdf_print_manager.cc @@ -132,7 +132,8 @@ void PdfPrintManager::PrintToPdf( set_cookie(print_pages_params->params->document_cookie); callback_ = std::move(callback); - GetPrintRenderFrame(rfh)->PrintWithParams(std::move(print_pages_params)); + // TODO(electron-maintainers): do something with job_settings here? + GetPrintRenderFrame(rfh)->PrintRequestedPages(true/*silent*/, base::Value{}/*job_settings*/); } void PdfPrintManager::GetDefaultPrintSettings( @@ -147,7 +148,7 @@ void PdfPrintManager::ScriptedPrint( auto default_param = printing::mojom::PrintPagesParams::New(); default_param->params = printing::mojom::PrintParams::New(); DLOG(ERROR) << "Scripted print is not supported"; - std::move(callback).Run(std::move(default_param)); + std::move(callback).Run(std::move(default_param), true/*canceled*/); } void PdfPrintManager::ShowInvalidPrinterSettingsError() { diff --git a/components/printing/common/print.mojom b/components/printing/common/print.mojom index 8e5c441b3d0a2d35fc5c6f9d43b4a4ca167e09ca..fa53eb1c9dd4e7a6b321bdd4cda2164b95244323 100644 --- a/components/printing/common/print.mojom +++ b/components/printing/common/print.mojom @@ -280,7 +280,7 @@ enum PrintFailureReason { interface PrintRenderFrame { // Tells the RenderFrame to switch the CSS to print media type, render every // requested page, and then switch back the CSS to display media type. - PrintRequestedPages(); + PrintRequestedPages(bool silent, mojo_base.mojom.DeprecatedDictionaryValue settings); // Requests the frame to be printed with specified parameters. This is used // to programmatically produce PDF by request from the browser (e.g. over @@ -362,7 +362,7 @@ interface PrintManagerHost { // Request the print settings from the user. This step is about showing // UI to the user to select the final print settings. [Sync] - ScriptedPrint(ScriptedPrintParams params) => (PrintPagesParams settings); + ScriptedPrint(ScriptedPrintParams params) => (PrintPagesParams settings, bool canceled); // Tells the browser that there are invalid printer settings. ShowInvalidPrinterSettingsError(); diff --git a/components/printing/renderer/print_render_frame_helper.cc b/components/printing/renderer/print_render_frame_helper.cc index db8913ae41d46d14fd15c6127e126e4b129dc4b8..64ee08e9091e4d67ff55097bc22177d9567214a1 100644 --- a/components/printing/renderer/print_render_frame_helper.cc +++ b/components/printing/renderer/print_render_frame_helper.cc @@ -42,6 +42,7 @@ #include "printing/mojom/print.mojom.h" #include "printing/page_number.h" #include "printing/print_job_constants.h" +#include "printing/print_settings.h" #include "printing/units.h" #include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h" #include "third_party/blink/public/common/associated_interfaces/associated_interface_registry.h" @@ -1277,7 +1278,8 @@ void PrintRenderFrameHelper::ScriptedPrint(bool user_initiated) { if (!weak_this) return; - Print(web_frame, blink::WebNode(), PrintRequestType::kScripted); + Print(web_frame, blink::WebNode(), PrintRequestType::kScripted, + false /* silent */, base::DictionaryValue() /* new_settings */); if (!weak_this) return; @@ -1308,7 +1310,7 @@ void PrintRenderFrameHelper::BindPrintRenderFrameReceiver( receivers_.Add(this, std::move(receiver)); } -void PrintRenderFrameHelper::PrintRequestedPages() { +void PrintRenderFrameHelper::PrintRequestedPages(bool silent, base::Value settings) { ScopedIPC scoped_ipc(weak_ptr_factory_.GetWeakPtr()); if (ipc_nesting_level_ > kAllowedIpcDepthForPrint) return; @@ -1323,7 +1325,7 @@ void PrintRenderFrameHelper::PrintRequestedPages() { // plugin node and print that instead. auto plugin = delegate_->GetPdfElement(frame); - Print(frame, plugin, PrintRequestType::kRegular); + Print(frame, plugin, PrintRequestType::kRegular, silent, std::move(settings)); if (!render_frame_gone_) frame->DispatchAfterPrintEvent(); @@ -1389,7 +1391,8 @@ void PrintRenderFrameHelper::PrintForSystemDialog() { } Print(frame, print_preview_context_.source_node(), - PrintRequestType::kRegular); + PrintRequestType::kRegular, false, + base::DictionaryValue()); if (!render_frame_gone_) print_preview_context_.DispatchAfterPrintEvent(); // WARNING: |this| may be gone at this point. Do not do any more work here and @@ -1438,6 +1441,8 @@ void PrintRenderFrameHelper::PrintPreview(base::Value settings) { if (ipc_nesting_level_ > kAllowedIpcDepthForPrint) return; + blink::WebLocalFrame* frame = render_frame()->GetWebFrame(); + print_preview_context_.InitWithFrame(frame); print_preview_context_.OnPrintPreview(); #if BUILDFLAG(IS_CHROMEOS_ASH) @@ -2051,7 +2056,8 @@ void PrintRenderFrameHelper::PrintNode(const blink::WebNode& node) { return; Print(duplicate_node.GetDocument().GetFrame(), duplicate_node, - PrintRequestType::kRegular); + PrintRequestType::kRegular, false /* silent */, + base::DictionaryValue() /* new_settings */); // Check if |this| is still valid. if (!weak_this) return; @@ -2066,7 +2072,9 @@ void PrintRenderFrameHelper::PrintNode(const blink::WebNode& node) { void PrintRenderFrameHelper::Print(blink::WebLocalFrame* frame, const blink::WebNode& node, - PrintRequestType print_request_type) { + PrintRequestType print_request_type, + bool silent, + base::Value settings) { // If still not finished with earlier print request simply ignore. if (prep_frame_view_) return; @@ -2074,7 +2082,7 @@ void PrintRenderFrameHelper::Print(blink::WebLocalFrame* frame, FrameReference frame_ref(frame); uint32_t expected_page_count = 0; - if (!CalculateNumberOfPages(frame, node, &expected_page_count)) { + if (!CalculateNumberOfPages(frame, node, &expected_page_count, base::Value::AsDictionaryValue(settings))) { DidFinishPrinting(FAIL_PRINT_INIT); return; // Failed to init print page settings. } @@ -2093,8 +2101,15 @@ void PrintRenderFrameHelper::Print(blink::WebLocalFrame* frame, print_pages_params_->params->print_scaling_option; auto self = weak_ptr_factory_.GetWeakPtr(); - mojom::PrintPagesParamsPtr print_settings = GetPrintSettingsFromUser( + mojom::PrintPagesParamsPtr print_settings; + + if (silent) { + print_settings = mojom::PrintPagesParams::New(); + print_settings->params = print_pages_params_->params->Clone(); + } else { + print_settings = GetPrintSettingsFromUser( frame_ref.GetFrame(), node, expected_page_count, print_request_type); + } // Check if |this| is still valid. if (!self) return; @@ -2327,36 +2342,52 @@ void PrintRenderFrameHelper::IPCProcessed() { } } -bool PrintRenderFrameHelper::InitPrintSettings(bool fit_to_paper_size) { - mojom::PrintPagesParams settings; - settings.params = mojom::PrintParams::New(); - GetPrintManagerHost()->GetDefaultPrintSettings(&settings.params); +bool PrintRenderFrameHelper::InitPrintSettings( + bool fit_to_paper_size, + const base::DictionaryValue& new_settings) { + mojom::PrintPagesParamsPtr settings; + + if (new_settings.DictEmpty()) { + settings = mojom::PrintPagesParams::New(); + settings->params = mojom::PrintParams::New(); + GetPrintManagerHost()->GetDefaultPrintSettings(&settings->params); + } else { + bool canceled = false; + int cookie = + print_pages_params_ ? print_pages_params_->params->document_cookie : 0; + GetPrintManagerHost()->UpdatePrintSettings( + cookie, new_settings.GetDict().Clone(), &settings, &canceled); + if (canceled) + return false; + } // Check if the printer returned any settings, if the settings is empty, we // can safely assume there are no printer drivers configured. So we safely // terminate. bool result = true; - if (!PrintMsg_Print_Params_IsValid(*settings.params)) + if (!PrintMsg_Print_Params_IsValid(*settings->params)) result = false; // Reset to default values. ignore_css_margins_ = false; - settings.pages.clear(); + settings->pages.clear(); - settings.params->print_scaling_option = + settings->params->print_scaling_option = fit_to_paper_size ? mojom::PrintScalingOption::kFitToPrintableArea : mojom::PrintScalingOption::kSourceSize; - SetPrintPagesParams(settings); + SetPrintPagesParams(*settings); return result; } -bool PrintRenderFrameHelper::CalculateNumberOfPages(blink::WebLocalFrame* frame, - const blink::WebNode& node, - uint32_t* number_of_pages) { +bool PrintRenderFrameHelper::CalculateNumberOfPages( + blink::WebLocalFrame* frame, + const blink::WebNode& node, + uint32_t* number_of_pages, + const base::DictionaryValue& settings) { DCHECK(frame); bool fit_to_paper_size = !IsPrintingPdfFrame(frame, node); - if (!InitPrintSettings(fit_to_paper_size)) { + if (!InitPrintSettings(fit_to_paper_size, settings)) { notify_browser_of_print_failure_ = false; GetPrintManagerHost()->ShowInvalidPrinterSettingsError(); return false; @@ -2481,7 +2512,7 @@ mojom::PrintPagesParamsPtr PrintRenderFrameHelper::GetPrintSettingsFromUser( std::move(params), base::BindOnce( [](base::OnceClosure quit_closure, mojom::PrintPagesParamsPtr* output, - mojom::PrintPagesParamsPtr input) { + mojom::PrintPagesParamsPtr input, bool canceled) { *output = std::move(input); std::move(quit_closure).Run(); }, @@ -2725,18 +2756,7 @@ void PrintRenderFrameHelper::RequestPrintPreview(PrintPreviewRequestType type, } bool PrintRenderFrameHelper::CheckForCancel() { - const mojom::PrintParams& print_params = *print_pages_params_->params; - bool cancel = false; - - if (!GetPrintManagerHost()->CheckForCancel(print_params.preview_ui_id, - print_params.preview_request_id, - &cancel)) { - cancel = true; - } - - if (cancel) - notify_browser_of_print_failure_ = false; - return cancel; + return false; } bool PrintRenderFrameHelper::PreviewPageRendered( diff --git a/components/printing/renderer/print_render_frame_helper.h b/components/printing/renderer/print_render_frame_helper.h index 220b28a7e63625fe8b76290f0d2f40dd32cae255..72801431a5d19f31c1a7db785b0cbaee8e65cca3 100644 --- a/components/printing/renderer/print_render_frame_helper.h +++ b/components/printing/renderer/print_render_frame_helper.h @@ -255,7 +255,7 @@ class PrintRenderFrameHelper mojo::PendingAssociatedReceiver<mojom::PrintRenderFrame> receiver); // printing::mojom::PrintRenderFrame: - void PrintRequestedPages() override; + void PrintRequestedPages(bool silent, base::Value settings) override; void PrintWithParams(mojom::PrintPagesParamsPtr params) override; #if BUILDFLAG(ENABLE_PRINT_PREVIEW) void PrintForSystemDialog() override; @@ -327,7 +327,9 @@ class PrintRenderFrameHelper // WARNING: |this| may be gone after this method returns. void Print(blink::WebLocalFrame* frame, const blink::WebNode& node, - PrintRequestType print_request_type); + PrintRequestType print_request_type, + bool silent, + base::Value settings); // Notification when printing is done - signal tear-down/free resources. void DidFinishPrinting(PrintingResult result); @@ -336,12 +338,14 @@ class PrintRenderFrameHelper // Initialize print page settings with default settings. // Used only for native printing workflow. - bool InitPrintSettings(bool fit_to_paper_size); + bool InitPrintSettings(bool fit_to_paper_size, + const base::DictionaryValue& settings); // Calculate number of pages in source document. bool CalculateNumberOfPages(blink::WebLocalFrame* frame, const blink::WebNode& node, - uint32_t* number_of_pages); + uint32_t* number_of_pages, + const base::DictionaryValue& settings); #if BUILDFLAG(ENABLE_PRINT_PREVIEW) // Set options for print preset from source PDF document. diff --git a/printing/printing_context.cc b/printing/printing_context.cc index 8a8fcefa9da92a044f5bdf6a2f242048b325d442..6dae33514675d6843736b2c9a767a4b72cb103fa 100644 --- a/printing/printing_context.cc +++ b/printing/printing_context.cc @@ -117,7 +117,6 @@ mojom::ResultCode PrintingContext::UsePdfSettings() { mojom::ResultCode PrintingContext::UpdatePrintSettings( base::Value::Dict job_settings) { - ResetSettings(); { std::unique_ptr<PrintSettings> settings = PrintSettingsFromJobSettings(job_settings); diff --git a/printing/printing_context.h b/printing/printing_context.h index 2c8ef23f7cb75a743fa18e3c613f7c719988028c..265005d6d51f861aa7ccd7e0eba7809b3c652dae 100644 --- a/printing/printing_context.h +++ b/printing/printing_context.h @@ -170,6 +170,9 @@ class COMPONENT_EXPORT(PRINTING) PrintingContext { bool PrintingAborted() const { return abort_printing_; } + // Reinitializes the settings for object reuse. + void ResetSettings(); + int job_id() const { return job_id_; } protected: @@ -180,9 +183,6 @@ class COMPONENT_EXPORT(PRINTING) PrintingContext { static std::unique_ptr<PrintingContext> CreateImpl(Delegate* delegate, bool skip_system_calls); - // Reinitializes the settings for object reuse. - void ResetSettings(); - // Determine if system calls should be skipped by this instance. bool skip_system_calls() const { #if BUILDFLAG(ENABLE_OOP_PRINTING)
closed
electron/electron
https://github.com/electron/electron
34,270
DCHECK on `webContents.print()`
Introduced by https://github.com/electron/electron/pull/33906. Root Cause: https://chromium-review.googlesource.com/c/chromium/src/+/3579297 <details> <summary> Stacktrace </summary> ``` [46358:0518/110313.131061:FATAL:values_mojom_traits.h(100)] Check failed: value.is_dict(). 0 Electron Framework 0x000000012ef92ba9 base::debug::CollectStackTrace(void**, unsigned long) + 9 1 Electron Framework 0x000000012eeb3ac3 base::debug::StackTrace::StackTrace() + 19 2 Electron Framework 0x000000012eecccdf logging::LogMessage::~LogMessage() + 175 3 Electron Framework 0x000000012eecdd2e logging::LogMessage::~LogMessage() + 14 4 Electron Framework 0x000000012a9ed02a mojo::internal::Serializer<mojo_base::mojom::DeprecatedDictionaryValueDataView, base::Value>::Serialize(base::Value&, mojo::internal::MessageFragment<mojo_base::mojom::internal::DeprecatedDictionaryValue_Data>&) + 90 5 Electron Framework 0x000000012e7582da printing::mojom::PrintRenderFrameProxy::PrintRequestedPages(bool, base::Value) + 362 6 Electron Framework 0x0000000133f15232 printing::PrintViewManagerBase::CompletePrintNow(content::RenderFrameHost*) + 146 7 Electron Framework 0x0000000133f14f3b printing::PrintViewManagerBase::PrintNow(content::RenderFrameHost*, bool, base::Value, base::OnceCallback<void (bool, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)>) + 395 8 Electron Framework 0x000000012a56ed16 electron::api::WebContents::OnGetDefaultPrinter(base::Value, base::OnceCallback<void (bool, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)>, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> >, bool, std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > >) + 1686 9 Electron Framework 0x000000012a580b93 void base::internal::FunctorTraits<void (electron::api::WebContents::*)(base::Value, base::OnceCallback<void (bool, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)>, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> >, bool, std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > >), void>::Invoke<void (electron::api::WebContents::*)(base::Value, base::OnceCallback<void (bool, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)>, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> >, bool, std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > >), base::WeakPtr<electron::api::WebContents>, base::Value, base::OnceCallback<void (bool, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)>, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> >, bool, std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > > >(void (electron::api::WebContents::*)(base::Value, base::OnceCallback<void (bool, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)>, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> >, bool, std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > >), base::WeakPtr<electron::api::WebContents>&&, base::Value&&, base::OnceCallback<void (bool, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)>&&, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> >&&, bool&&, std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > >&&) + 291 10 Electron Framework 0x000000012a58099d base::internal::Invoker<base::internal::BindState<void (electron::api::WebContents::*)(base::Value, base::OnceCallback<void (bool, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)>, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> >, bool, std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > >), base::WeakPtr<electron::api::WebContents>, base::Value, base::OnceCallback<void (bool, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)>, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> >, bool>, void (std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > >)>::RunOnce(base::internal::BindStateBase*, std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > >&&) + 77 11 Electron Framework 0x000000012a581102 void base::internal::ReplyAdapter<std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > >, std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > > >(base::OnceCallback<void (std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > >)>, std::__1::unique_ptr<std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > >, std::__1::default_delete<std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > > > >*) + 210 12 Electron Framework 0x000000012a4f9627 base::internal::Invoker<base::internal::BindState<void (*)(base::OnceCallback<(anonymous namespace)::CloseFileResult ()>, std::__1::unique_ptr<(anonymous namespace)::CloseFileResult, std::__1::default_delete<(anonymous namespace)::CloseFileResult> >*), base::OnceCallback<(anonymous namespace)::CloseFileResult ()>, base::internal::UnretainedWrapper<std::__1::unique_ptr<(anonymous namespace)::CloseFileResult, std::__1::default_delete<(anonymous namespace)::CloseFileResult> > > >, void ()>::RunOnce(base::internal::BindStateBase*) + 39 13 Electron Framework 0x000000012ef74403 base::(anonymous namespace)::PostTaskAndReplyRelay::RunReply(base::(anonymous namespace)::PostTaskAndReplyRelay) + 211 14 Electron Framework 0x000000012ef74499 base::internal::Invoker<base::internal::BindState<void (*)(base::(anonymous namespace)::PostTaskAndReplyRelay), base::(anonymous namespace)::PostTaskAndReplyRelay>, void ()>::RunOnce(base::internal::BindStateBase*) + 73 15 Electron Framework 0x000000012ef261f9 base::TaskAnnotator::RunTaskImpl(base::PendingTask&) + 313 16 Electron Framework 0x000000012ef4e1ca base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::DoWorkImpl(base::sequence_manager::LazyNow*) + 1066 17 Electron Framework 0x000000012ef4d88e base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::DoWork() + 126 18 Electron Framework 0x000000012ef4e9e2 non-virtual thunk to base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::DoWork() + 18 19 Electron Framework 0x000000012efa83e1 base::MessagePumpCFRunLoopBase::RunWork() + 97 20 Electron Framework 0x000000012efa78c2 base::mac::CallWithEHFrame(void () block_pointer) + 10 21 Electron Framework 0x000000012efa7e0f base::MessagePumpCFRunLoopBase::RunWorkSource(void*) + 63 22 CoreFoundation 0x00007ff80b673aeb __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17 23 CoreFoundation 0x00007ff80b673a53 __CFRunLoopDoSource0 + 180 24 CoreFoundation 0x00007ff80b6737cd __CFRunLoopDoSources0 + 242 25 CoreFoundation 0x00007ff80b6721e8 __CFRunLoopRun + 892 26 CoreFoundation 0x00007ff80b6717ac CFRunLoopRunSpecific + 562 27 HIToolbox 0x00007ff8142f8ce6 RunCurrentEventLoopInMode + 292 28 HIToolbox 0x00007ff8142f8a4a ReceiveNextEventCommon + 594 29 HIToolbox 0x00007ff8142f87e5 _BlockUntilNextEventMatchingListInModeWithFilter + 70 30 AppKit 0x00007ff80e09853d _DPSNextEvent + 927 31 AppKit 0x00007ff80e096bfa -[NSApplication(NSEvent) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] + 1394 32 AppKit 0x00007ff80e0892a9 -[NSApplication run] + 586 33 Electron Framework 0x000000012efa8e7c base::MessagePumpNSApplication::DoRun(base::MessagePump::Delegate*) + 348 34 Electron Framework 0x000000012efa796b base::MessagePumpCFRunLoopBase::Run(base::MessagePump::Delegate*) + 155 35 Electron Framework 0x000000012ef4ef97 base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::Run(bool, base::TimeDelta) + 695 36 Electron Framework 0x000000012ef01dc6 base::RunLoop::Run(base::Location const&) + 726 37 Electron Framework 0x000000012dac4c83 content::BrowserMainLoop::RunMainMessageLoop() + 243 38 Electron Framework 0x000000012dac6822 content::BrowserMainRunnerImpl::Run() + 82 39 Electron Framework 0x000000012dac1fce content::BrowserMain(content::MainFunctionParams) + 270 40 Electron Framework 0x000000012a90bd12 content::RunBrowserProcessMain(content::MainFunctionParams, content::ContentMainDelegate*) + 258 41 Electron Framework 0x000000012a90d28b content::ContentMainRunnerImpl::RunBrowser(content::MainFunctionParams, bool) + 1403 42 Electron Framework 0x000000012a90cc90 content::ContentMainRunnerImpl::Run() + 736 43 Electron Framework 0x000000012a90b637 content::RunContentProcess(content::ContentMainParams, content::ContentMainRunner*) + 2679 44 Electron Framework 0x000000012a90b752 content::ContentMain(content::ContentMainParams) + 98 45 Electron Framework 0x000000012a4b883d ElectronMain + 157 46 dyld 0x0000000114aee51e start + 462 Task trace: 0 Electron Framework 0x000000012a56f8b0 electron::api::WebContents::Print(gin::Arguments*) + 2832 1 Electron Framework 0x000000012a56f8b0 electron::api::WebContents::Print(gin::Arguments*) + 2832 2 Electron Framework 0x000000012f718430 IPC::(anonymous namespace)::ChannelAssociatedGroupController::Accept(mojo::Message*) + 784 3 Electron Framework 0x000000012f2f4f9e mojo::SimpleWatcher::Context::Notify(unsigned int, MojoHandleSignalsState, unsigned int) + 430 Crash keys: "ui_scheduler_async_stack" = "0x12A56F8B0 0x12A56F8B0" "io_scheduler_async_stack" = "0x12BEBEDDB 0x0" "platform" = "darwin" "process_type" = "browser" ``` </details>
https://github.com/electron/electron/issues/34270
https://github.com/electron/electron/pull/34271
73e0bf973d2b7835290d61cab6638309a21a2719
588005a9d5a74b953961605579cf4ad6f8dc2b20
2022-05-18T09:05:02Z
c++
2022-05-19T08:05:07Z
shell/browser/api/electron_api_web_contents.cc
// Copyright (c) 2014 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/api/electron_api_web_contents.h" #include <limits> #include <memory> #include <set> #include <string> #include <unordered_set> #include <utility> #include <vector> #include "base/containers/id_map.h" #include "base/files/file_util.h" #include "base/json/json_reader.h" #include "base/no_destructor.h" #include "base/strings/utf_string_conversions.h" #include "base/task/current_thread.h" #include "base/task/thread_pool.h" #include "base/threading/scoped_blocking_call.h" #include "base/threading/sequenced_task_runner_handle.h" #include "base/threading/thread_restrictions.h" #include "base/threading/thread_task_runner_handle.h" #include "base/values.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/ui/exclusive_access/exclusive_access_manager.h" #include "chrome/browser/ui/views/eye_dropper/eye_dropper.h" #include "chrome/common/pref_names.h" #include "components/prefs/pref_service.h" #include "components/prefs/scoped_user_pref_update.h" #include "components/security_state/content/content_utils.h" #include "components/security_state/core/security_state.h" #include "content/browser/renderer_host/frame_tree_node.h" // nogncheck #include "content/browser/renderer_host/render_frame_host_manager.h" // nogncheck #include "content/browser/renderer_host/render_widget_host_impl.h" // nogncheck #include "content/browser/renderer_host/render_widget_host_view_base.h" // nogncheck #include "content/public/browser/child_process_security_policy.h" #include "content/public/browser/context_menu_params.h" #include "content/public/browser/desktop_media_id.h" #include "content/public/browser/desktop_streams_registry.h" #include "content/public/browser/download_request_utils.h" #include "content/public/browser/favicon_status.h" #include "content/public/browser/file_select_listener.h" #include "content/public/browser/native_web_keyboard_event.h" #include "content/public/browser/navigation_details.h" #include "content/public/browser/navigation_entry.h" #include "content/public/browser/navigation_handle.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/render_widget_host.h" #include "content/public/browser/render_widget_host_view.h" #include "content/public/browser/service_worker_context.h" #include "content/public/browser/site_instance.h" #include "content/public/browser/storage_partition.h" #include "content/public/browser/web_contents.h" #include "content/public/common/referrer_type_converters.h" #include "content/public/common/webplugininfo.h" #include "electron/buildflags/buildflags.h" #include "electron/shell/common/api/api.mojom.h" #include "gin/arguments.h" #include "gin/data_object_builder.h" #include "gin/handle.h" #include "gin/object_template_builder.h" #include "gin/wrappable.h" #include "mojo/public/cpp/bindings/associated_remote.h" #include "mojo/public/cpp/bindings/pending_receiver.h" #include "mojo/public/cpp/bindings/remote.h" #include "mojo/public/cpp/system/platform_handle.h" #include "ppapi/buildflags/buildflags.h" #include "printing/buildflags/buildflags.h" #include "printing/print_job_constants.h" #include "services/resource_coordinator/public/cpp/memory_instrumentation/memory_instrumentation.h" #include "services/service_manager/public/cpp/interface_provider.h" #include "shell/browser/api/electron_api_browser_window.h" #include "shell/browser/api/electron_api_debugger.h" #include "shell/browser/api/electron_api_session.h" #include "shell/browser/api/electron_api_web_frame_main.h" #include "shell/browser/api/message_port.h" #include "shell/browser/browser.h" #include "shell/browser/child_web_contents_tracker.h" #include "shell/browser/electron_autofill_driver_factory.h" #include "shell/browser/electron_browser_client.h" #include "shell/browser/electron_browser_context.h" #include "shell/browser/electron_browser_main_parts.h" #include "shell/browser/electron_javascript_dialog_manager.h" #include "shell/browser/electron_navigation_throttle.h" #include "shell/browser/file_select_helper.h" #include "shell/browser/native_window.h" #include "shell/browser/session_preferences.h" #include "shell/browser/ui/drag_util.h" #include "shell/browser/ui/file_dialog.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/ui/inspectable_web_contents_view.h" #include "shell/browser/web_contents_permission_helper.h" #include "shell/browser/web_contents_preferences.h" #include "shell/browser/web_contents_zoom_controller.h" #include "shell/browser/web_view_guest_delegate.h" #include "shell/browser/web_view_manager.h" #include "shell/common/api/electron_api_native_image.h" #include "shell/common/api/electron_bindings.h" #include "shell/common/color_util.h" #include "shell/common/electron_constants.h" #include "shell/common/gin_converters/base_converter.h" #include "shell/common/gin_converters/blink_converter.h" #include "shell/common/gin_converters/callback_converter.h" #include "shell/common/gin_converters/content_converter.h" #include "shell/common/gin_converters/file_path_converter.h" #include "shell/common/gin_converters/frame_converter.h" #include "shell/common/gin_converters/gfx_converter.h" #include "shell/common/gin_converters/gurl_converter.h" #include "shell/common/gin_converters/image_converter.h" #include "shell/common/gin_converters/net_converter.h" #include "shell/common/gin_converters/value_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/gin_helper/object_template_builder.h" #include "shell/common/language_util.h" #include "shell/common/mouse_util.h" #include "shell/common/node_includes.h" #include "shell/common/options_switches.h" #include "shell/common/process_util.h" #include "shell/common/v8_value_serializer.h" #include "storage/browser/file_system/isolated_context.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h" #include "third_party/blink/public/common/input/web_input_event.h" #include "third_party/blink/public/common/messaging/transferable_message_mojom_traits.h" #include "third_party/blink/public/common/page/page_zoom.h" #include "third_party/blink/public/mojom/frame/find_in_page.mojom.h" #include "third_party/blink/public/mojom/frame/fullscreen.mojom.h" #include "third_party/blink/public/mojom/messaging/transferable_message.mojom.h" #include "third_party/blink/public/mojom/renderer_preferences.mojom.h" #include "ui/base/cursor/cursor.h" #include "ui/base/cursor/mojom/cursor_type.mojom-shared.h" #include "ui/display/screen.h" #include "ui/events/base_event_utils.h" #if BUILDFLAG(ENABLE_OSR) #include "shell/browser/osr/osr_render_widget_host_view.h" #include "shell/browser/osr/osr_web_contents_view.h" #endif #if !BUILDFLAG(IS_MAC) #include "ui/aura/window.h" #else #include "ui/base/cocoa/defaults_utils.h" #endif #if BUILDFLAG(IS_LINUX) #include "ui/views/linux_ui/linux_ui.h" #endif #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_WIN) #include "ui/gfx/font_render_params.h" #endif #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #include "extensions/browser/script_executor.h" #include "extensions/browser/view_type_utils.h" #include "extensions/common/mojom/view_type.mojom.h" #include "shell/browser/extensions/electron_extension_web_contents_observer.h" #endif #if BUILDFLAG(ENABLE_PRINTING) #include "components/printing/browser/print_manager_utils.h" #include "printing/backend/print_backend.h" // nogncheck #include "printing/mojom/print.mojom.h" // nogncheck #include "shell/browser/printing/print_preview_message_handler.h" #include "shell/browser/printing/print_view_manager_electron.h" #if BUILDFLAG(IS_WIN) #include "printing/backend/win_helper.h" #endif #endif #if BUILDFLAG(ENABLE_PICTURE_IN_PICTURE) #include "chrome/browser/picture_in_picture/picture_in_picture_window_manager.h" #endif #if BUILDFLAG(ENABLE_PDF_VIEWER) #include "components/pdf/browser/pdf_web_contents_helper.h" // nogncheck #include "shell/browser/electron_pdf_web_contents_helper_client.h" #endif #if BUILDFLAG(ENABLE_PLUGINS) #include "content/public/browser/plugin_service.h" #endif #ifndef MAS_BUILD #include "chrome/browser/hang_monitor/hang_crash_dump.h" // nogncheck #endif namespace gin { #if BUILDFLAG(ENABLE_PRINTING) template <> struct Converter<printing::mojom::MarginType> { static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, printing::mojom::MarginType* out) { std::string type; if (ConvertFromV8(isolate, val, &type)) { if (type == "default") { *out = printing::mojom::MarginType::kDefaultMargins; return true; } if (type == "none") { *out = printing::mojom::MarginType::kNoMargins; return true; } if (type == "printableArea") { *out = printing::mojom::MarginType::kPrintableAreaMargins; return true; } if (type == "custom") { *out = printing::mojom::MarginType::kCustomMargins; return true; } } return false; } }; template <> struct Converter<printing::mojom::DuplexMode> { static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, printing::mojom::DuplexMode* out) { std::string mode; if (ConvertFromV8(isolate, val, &mode)) { if (mode == "simplex") { *out = printing::mojom::DuplexMode::kSimplex; return true; } if (mode == "longEdge") { *out = printing::mojom::DuplexMode::kLongEdge; return true; } if (mode == "shortEdge") { *out = printing::mojom::DuplexMode::kShortEdge; return true; } } return false; } }; #endif template <> struct Converter<WindowOpenDisposition> { static v8::Local<v8::Value> ToV8(v8::Isolate* isolate, WindowOpenDisposition val) { std::string disposition = "other"; switch (val) { case WindowOpenDisposition::CURRENT_TAB: disposition = "default"; break; case WindowOpenDisposition::NEW_FOREGROUND_TAB: disposition = "foreground-tab"; break; case WindowOpenDisposition::NEW_BACKGROUND_TAB: disposition = "background-tab"; break; case WindowOpenDisposition::NEW_POPUP: case WindowOpenDisposition::NEW_WINDOW: disposition = "new-window"; break; case WindowOpenDisposition::SAVE_TO_DISK: disposition = "save-to-disk"; break; default: break; } return gin::ConvertToV8(isolate, disposition); } }; template <> struct Converter<content::SavePageType> { static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, content::SavePageType* out) { std::string save_type; if (!ConvertFromV8(isolate, val, &save_type)) return false; save_type = base::ToLowerASCII(save_type); if (save_type == "htmlonly") { *out = content::SAVE_PAGE_TYPE_AS_ONLY_HTML; } else if (save_type == "htmlcomplete") { *out = content::SAVE_PAGE_TYPE_AS_COMPLETE_HTML; } else if (save_type == "mhtml") { *out = content::SAVE_PAGE_TYPE_AS_MHTML; } else { return false; } return true; } }; template <> struct Converter<electron::api::WebContents::Type> { static v8::Local<v8::Value> ToV8(v8::Isolate* isolate, electron::api::WebContents::Type val) { using Type = electron::api::WebContents::Type; std::string type; switch (val) { case Type::kBackgroundPage: type = "backgroundPage"; break; case Type::kBrowserWindow: type = "window"; break; case Type::kBrowserView: type = "browserView"; break; case Type::kRemote: type = "remote"; break; case Type::kWebView: type = "webview"; break; case Type::kOffScreen: type = "offscreen"; break; default: break; } return gin::ConvertToV8(isolate, type); } static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, electron::api::WebContents::Type* out) { using Type = electron::api::WebContents::Type; std::string type; if (!ConvertFromV8(isolate, val, &type)) return false; if (type == "backgroundPage") { *out = Type::kBackgroundPage; } else if (type == "browserView") { *out = Type::kBrowserView; } else if (type == "webview") { *out = Type::kWebView; #if BUILDFLAG(ENABLE_OSR) } else if (type == "offscreen") { *out = Type::kOffScreen; #endif } else { return false; } return true; } }; template <> struct Converter<scoped_refptr<content::DevToolsAgentHost>> { static v8::Local<v8::Value> ToV8( v8::Isolate* isolate, const scoped_refptr<content::DevToolsAgentHost>& val) { gin_helper::Dictionary dict(isolate, v8::Object::New(isolate)); dict.Set("id", val->GetId()); dict.Set("url", val->GetURL().spec()); return dict.GetHandle(); } }; } // namespace gin namespace electron { namespace api { namespace { base::IDMap<WebContents*>& GetAllWebContents() { static base::NoDestructor<base::IDMap<WebContents*>> s_all_web_contents; return *s_all_web_contents; } // Called when CapturePage is done. void OnCapturePageDone(gin_helper::Promise<gfx::Image> promise, const SkBitmap& bitmap) { // Hack to enable transparency in captured image promise.Resolve(gfx::Image::CreateFrom1xBitmap(bitmap)); } absl::optional<base::TimeDelta> GetCursorBlinkInterval() { #if BUILDFLAG(IS_MAC) absl::optional<base::TimeDelta> system_value( ui::TextInsertionCaretBlinkPeriodFromDefaults()); if (system_value) return *system_value; #elif BUILDFLAG(IS_LINUX) if (auto* linux_ui = views::LinuxUI::instance()) return linux_ui->GetCursorBlinkInterval(); #elif BUILDFLAG(IS_WIN) const auto system_msec = ::GetCaretBlinkTime(); if (system_msec != 0) { return (system_msec == INFINITE) ? base::TimeDelta() : base::Milliseconds(system_msec); } #endif return absl::nullopt; } #if BUILDFLAG(ENABLE_PRINTING) // This will return false if no printer with the provided device_name can be // found on the network. We need to check this because Chromium does not do // sanity checking of device_name validity and so will crash on invalid names. bool IsDeviceNameValid(const std::u16string& device_name) { #if BUILDFLAG(IS_MAC) base::ScopedCFTypeRef<CFStringRef> new_printer_id( base::SysUTF16ToCFStringRef(device_name)); PMPrinter new_printer = PMPrinterCreateFromPrinterID(new_printer_id.get()); bool printer_exists = new_printer != nullptr; PMRelease(new_printer); return printer_exists; #elif BUILDFLAG(IS_WIN) printing::ScopedPrinterHandle printer; return printer.OpenPrinterWithName(base::as_wcstr(device_name)); #else return true; #endif } std::pair<std::string, std::u16string> GetDefaultPrinterAsync() { #if BUILDFLAG(IS_WIN) // Blocking is needed here because Windows printer drivers are oftentimes // not thread-safe and have to be accessed on the UI thread. base::ThreadRestrictions::ScopedAllowIO allow_io; #endif scoped_refptr<printing::PrintBackend> print_backend = printing::PrintBackend::CreateInstance( g_browser_process->GetApplicationLocale()); std::string printer_name; printing::mojom::ResultCode code = print_backend->GetDefaultPrinterName(printer_name); // We don't want to return if this fails since some devices won't have a // default printer. if (code != printing::mojom::ResultCode::kSuccess) LOG(ERROR) << "Failed to get default printer name"; // Check for existing printers and pick the first one should it exist. if (printer_name.empty()) { printing::PrinterList printers; if (print_backend->EnumeratePrinters(&printers) != printing::mojom::ResultCode::kSuccess) return std::make_pair("Failed to enumerate printers", std::u16string()); if (!printers.empty()) printer_name = printers.front().printer_name; } return std::make_pair(std::string(), base::UTF8ToUTF16(printer_name)); } // Copied from // chrome/browser/ui/webui/print_preview/local_printer_handler_default.cc:L36-L54 scoped_refptr<base::TaskRunner> CreatePrinterHandlerTaskRunner() { // USER_VISIBLE because the result is displayed in the print preview dialog. #if !BUILDFLAG(IS_WIN) static constexpr base::TaskTraits kTraits = { base::MayBlock(), base::TaskPriority::USER_VISIBLE}; #endif #if defined(USE_CUPS) // CUPS is thread safe. return base::ThreadPool::CreateTaskRunner(kTraits); #elif BUILDFLAG(IS_WIN) // Windows drivers are likely not thread-safe and need to be accessed on the // UI thread. return content::GetUIThreadTaskRunner( {base::MayBlock(), base::TaskPriority::USER_VISIBLE}); #else // Be conservative on unsupported platforms. return base::ThreadPool::CreateSingleThreadTaskRunner(kTraits); #endif } #endif struct UserDataLink : public base::SupportsUserData::Data { explicit UserDataLink(base::WeakPtr<WebContents> contents) : web_contents(contents) {} base::WeakPtr<WebContents> web_contents; }; const void* kElectronApiWebContentsKey = &kElectronApiWebContentsKey; const char kRootName[] = "<root>"; struct FileSystem { FileSystem() = default; FileSystem(const std::string& type, const std::string& file_system_name, const std::string& root_url, const std::string& file_system_path) : type(type), file_system_name(file_system_name), root_url(root_url), file_system_path(file_system_path) {} std::string type; std::string file_system_name; std::string root_url; std::string file_system_path; }; std::string RegisterFileSystem(content::WebContents* web_contents, const base::FilePath& path) { auto* isolated_context = storage::IsolatedContext::GetInstance(); std::string root_name(kRootName); storage::IsolatedContext::ScopedFSHandle file_system = isolated_context->RegisterFileSystemForPath( storage::kFileSystemTypeLocal, std::string(), path, &root_name); content::ChildProcessSecurityPolicy* policy = content::ChildProcessSecurityPolicy::GetInstance(); content::RenderViewHost* render_view_host = web_contents->GetRenderViewHost(); int renderer_id = render_view_host->GetProcess()->GetID(); policy->GrantReadFileSystem(renderer_id, file_system.id()); policy->GrantWriteFileSystem(renderer_id, file_system.id()); policy->GrantCreateFileForFileSystem(renderer_id, file_system.id()); policy->GrantDeleteFromFileSystem(renderer_id, file_system.id()); if (!policy->CanReadFile(renderer_id, path)) policy->GrantReadFile(renderer_id, path); return file_system.id(); } FileSystem CreateFileSystemStruct(content::WebContents* web_contents, const std::string& file_system_id, const std::string& file_system_path, const std::string& type) { const GURL origin = web_contents->GetURL().DeprecatedGetOriginAsURL(); std::string file_system_name = storage::GetIsolatedFileSystemName(origin, file_system_id); std::string root_url = storage::GetIsolatedFileSystemRootURIString( origin, file_system_id, kRootName); return FileSystem(type, file_system_name, root_url, file_system_path); } std::unique_ptr<base::DictionaryValue> CreateFileSystemValue( const FileSystem& file_system) { auto file_system_value = std::make_unique<base::DictionaryValue>(); file_system_value->SetString("type", file_system.type); file_system_value->SetString("fileSystemName", file_system.file_system_name); file_system_value->SetString("rootURL", file_system.root_url); file_system_value->SetString("fileSystemPath", file_system.file_system_path); return file_system_value; } void WriteToFile(const base::FilePath& path, const std::string& content) { base::ScopedBlockingCall scoped_blocking_call(FROM_HERE, base::BlockingType::WILL_BLOCK); DCHECK(!path.empty()); base::WriteFile(path, content.data(), content.size()); } void AppendToFile(const base::FilePath& path, const std::string& content) { base::ScopedBlockingCall scoped_blocking_call(FROM_HERE, base::BlockingType::WILL_BLOCK); DCHECK(!path.empty()); base::AppendToFile(path, content); } PrefService* GetPrefService(content::WebContents* web_contents) { auto* context = web_contents->GetBrowserContext(); return static_cast<electron::ElectronBrowserContext*>(context)->prefs(); } std::map<std::string, std::string> GetAddedFileSystemPaths( content::WebContents* web_contents) { auto* pref_service = GetPrefService(web_contents); const base::Value* file_system_paths_value = pref_service->GetDictionary(prefs::kDevToolsFileSystemPaths); std::map<std::string, std::string> result; if (file_system_paths_value) { const base::DictionaryValue* file_system_paths_dict; file_system_paths_value->GetAsDictionary(&file_system_paths_dict); for (auto it : file_system_paths_dict->DictItems()) { std::string type = it.second.is_string() ? it.second.GetString() : std::string(); result[it.first] = type; } } return result; } bool IsDevToolsFileSystemAdded(content::WebContents* web_contents, const std::string& file_system_path) { auto file_system_paths = GetAddedFileSystemPaths(web_contents); return file_system_paths.find(file_system_path) != file_system_paths.end(); } void SetBackgroundColor(content::RenderWidgetHostView* rwhv, SkColor color) { rwhv->SetBackgroundColor(color); static_cast<content::RenderWidgetHostViewBase*>(rwhv) ->SetContentBackgroundColor(color); } } // namespace #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) WebContents::Type GetTypeFromViewType(extensions::mojom::ViewType view_type) { switch (view_type) { case extensions::mojom::ViewType::kExtensionBackgroundPage: return WebContents::Type::kBackgroundPage; case extensions::mojom::ViewType::kAppWindow: case extensions::mojom::ViewType::kComponent: case extensions::mojom::ViewType::kExtensionDialog: case extensions::mojom::ViewType::kExtensionPopup: case extensions::mojom::ViewType::kBackgroundContents: case extensions::mojom::ViewType::kExtensionGuest: case extensions::mojom::ViewType::kTabContents: case extensions::mojom::ViewType::kInvalid: return WebContents::Type::kRemote; } } #endif WebContents::WebContents(v8::Isolate* isolate, content::WebContents* web_contents) : content::WebContentsObserver(web_contents), type_(Type::kRemote), id_(GetAllWebContents().Add(this)), devtools_file_system_indexer_( base::MakeRefCounted<DevToolsFileSystemIndexer>()), exclusive_access_manager_(std::make_unique<ExclusiveAccessManager>(this)), file_task_runner_( base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()})) #if BUILDFLAG(ENABLE_PRINTING) , print_task_runner_(CreatePrinterHandlerTaskRunner()) #endif { #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) // WebContents created by extension host will have valid ViewType set. extensions::mojom::ViewType view_type = extensions::GetViewType(web_contents); if (view_type != extensions::mojom::ViewType::kInvalid) { InitWithExtensionView(isolate, web_contents, view_type); } extensions::ElectronExtensionWebContentsObserver::CreateForWebContents( web_contents); script_executor_ = std::make_unique<extensions::ScriptExecutor>(web_contents); #endif auto session = Session::CreateFrom(isolate, GetBrowserContext()); session_.Reset(isolate, session.ToV8()); web_contents->SetUserAgentOverride(blink::UserAgentOverride::UserAgentOnly( GetBrowserContext()->GetUserAgent()), false); web_contents->SetUserData(kElectronApiWebContentsKey, std::make_unique<UserDataLink>(GetWeakPtr())); InitZoomController(web_contents, gin::Dictionary::CreateEmpty(isolate)); } WebContents::WebContents(v8::Isolate* isolate, std::unique_ptr<content::WebContents> web_contents, Type type) : content::WebContentsObserver(web_contents.get()), type_(type), id_(GetAllWebContents().Add(this)), devtools_file_system_indexer_( base::MakeRefCounted<DevToolsFileSystemIndexer>()), exclusive_access_manager_(std::make_unique<ExclusiveAccessManager>(this)), file_task_runner_( base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()})) #if BUILDFLAG(ENABLE_PRINTING) , print_task_runner_(CreatePrinterHandlerTaskRunner()) #endif { DCHECK(type != Type::kRemote) << "Can't take ownership of a remote WebContents"; auto session = Session::CreateFrom(isolate, GetBrowserContext()); session_.Reset(isolate, session.ToV8()); InitWithSessionAndOptions(isolate, std::move(web_contents), session, gin::Dictionary::CreateEmpty(isolate)); } WebContents::WebContents(v8::Isolate* isolate, const gin_helper::Dictionary& options) : id_(GetAllWebContents().Add(this)), devtools_file_system_indexer_( base::MakeRefCounted<DevToolsFileSystemIndexer>()), exclusive_access_manager_(std::make_unique<ExclusiveAccessManager>(this)), file_task_runner_( base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()})) #if BUILDFLAG(ENABLE_PRINTING) , print_task_runner_(CreatePrinterHandlerTaskRunner()) #endif { // Read options. options.Get("backgroundThrottling", &background_throttling_); // Get type options.Get("type", &type_); #if BUILDFLAG(ENABLE_OSR) bool b = false; if (options.Get(options::kOffscreen, &b) && b) type_ = Type::kOffScreen; #endif // Init embedder earlier options.Get("embedder", &embedder_); // Whether to enable DevTools. options.Get("devTools", &enable_devtools_); // BrowserViews are not attached to a window initially so they should start // off as hidden. This is also important for compositor recycling. See: // https://github.com/electron/electron/pull/21372 bool initially_shown = type_ != Type::kBrowserView; options.Get(options::kShow, &initially_shown); // Obtain the session. std::string partition; gin::Handle<api::Session> session; if (options.Get("session", &session) && !session.IsEmpty()) { } else if (options.Get("partition", &partition)) { session = Session::FromPartition(isolate, partition); } else { // Use the default session if not specified. session = Session::FromPartition(isolate, ""); } session_.Reset(isolate, session.ToV8()); std::unique_ptr<content::WebContents> web_contents; if (IsGuest()) { scoped_refptr<content::SiteInstance> site_instance = content::SiteInstance::CreateForURL(session->browser_context(), GURL("chrome-guest://fake-host")); content::WebContents::CreateParams params(session->browser_context(), site_instance); guest_delegate_ = std::make_unique<WebViewGuestDelegate>(embedder_->web_contents(), this); params.guest_delegate = guest_delegate_.get(); #if BUILDFLAG(ENABLE_OSR) if (embedder_ && embedder_->IsOffScreen()) { auto* view = new OffScreenWebContentsView( false, base::BindRepeating(&WebContents::OnPaint, base::Unretained(this))); params.view = view; params.delegate_view = view; web_contents = content::WebContents::Create(params); view->SetWebContents(web_contents.get()); } else { #endif web_contents = content::WebContents::Create(params); #if BUILDFLAG(ENABLE_OSR) } } else if (IsOffScreen()) { // webPreferences does not have a transparent option, so if the window needs // to be transparent, that will be set at electron_api_browser_window.cc#L57 // and we then need to pull it back out and check it here. std::string background_color; options.GetHidden(options::kBackgroundColor, &background_color); bool transparent = ParseCSSColor(background_color) == SK_ColorTRANSPARENT; content::WebContents::CreateParams params(session->browser_context()); auto* view = new OffScreenWebContentsView( transparent, base::BindRepeating(&WebContents::OnPaint, base::Unretained(this))); params.view = view; params.delegate_view = view; web_contents = content::WebContents::Create(params); view->SetWebContents(web_contents.get()); #endif } else { content::WebContents::CreateParams params(session->browser_context()); params.initially_hidden = !initially_shown; web_contents = content::WebContents::Create(params); } InitWithSessionAndOptions(isolate, std::move(web_contents), session, options); } void WebContents::InitZoomController(content::WebContents* web_contents, const gin_helper::Dictionary& options) { WebContentsZoomController::CreateForWebContents(web_contents); zoom_controller_ = WebContentsZoomController::FromWebContents(web_contents); double zoom_factor; if (options.Get(options::kZoomFactor, &zoom_factor)) zoom_controller_->SetDefaultZoomFactor(zoom_factor); } void WebContents::InitWithSessionAndOptions( v8::Isolate* isolate, std::unique_ptr<content::WebContents> owned_web_contents, gin::Handle<api::Session> session, const gin_helper::Dictionary& options) { Observe(owned_web_contents.get()); InitWithWebContents(std::move(owned_web_contents), session->browser_context(), IsGuest()); inspectable_web_contents_->GetView()->SetDelegate(this); auto* prefs = web_contents()->GetMutableRendererPrefs(); // Collect preferred languages from OS and browser process. accept_languages // effects HTTP header, navigator.languages, and CJK fallback font selection. // // Note that an application locale set to the browser process might be // different with the one set to the preference list. // (e.g. overridden with --lang) std::string accept_languages = g_browser_process->GetApplicationLocale() + ","; for (auto const& language : electron::GetPreferredLanguages()) { if (language == g_browser_process->GetApplicationLocale()) continue; accept_languages += language + ","; } accept_languages.pop_back(); prefs->accept_languages = accept_languages; #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_WIN) // Update font settings. static const gfx::FontRenderParams params( gfx::GetFontRenderParams(gfx::FontRenderParamsQuery(), nullptr)); prefs->should_antialias_text = params.antialiasing; prefs->use_subpixel_positioning = params.subpixel_positioning; prefs->hinting = params.hinting; prefs->use_autohinter = params.autohinter; prefs->use_bitmaps = params.use_bitmaps; prefs->subpixel_rendering = params.subpixel_rendering; #endif // Honor the system's cursor blink rate settings if (auto interval = GetCursorBlinkInterval()) prefs->caret_blink_interval = *interval; // Save the preferences in C++. // If there's already a WebContentsPreferences object, we created it as part // of the webContents.setWindowOpenHandler path, so don't overwrite it. if (!WebContentsPreferences::From(web_contents())) { new WebContentsPreferences(web_contents(), options); } // Trigger re-calculation of webkit prefs. web_contents()->NotifyPreferencesChanged(); WebContentsPermissionHelper::CreateForWebContents(web_contents()); InitZoomController(web_contents(), options); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) extensions::ElectronExtensionWebContentsObserver::CreateForWebContents( web_contents()); script_executor_ = std::make_unique<extensions::ScriptExecutor>(web_contents()); #endif AutofillDriverFactory::CreateForWebContents(web_contents()); web_contents()->SetUserAgentOverride(blink::UserAgentOverride::UserAgentOnly( GetBrowserContext()->GetUserAgent()), false); if (IsGuest()) { NativeWindow* owner_window = nullptr; if (embedder_) { // New WebContents's owner_window is the embedder's owner_window. auto* relay = NativeWindowRelay::FromWebContents(embedder_->web_contents()); if (relay) owner_window = relay->GetNativeWindow(); } if (owner_window) SetOwnerWindow(owner_window); } web_contents()->SetUserData(kElectronApiWebContentsKey, std::make_unique<UserDataLink>(GetWeakPtr())); } #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) void WebContents::InitWithExtensionView(v8::Isolate* isolate, content::WebContents* web_contents, extensions::mojom::ViewType view_type) { // Must reassign type prior to calling `Init`. type_ = GetTypeFromViewType(view_type); if (type_ == Type::kRemote) return; if (type_ == Type::kBackgroundPage) // non-background-page WebContents are retained by other classes. We need // to pin here to prevent background-page WebContents from being GC'd. // The background page api::WebContents will live until the underlying // content::WebContents is destroyed. Pin(isolate); // Allow toggling DevTools for background pages Observe(web_contents); InitWithWebContents(std::unique_ptr<content::WebContents>(web_contents), GetBrowserContext(), IsGuest()); inspectable_web_contents_->GetView()->SetDelegate(this); } #endif void WebContents::InitWithWebContents( std::unique_ptr<content::WebContents> web_contents, ElectronBrowserContext* browser_context, bool is_guest) { browser_context_ = browser_context; web_contents->SetDelegate(this); #if BUILDFLAG(ENABLE_PRINTING) PrintPreviewMessageHandler::CreateForWebContents(web_contents.get()); PrintViewManagerElectron::CreateForWebContents(web_contents.get()); printing::CreateCompositeClientIfNeeded(web_contents.get(), browser_context->GetUserAgent()); #endif #if BUILDFLAG(ENABLE_PDF_VIEWER) pdf::PDFWebContentsHelper::CreateForWebContentsWithClient( web_contents.get(), std::make_unique<ElectronPDFWebContentsHelperClient>()); #endif // Determine whether the WebContents is offscreen. auto* web_preferences = WebContentsPreferences::From(web_contents.get()); offscreen_ = web_preferences && web_preferences->IsOffscreen(); // Create InspectableWebContents. inspectable_web_contents_ = std::make_unique<InspectableWebContents>( std::move(web_contents), browser_context->prefs(), is_guest); inspectable_web_contents_->SetDelegate(this); } WebContents::~WebContents() { // clear out objects that have been granted permissions so that when // WebContents::RenderFrameDeleted is called as a result of WebContents // destruction it doesn't try to clear out a granted_devices_ // on a destructed object. granted_devices_.clear(); if (!inspectable_web_contents_) { WebContentsDestroyed(); return; } inspectable_web_contents_->GetView()->SetDelegate(nullptr); // This event is only for internal use, which is emitted when WebContents is // being destroyed. Emit("will-destroy"); // For guest view based on OOPIF, the WebContents is released by the embedder // frame, and we need to clear the reference to the memory. bool not_owned_by_this = IsGuest() && attached_; #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) // And background pages are owned by extensions::ExtensionHost. if (type_ == Type::kBackgroundPage) not_owned_by_this = true; #endif if (not_owned_by_this) { inspectable_web_contents_->ReleaseWebContents(); WebContentsDestroyed(); } // InspectableWebContents will be automatically destroyed. } void WebContents::DeleteThisIfAlive() { // It is possible that the FirstWeakCallback has been called but the // SecondWeakCallback has not, in this case the garbage collection of // WebContents has already started and we should not |delete this|. // Calling |GetWrapper| can detect this corner case. auto* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); v8::Local<v8::Object> wrapper; if (!GetWrapper(isolate).ToLocal(&wrapper)) return; delete this; } void WebContents::Destroy() { // The content::WebContents should be destroyed asyncronously when possible // as user may choose to destroy WebContents during an event of it. if (Browser::Get()->is_shutting_down() || IsGuest()) { DeleteThisIfAlive(); } else { content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce( [](base::WeakPtr<WebContents> contents) { if (contents) contents->DeleteThisIfAlive(); }, GetWeakPtr())); } } bool WebContents::DidAddMessageToConsole( content::WebContents* source, blink::mojom::ConsoleMessageLevel level, const std::u16string& message, int32_t line_no, const std::u16string& source_id) { return Emit("console-message", static_cast<int32_t>(level), message, line_no, source_id); } void WebContents::OnCreateWindow( const GURL& target_url, const content::Referrer& referrer, const std::string& frame_name, WindowOpenDisposition disposition, const std::string& features, const scoped_refptr<network::ResourceRequestBody>& body) { Emit("-new-window", target_url, frame_name, disposition, features, referrer, body); } void WebContents::WebContentsCreatedWithFullParams( content::WebContents* source_contents, int opener_render_process_id, int opener_render_frame_id, const content::mojom::CreateNewWindowParams& params, content::WebContents* new_contents) { ChildWebContentsTracker::CreateForWebContents(new_contents); auto* tracker = ChildWebContentsTracker::FromWebContents(new_contents); tracker->url = params.target_url; tracker->frame_name = params.frame_name; tracker->referrer = params.referrer.To<content::Referrer>(); tracker->raw_features = params.raw_features; tracker->body = params.body; v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); gin_helper::Dictionary dict; gin::ConvertFromV8(isolate, pending_child_web_preferences_.Get(isolate), &dict); pending_child_web_preferences_.Reset(); // Associate the preferences passed in via `setWindowOpenHandler` with the // content::WebContents that was just created for the child window. These // preferences will be picked up by the RenderWidgetHost via its call to the // delegate's OverrideWebkitPrefs. new WebContentsPreferences(new_contents, dict); } bool WebContents::IsWebContentsCreationOverridden( content::SiteInstance* source_site_instance, content::mojom::WindowContainerType window_container_type, const GURL& opener_url, const content::mojom::CreateNewWindowParams& params) { bool default_prevented = Emit( "-will-add-new-contents", params.target_url, params.frame_name, params.raw_features, params.disposition, *params.referrer, params.body); // If the app prevented the default, redirect to CreateCustomWebContents, // which always returns nullptr, which will result in the window open being // prevented (window.open() will return null in the renderer). return default_prevented; } void WebContents::SetNextChildWebPreferences( const gin_helper::Dictionary preferences) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); // Store these prefs for when Chrome calls WebContentsCreatedWithFullParams // with the new child contents. pending_child_web_preferences_.Reset(isolate, preferences.GetHandle()); } content::WebContents* WebContents::CreateCustomWebContents( content::RenderFrameHost* opener, content::SiteInstance* source_site_instance, bool is_new_browsing_instance, const GURL& opener_url, const std::string& frame_name, const GURL& target_url, const content::StoragePartitionConfig& partition_config, content::SessionStorageNamespace* session_storage_namespace) { return nullptr; } void WebContents::AddNewContents( content::WebContents* source, std::unique_ptr<content::WebContents> new_contents, const GURL& target_url, WindowOpenDisposition disposition, const gfx::Rect& initial_rect, bool user_gesture, bool* was_blocked) { auto* tracker = ChildWebContentsTracker::FromWebContents(new_contents.get()); DCHECK(tracker); v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); auto api_web_contents = CreateAndTake(isolate, std::move(new_contents), Type::kBrowserWindow); // We call RenderFrameCreated here as at this point the empty "about:blank" // render frame has already been created. If the window never navigates again // RenderFrameCreated won't be called and certain prefs like // "kBackgroundColor" will not be applied. auto* frame = api_web_contents->MainFrame(); if (frame) { api_web_contents->HandleNewRenderFrame(frame); } if (Emit("-add-new-contents", api_web_contents, disposition, user_gesture, initial_rect.x(), initial_rect.y(), initial_rect.width(), initial_rect.height(), tracker->url, tracker->frame_name, tracker->referrer, tracker->raw_features, tracker->body)) { api_web_contents->Destroy(); } } content::WebContents* WebContents::OpenURLFromTab( content::WebContents* source, const content::OpenURLParams& params) { auto weak_this = GetWeakPtr(); if (params.disposition != WindowOpenDisposition::CURRENT_TAB) { Emit("-new-window", params.url, "", params.disposition, "", params.referrer, params.post_data); return nullptr; } if (!weak_this || !web_contents()) return nullptr; content::NavigationController::LoadURLParams load_url_params(params.url); load_url_params.referrer = params.referrer; load_url_params.transition_type = params.transition; load_url_params.extra_headers = params.extra_headers; load_url_params.should_replace_current_entry = params.should_replace_current_entry; load_url_params.is_renderer_initiated = params.is_renderer_initiated; load_url_params.started_from_context_menu = params.started_from_context_menu; load_url_params.initiator_origin = params.initiator_origin; load_url_params.source_site_instance = params.source_site_instance; load_url_params.frame_tree_node_id = params.frame_tree_node_id; load_url_params.redirect_chain = params.redirect_chain; load_url_params.has_user_gesture = params.user_gesture; load_url_params.blob_url_loader_factory = params.blob_url_loader_factory; load_url_params.href_translate = params.href_translate; load_url_params.reload_type = params.reload_type; if (params.post_data) { load_url_params.load_type = content::NavigationController::LOAD_TYPE_HTTP_POST; load_url_params.post_data = params.post_data; } source->GetController().LoadURLWithParams(load_url_params); return source; } void WebContents::BeforeUnloadFired(content::WebContents* tab, bool proceed, bool* proceed_to_fire_unload) { if (type_ == Type::kBrowserWindow || type_ == Type::kOffScreen || type_ == Type::kBrowserView) *proceed_to_fire_unload = proceed; else *proceed_to_fire_unload = true; // Note that Chromium does not emit this for navigations. Emit("before-unload-fired", proceed); } void WebContents::SetContentsBounds(content::WebContents* source, const gfx::Rect& rect) { for (ExtendedWebContentsObserver& observer : observers_) observer.OnSetContentBounds(rect); } void WebContents::CloseContents(content::WebContents* source) { Emit("close"); auto* autofill_driver_factory = AutofillDriverFactory::FromWebContents(web_contents()); if (autofill_driver_factory) { autofill_driver_factory->CloseAllPopups(); } for (ExtendedWebContentsObserver& observer : observers_) observer.OnCloseContents(); } void WebContents::ActivateContents(content::WebContents* source) { for (ExtendedWebContentsObserver& observer : observers_) observer.OnActivateContents(); } void WebContents::UpdateTargetURL(content::WebContents* source, const GURL& url) { Emit("update-target-url", url); } bool WebContents::HandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) { if (type_ == Type::kWebView && embedder_) { // Send the unhandled keyboard events back to the embedder. return embedder_->HandleKeyboardEvent(source, event); } else { return PlatformHandleKeyboardEvent(source, event); } } #if !BUILDFLAG(IS_MAC) // NOTE: The macOS version of this function is found in // electron_api_web_contents_mac.mm, as it requires calling into objective-C // code. bool WebContents::PlatformHandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) { // Escape exits tabbed fullscreen mode. if (event.windows_key_code == ui::VKEY_ESCAPE && is_html_fullscreen()) { ExitFullscreenModeForTab(source); return true; } // Check if the webContents has preferences and to ignore shortcuts auto* web_preferences = WebContentsPreferences::From(source); if (web_preferences && web_preferences->ShouldIgnoreMenuShortcuts()) return false; // Let the NativeWindow handle other parts. if (owner_window()) { owner_window()->HandleKeyboardEvent(source, event); return true; } return false; } #endif content::KeyboardEventProcessingResult WebContents::PreHandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) { if (exclusive_access_manager_->HandleUserKeyEvent(event)) return content::KeyboardEventProcessingResult::HANDLED; if (event.GetType() == blink::WebInputEvent::Type::kRawKeyDown || event.GetType() == blink::WebInputEvent::Type::kKeyUp) { bool prevent_default = Emit("before-input-event", event); if (prevent_default) { return content::KeyboardEventProcessingResult::HANDLED; } } return content::KeyboardEventProcessingResult::NOT_HANDLED; } void WebContents::ContentsZoomChange(bool zoom_in) { Emit("zoom-changed", zoom_in ? "in" : "out"); } Profile* WebContents::GetProfile() { return nullptr; } bool WebContents::IsFullscreen() const { return owner_window_ && owner_window_->IsFullscreen(); } void WebContents::EnterFullscreen(const GURL& url, ExclusiveAccessBubbleType bubble_type, const int64_t display_id) {} void WebContents::ExitFullscreen() {} void WebContents::UpdateExclusiveAccessExitBubbleContent( const GURL& url, ExclusiveAccessBubbleType bubble_type, ExclusiveAccessBubbleHideCallback bubble_first_hide_callback, bool force_update) {} void WebContents::OnExclusiveAccessUserInput() {} content::WebContents* WebContents::GetActiveWebContents() { return web_contents(); } bool WebContents::CanUserExitFullscreen() const { return true; } bool WebContents::IsExclusiveAccessBubbleDisplayed() const { return false; } void WebContents::EnterFullscreenModeForTab( content::RenderFrameHost* requesting_frame, const blink::mojom::FullscreenOptions& options) { auto* source = content::WebContents::FromRenderFrameHost(requesting_frame); auto* permission_helper = WebContentsPermissionHelper::FromWebContents(source); auto callback = base::BindRepeating(&WebContents::OnEnterFullscreenModeForTab, base::Unretained(this), requesting_frame, options); permission_helper->RequestFullscreenPermission(callback); exclusive_access_manager_->fullscreen_controller()->EnterFullscreenModeForTab( requesting_frame, options.display_id); } void WebContents::OnEnterFullscreenModeForTab( content::RenderFrameHost* requesting_frame, const blink::mojom::FullscreenOptions& options, bool allowed) { if (!allowed || !owner_window_) return; auto* source = content::WebContents::FromRenderFrameHost(requesting_frame); if (IsFullscreenForTabOrPending(source)) { DCHECK_EQ(fullscreen_frame_, source->GetFocusedFrame()); return; } SetHtmlApiFullscreen(true); if (native_fullscreen_) { // Explicitly trigger a view resize, as the size is not actually changing if // the browser is fullscreened, too. source->GetRenderViewHost()->GetWidget()->SynchronizeVisualProperties(); } } void WebContents::ExitFullscreenModeForTab(content::WebContents* source) { if (!owner_window_) return; // This needs to be called before we exit fullscreen on the native window, // or the controller will incorrectly think we weren't fullscreen and bail. exclusive_access_manager_->fullscreen_controller()->ExitFullscreenModeForTab( source); SetHtmlApiFullscreen(false); if (native_fullscreen_) { // Explicitly trigger a view resize, as the size is not actually changing if // the browser is fullscreened, too. Chrome does this indirectly from // `chrome/browser/ui/exclusive_access/fullscreen_controller.cc`. source->GetRenderViewHost()->GetWidget()->SynchronizeVisualProperties(); } } void WebContents::RendererUnresponsive( content::WebContents* source, content::RenderWidgetHost* render_widget_host, base::RepeatingClosure hang_monitor_restarter) { Emit("unresponsive"); } void WebContents::RendererResponsive( content::WebContents* source, content::RenderWidgetHost* render_widget_host) { Emit("responsive"); } bool WebContents::HandleContextMenu(content::RenderFrameHost& render_frame_host, const content::ContextMenuParams& params) { Emit("context-menu", std::make_pair(params, &render_frame_host)); return true; } bool WebContents::OnGoToEntryOffset(int offset) { GoToOffset(offset); return false; } void WebContents::FindReply(content::WebContents* web_contents, int request_id, int number_of_matches, const gfx::Rect& selection_rect, int active_match_ordinal, bool final_update) { if (!final_update) return; v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); gin_helper::Dictionary result = gin::Dictionary::CreateEmpty(isolate); result.Set("requestId", request_id); result.Set("matches", number_of_matches); result.Set("selectionArea", selection_rect); result.Set("activeMatchOrdinal", active_match_ordinal); result.Set("finalUpdate", final_update); // Deprecate after 2.0 Emit("found-in-page", result.GetHandle()); } void WebContents::RequestExclusivePointerAccess( content::WebContents* web_contents, bool user_gesture, bool last_unlocked_by_target, bool allowed) { if (allowed) { exclusive_access_manager_->mouse_lock_controller()->RequestToLockMouse( web_contents, user_gesture, last_unlocked_by_target); } else { web_contents->GotResponseToLockMouseRequest( blink::mojom::PointerLockResult::kPermissionDenied); } } void WebContents::RequestToLockMouse(content::WebContents* web_contents, bool user_gesture, bool last_unlocked_by_target) { auto* permission_helper = WebContentsPermissionHelper::FromWebContents(web_contents); permission_helper->RequestPointerLockPermission( user_gesture, last_unlocked_by_target, base::BindOnce(&WebContents::RequestExclusivePointerAccess, base::Unretained(this))); } void WebContents::LostMouseLock() { exclusive_access_manager_->mouse_lock_controller()->LostMouseLock(); } void WebContents::RequestKeyboardLock(content::WebContents* web_contents, bool esc_key_locked) { exclusive_access_manager_->keyboard_lock_controller()->RequestKeyboardLock( web_contents, esc_key_locked); } void WebContents::CancelKeyboardLockRequest( content::WebContents* web_contents) { exclusive_access_manager_->keyboard_lock_controller() ->CancelKeyboardLockRequest(web_contents); } bool WebContents::CheckMediaAccessPermission( content::RenderFrameHost* render_frame_host, const GURL& security_origin, blink::mojom::MediaStreamType type) { auto* web_contents = content::WebContents::FromRenderFrameHost(render_frame_host); auto* permission_helper = WebContentsPermissionHelper::FromWebContents(web_contents); return permission_helper->CheckMediaAccessPermission(security_origin, type); } void WebContents::RequestMediaAccessPermission( content::WebContents* web_contents, const content::MediaStreamRequest& request, content::MediaResponseCallback callback) { auto* permission_helper = WebContentsPermissionHelper::FromWebContents(web_contents); permission_helper->RequestMediaAccessPermission(request, std::move(callback)); } content::JavaScriptDialogManager* WebContents::GetJavaScriptDialogManager( content::WebContents* source) { if (!dialog_manager_) dialog_manager_ = std::make_unique<ElectronJavaScriptDialogManager>(); return dialog_manager_.get(); } void WebContents::OnAudioStateChanged(bool audible) { Emit("-audio-state-changed", audible); } void WebContents::BeforeUnloadFired(bool proceed, const base::TimeTicks& proceed_time) { // Do nothing, we override this method just to avoid compilation error since // there are two virtual functions named BeforeUnloadFired. } void WebContents::HandleNewRenderFrame( content::RenderFrameHost* render_frame_host) { auto* rwhv = render_frame_host->GetView(); if (!rwhv) return; // Set the background color of RenderWidgetHostView. auto* web_preferences = WebContentsPreferences::From(web_contents()); if (web_preferences) { absl::optional<SkColor> maybe_color = web_preferences->GetBackgroundColor(); web_contents()->SetPageBaseBackgroundColor(maybe_color); bool guest = IsGuest() || type_ == Type::kBrowserView; SkColor color = maybe_color.value_or(guest ? SK_ColorTRANSPARENT : SK_ColorWHITE); SetBackgroundColor(rwhv, color); } if (!background_throttling_) render_frame_host->GetRenderViewHost()->SetSchedulerThrottling(false); auto* rwh_impl = static_cast<content::RenderWidgetHostImpl*>(rwhv->GetRenderWidgetHost()); if (rwh_impl) rwh_impl->disable_hidden_ = !background_throttling_; auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host); if (web_frame) web_frame->Connect(); } void WebContents::OnBackgroundColorChanged() { absl::optional<SkColor> color = web_contents()->GetBackgroundColor(); if (color.has_value()) { auto* const view = web_contents()->GetRenderWidgetHostView(); static_cast<content::RenderWidgetHostViewBase*>(view) ->SetContentBackgroundColor(color.value()); } } void WebContents::RenderFrameCreated( content::RenderFrameHost* render_frame_host) { HandleNewRenderFrame(render_frame_host); // RenderFrameCreated is called for speculative frames which may not be // used in certain cross-origin navigations. Invoking // RenderFrameHost::GetLifecycleState currently crashes when called for // speculative frames so we need to filter it out for now. Check // https://crbug.com/1183639 for details on when this can be removed. auto* rfh_impl = static_cast<content::RenderFrameHostImpl*>(render_frame_host); if (rfh_impl->lifecycle_state() == content::RenderFrameHostImpl::LifecycleStateImpl::kSpeculative) { return; } content::RenderFrameHost::LifecycleState lifecycle_state = render_frame_host->GetLifecycleState(); if (lifecycle_state == content::RenderFrameHost::LifecycleState::kActive) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); gin_helper::Dictionary details = gin_helper::Dictionary::CreateEmpty(isolate); details.SetGetter("frame", render_frame_host); Emit("frame-created", details); } } void WebContents::RenderFrameDeleted( content::RenderFrameHost* render_frame_host) { // A RenderFrameHost can be deleted when: // - A WebContents is removed and its containing frames are disposed. // - An <iframe> is removed from the DOM. // - Cross-origin navigation creates a new RFH in a separate process which // is swapped by content::RenderFrameHostManager. // // clear out objects that have been granted permissions if (!granted_devices_.empty()) { granted_devices_.erase(render_frame_host->GetFrameTreeNodeId()); } // WebFrameMain::FromRenderFrameHost(rfh) will use the RFH's FrameTreeNode ID // to find an existing instance of WebFrameMain. During a cross-origin // navigation, the deleted RFH will be the old host which was swapped out. In // this special case, we need to also ensure that WebFrameMain's internal RFH // matches before marking it as disposed. auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host); if (web_frame && web_frame->render_frame_host() == render_frame_host) web_frame->MarkRenderFrameDisposed(); } void WebContents::RenderFrameHostChanged(content::RenderFrameHost* old_host, content::RenderFrameHost* new_host) { // During cross-origin navigation, a FrameTreeNode will swap out its RFH. // If an instance of WebFrameMain exists, it will need to have its RFH // swapped as well. // // |old_host| can be a nullptr so we use |new_host| for looking up the // WebFrameMain instance. auto* web_frame = WebFrameMain::FromFrameTreeNodeId(new_host->GetFrameTreeNodeId()); if (web_frame) { web_frame->UpdateRenderFrameHost(new_host); } } void WebContents::FrameDeleted(int frame_tree_node_id) { auto* web_frame = WebFrameMain::FromFrameTreeNodeId(frame_tree_node_id); if (web_frame) web_frame->Destroyed(); } void WebContents::RenderViewDeleted(content::RenderViewHost* render_view_host) { // This event is necessary for tracking any states with respect to // intermediate render view hosts aka speculative render view hosts. Currently // used by object-registry.js to ref count remote objects. Emit("render-view-deleted", render_view_host->GetProcess()->GetID()); if (web_contents()->GetRenderViewHost() == render_view_host) { // When the RVH that has been deleted is the current RVH it means that the // the web contents are being closed. This is communicated by this event. // Currently tracked by guest-window-manager.ts to destroy the // BrowserWindow. Emit("current-render-view-deleted", render_view_host->GetProcess()->GetID()); } } void WebContents::PrimaryMainFrameRenderProcessGone( base::TerminationStatus status) { auto weak_this = GetWeakPtr(); Emit("crashed", status == base::TERMINATION_STATUS_PROCESS_WAS_KILLED); // User might destroy WebContents in the crashed event. if (!weak_this || !web_contents()) return; v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); gin_helper::Dictionary details = gin_helper::Dictionary::CreateEmpty(isolate); details.Set("reason", status); details.Set("exitCode", web_contents()->GetCrashedErrorCode()); Emit("render-process-gone", details); } void WebContents::PluginCrashed(const base::FilePath& plugin_path, base::ProcessId plugin_pid) { #if BUILDFLAG(ENABLE_PLUGINS) content::WebPluginInfo info; auto* plugin_service = content::PluginService::GetInstance(); plugin_service->GetPluginInfoByPath(plugin_path, &info); Emit("plugin-crashed", info.name, info.version); #endif // BUILDFLAG(ENABLE_PLUGINS) } void WebContents::MediaStartedPlaying(const MediaPlayerInfo& video_type, const content::MediaPlayerId& id) { Emit("media-started-playing"); } void WebContents::MediaStoppedPlaying( const MediaPlayerInfo& video_type, const content::MediaPlayerId& id, content::WebContentsObserver::MediaStoppedReason reason) { Emit("media-paused"); } void WebContents::DidChangeThemeColor() { auto theme_color = web_contents()->GetThemeColor(); if (theme_color) { Emit("did-change-theme-color", electron::ToRGBHex(theme_color.value())); } else { Emit("did-change-theme-color", nullptr); } } void WebContents::DidAcquireFullscreen(content::RenderFrameHost* rfh) { set_fullscreen_frame(rfh); } void WebContents::OnWebContentsFocused( content::RenderWidgetHost* render_widget_host) { Emit("focus"); } void WebContents::OnWebContentsLostFocus( content::RenderWidgetHost* render_widget_host) { Emit("blur"); } void WebContents::DOMContentLoaded( content::RenderFrameHost* render_frame_host) { auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host); if (web_frame) web_frame->DOMContentLoaded(); if (!render_frame_host->GetParent()) Emit("dom-ready"); } void WebContents::DidFinishLoad(content::RenderFrameHost* render_frame_host, const GURL& validated_url) { bool is_main_frame = !render_frame_host->GetParent(); int frame_process_id = render_frame_host->GetProcess()->GetID(); int frame_routing_id = render_frame_host->GetRoutingID(); auto weak_this = GetWeakPtr(); Emit("did-frame-finish-load", is_main_frame, frame_process_id, frame_routing_id); // ⚠️WARNING!⚠️ // Emit() triggers JS which can call destroy() on |this|. It's not safe to // assume that |this| points to valid memory at this point. if (is_main_frame && weak_this && web_contents()) Emit("did-finish-load"); } void WebContents::DidFailLoad(content::RenderFrameHost* render_frame_host, const GURL& url, int error_code) { bool is_main_frame = !render_frame_host->GetParent(); int frame_process_id = render_frame_host->GetProcess()->GetID(); int frame_routing_id = render_frame_host->GetRoutingID(); Emit("did-fail-load", error_code, "", url, is_main_frame, frame_process_id, frame_routing_id); } void WebContents::DidStartLoading() { Emit("did-start-loading"); } void WebContents::DidStopLoading() { auto* web_preferences = WebContentsPreferences::From(web_contents()); if (web_preferences && web_preferences->ShouldUsePreferredSizeMode()) web_contents()->GetRenderViewHost()->EnablePreferredSizeMode(); Emit("did-stop-loading"); } bool WebContents::EmitNavigationEvent( const std::string& event, content::NavigationHandle* navigation_handle) { bool is_main_frame = navigation_handle->IsInMainFrame(); int frame_tree_node_id = navigation_handle->GetFrameTreeNodeId(); content::FrameTreeNode* frame_tree_node = content::FrameTreeNode::GloballyFindByID(frame_tree_node_id); content::RenderFrameHostManager* render_manager = frame_tree_node->render_manager(); content::RenderFrameHost* frame_host = nullptr; if (render_manager) { frame_host = render_manager->speculative_frame_host(); if (!frame_host) frame_host = render_manager->current_frame_host(); } int frame_process_id = -1, frame_routing_id = -1; if (frame_host) { frame_process_id = frame_host->GetProcess()->GetID(); frame_routing_id = frame_host->GetRoutingID(); } bool is_same_document = navigation_handle->IsSameDocument(); auto url = navigation_handle->GetURL(); return Emit(event, url, is_same_document, is_main_frame, frame_process_id, frame_routing_id); } void WebContents::Message(bool internal, const std::string& channel, blink::CloneableMessage arguments, content::RenderFrameHost* render_frame_host) { TRACE_EVENT1("electron", "WebContents::Message", "channel", channel); // webContents.emit('-ipc-message', new Event(), internal, channel, // arguments); EmitWithSender("-ipc-message", render_frame_host, electron::mojom::ElectronApiIPC::InvokeCallback(), internal, channel, std::move(arguments)); } void WebContents::Invoke( bool internal, const std::string& channel, blink::CloneableMessage arguments, electron::mojom::ElectronApiIPC::InvokeCallback callback, content::RenderFrameHost* render_frame_host) { TRACE_EVENT1("electron", "WebContents::Invoke", "channel", channel); // webContents.emit('-ipc-invoke', new Event(), internal, channel, arguments); EmitWithSender("-ipc-invoke", render_frame_host, std::move(callback), internal, channel, std::move(arguments)); } void WebContents::OnFirstNonEmptyLayout( content::RenderFrameHost* render_frame_host) { if (render_frame_host == web_contents()->GetMainFrame()) { Emit("ready-to-show"); } } void WebContents::ReceivePostMessage( const std::string& channel, blink::TransferableMessage message, content::RenderFrameHost* render_frame_host) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); auto wrapped_ports = MessagePort::EntanglePorts(isolate, std::move(message.ports)); v8::Local<v8::Value> message_value = electron::DeserializeV8Value(isolate, message); EmitWithSender("-ipc-ports", render_frame_host, electron::mojom::ElectronApiIPC::InvokeCallback(), false, channel, message_value, std::move(wrapped_ports)); } void WebContents::MessageSync( bool internal, const std::string& channel, blink::CloneableMessage arguments, electron::mojom::ElectronApiIPC::MessageSyncCallback callback, content::RenderFrameHost* render_frame_host) { TRACE_EVENT1("electron", "WebContents::MessageSync", "channel", channel); // webContents.emit('-ipc-message-sync', new Event(sender, message), internal, // channel, arguments); EmitWithSender("-ipc-message-sync", render_frame_host, std::move(callback), internal, channel, std::move(arguments)); } void WebContents::MessageTo(int32_t web_contents_id, const std::string& channel, blink::CloneableMessage arguments) { TRACE_EVENT1("electron", "WebContents::MessageTo", "channel", channel); auto* target_web_contents = FromID(web_contents_id); if (target_web_contents) { content::RenderFrameHost* frame = target_web_contents->MainFrame(); DCHECK(frame); v8::HandleScope handle_scope(JavascriptEnvironment::GetIsolate()); gin::Handle<WebFrameMain> web_frame_main = WebFrameMain::From(JavascriptEnvironment::GetIsolate(), frame); if (!web_frame_main->CheckRenderFrame()) return; int32_t sender_id = ID(); web_frame_main->GetRendererApi()->Message(false /* internal */, channel, std::move(arguments), sender_id); } } void WebContents::MessageHost(const std::string& channel, blink::CloneableMessage arguments, content::RenderFrameHost* render_frame_host) { TRACE_EVENT1("electron", "WebContents::MessageHost", "channel", channel); // webContents.emit('ipc-message-host', new Event(), channel, args); EmitWithSender("ipc-message-host", render_frame_host, electron::mojom::ElectronApiIPC::InvokeCallback(), channel, std::move(arguments)); } void WebContents::UpdateDraggableRegions( std::vector<mojom::DraggableRegionPtr> regions) { for (ExtendedWebContentsObserver& observer : observers_) observer.OnDraggableRegionsUpdated(regions); } void WebContents::DidStartNavigation( content::NavigationHandle* navigation_handle) { EmitNavigationEvent("did-start-navigation", navigation_handle); } void WebContents::DidRedirectNavigation( content::NavigationHandle* navigation_handle) { EmitNavigationEvent("did-redirect-navigation", navigation_handle); } void WebContents::ReadyToCommitNavigation( content::NavigationHandle* navigation_handle) { // Don't focus content in an inactive window. if (!owner_window()) return; #if BUILDFLAG(IS_MAC) if (!owner_window()->IsActive()) return; #else if (!owner_window()->widget()->IsActive()) return; #endif // Don't focus content after subframe navigations. if (!navigation_handle->IsInMainFrame()) return; // Only focus for top-level contents. if (type_ != Type::kBrowserWindow) return; web_contents()->SetInitialFocus(); } void WebContents::DidFinishNavigation( content::NavigationHandle* navigation_handle) { if (owner_window_) { owner_window_->NotifyLayoutWindowControlsOverlay(); } if (!navigation_handle->HasCommitted()) return; bool is_main_frame = navigation_handle->IsInMainFrame(); content::RenderFrameHost* frame_host = navigation_handle->GetRenderFrameHost(); int frame_process_id = -1, frame_routing_id = -1; if (frame_host) { frame_process_id = frame_host->GetProcess()->GetID(); frame_routing_id = frame_host->GetRoutingID(); } if (!navigation_handle->IsErrorPage()) { // FIXME: All the Emit() calls below could potentially result in |this| // being destroyed (by JS listening for the event and calling // webContents.destroy()). auto url = navigation_handle->GetURL(); bool is_same_document = navigation_handle->IsSameDocument(); if (is_same_document) { Emit("did-navigate-in-page", url, is_main_frame, frame_process_id, frame_routing_id); } else { const net::HttpResponseHeaders* http_response = navigation_handle->GetResponseHeaders(); std::string http_status_text; int http_response_code = -1; if (http_response) { http_status_text = http_response->GetStatusText(); http_response_code = http_response->response_code(); } Emit("did-frame-navigate", url, http_response_code, http_status_text, is_main_frame, frame_process_id, frame_routing_id); if (is_main_frame) { Emit("did-navigate", url, http_response_code, http_status_text); } } if (IsGuest()) Emit("load-commit", url, is_main_frame); } else { auto url = navigation_handle->GetURL(); int code = navigation_handle->GetNetErrorCode(); auto description = net::ErrorToShortString(code); Emit("did-fail-provisional-load", code, description, url, is_main_frame, frame_process_id, frame_routing_id); // Do not emit "did-fail-load" for canceled requests. if (code != net::ERR_ABORTED) { EmitWarning( node::Environment::GetCurrent(JavascriptEnvironment::GetIsolate()), "Failed to load URL: " + url.possibly_invalid_spec() + " with error: " + description, "electron"); Emit("did-fail-load", code, description, url, is_main_frame, frame_process_id, frame_routing_id); } } content::NavigationEntry* entry = navigation_handle->GetNavigationEntry(); // This check is needed due to an issue in Chromium // Check the Chromium issue to keep updated: // https://bugs.chromium.org/p/chromium/issues/detail?id=1178663 // If a history entry has been made and the forward/back call has been made, // proceed with setting the new title if (entry && (entry->GetTransitionType() & ui::PAGE_TRANSITION_FORWARD_BACK)) WebContents::TitleWasSet(entry); } void WebContents::TitleWasSet(content::NavigationEntry* entry) { std::u16string final_title; bool explicit_set = true; if (entry) { auto title = entry->GetTitle(); auto url = entry->GetURL(); if (url.SchemeIsFile() && title.empty()) { final_title = base::UTF8ToUTF16(url.ExtractFileName()); explicit_set = false; } else { final_title = title; } } else { final_title = web_contents()->GetTitle(); } for (ExtendedWebContentsObserver& observer : observers_) observer.OnPageTitleUpdated(final_title, explicit_set); Emit("page-title-updated", final_title, explicit_set); } void WebContents::DidUpdateFaviconURL( content::RenderFrameHost* render_frame_host, const std::vector<blink::mojom::FaviconURLPtr>& urls) { std::set<GURL> unique_urls; for (const auto& iter : urls) { if (iter->icon_type != blink::mojom::FaviconIconType::kFavicon) continue; const GURL& url = iter->icon_url; if (url.is_valid()) unique_urls.insert(url); } Emit("page-favicon-updated", unique_urls); } void WebContents::DevToolsReloadPage() { Emit("devtools-reload-page"); } void WebContents::DevToolsFocused() { Emit("devtools-focused"); } void WebContents::DevToolsOpened() { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); DCHECK(inspectable_web_contents_); DCHECK(inspectable_web_contents_->GetDevToolsWebContents()); auto handle = FromOrCreate( isolate, inspectable_web_contents_->GetDevToolsWebContents()); devtools_web_contents_.Reset(isolate, handle.ToV8()); // Set inspected tabID. base::Value tab_id(ID()); inspectable_web_contents_->CallClientFunction("DevToolsAPI.setInspectedTabId", &tab_id, nullptr, nullptr); // Inherit owner window in devtools when it doesn't have one. auto* devtools = inspectable_web_contents_->GetDevToolsWebContents(); bool has_window = devtools->GetUserData(NativeWindowRelay::UserDataKey()); if (owner_window() && !has_window) handle->SetOwnerWindow(devtools, owner_window()); Emit("devtools-opened"); } void WebContents::DevToolsClosed() { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); devtools_web_contents_.Reset(); Emit("devtools-closed"); } void WebContents::DevToolsResized() { for (ExtendedWebContentsObserver& observer : observers_) observer.OnDevToolsResized(); } void WebContents::SetOwnerWindow(NativeWindow* owner_window) { SetOwnerWindow(GetWebContents(), owner_window); } void WebContents::SetOwnerWindow(content::WebContents* web_contents, NativeWindow* owner_window) { if (owner_window) { owner_window_ = owner_window->GetWeakPtr(); NativeWindowRelay::CreateForWebContents(web_contents, owner_window->GetWeakPtr()); } else { owner_window_ = nullptr; web_contents->RemoveUserData(NativeWindowRelay::UserDataKey()); } #if BUILDFLAG(ENABLE_OSR) auto* osr_wcv = GetOffScreenWebContentsView(); if (osr_wcv) osr_wcv->SetNativeWindow(owner_window); #endif } content::WebContents* WebContents::GetWebContents() const { if (!inspectable_web_contents_) return nullptr; return inspectable_web_contents_->GetWebContents(); } content::WebContents* WebContents::GetDevToolsWebContents() const { if (!inspectable_web_contents_) return nullptr; return inspectable_web_contents_->GetDevToolsWebContents(); } void WebContents::WebContentsDestroyed() { // Clear the pointer stored in wrapper. if (GetAllWebContents().Lookup(id_)) GetAllWebContents().Remove(id_); v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); v8::Local<v8::Object> wrapper; if (!GetWrapper(isolate).ToLocal(&wrapper)) return; wrapper->SetAlignedPointerInInternalField(0, nullptr); // Tell WebViewGuestDelegate that the WebContents has been destroyed. if (guest_delegate_) guest_delegate_->WillDestroy(); Observe(nullptr); Emit("destroyed"); } void WebContents::NavigationEntryCommitted( const content::LoadCommittedDetails& details) { Emit("navigation-entry-committed", details.entry->GetURL(), details.is_same_document, details.did_replace_entry); } bool WebContents::GetBackgroundThrottling() const { return background_throttling_; } void WebContents::SetBackgroundThrottling(bool allowed) { background_throttling_ = allowed; auto* rfh = web_contents()->GetMainFrame(); if (!rfh) return; auto* rwhv = rfh->GetView(); if (!rwhv) return; auto* rwh_impl = static_cast<content::RenderWidgetHostImpl*>(rwhv->GetRenderWidgetHost()); if (!rwh_impl) return; rwh_impl->disable_hidden_ = !background_throttling_; web_contents()->GetRenderViewHost()->SetSchedulerThrottling(allowed); if (rwh_impl->is_hidden()) { rwh_impl->WasShown({}); } } int WebContents::GetProcessID() const { return web_contents()->GetMainFrame()->GetProcess()->GetID(); } base::ProcessId WebContents::GetOSProcessID() const { base::ProcessHandle process_handle = web_contents()->GetMainFrame()->GetProcess()->GetProcess().Handle(); return base::GetProcId(process_handle); } WebContents::Type WebContents::GetType() const { return type_; } bool WebContents::Equal(const WebContents* web_contents) const { return ID() == web_contents->ID(); } GURL WebContents::GetURL() const { return web_contents()->GetLastCommittedURL(); } void WebContents::LoadURL(const GURL& url, const gin_helper::Dictionary& options) { if (!url.is_valid() || url.spec().size() > url::kMaxURLChars) { Emit("did-fail-load", static_cast<int>(net::ERR_INVALID_URL), net::ErrorToShortString(net::ERR_INVALID_URL), url.possibly_invalid_spec(), true); return; } content::NavigationController::LoadURLParams params(url); if (!options.Get("httpReferrer", &params.referrer)) { GURL http_referrer; if (options.Get("httpReferrer", &http_referrer)) params.referrer = content::Referrer(http_referrer.GetAsReferrer(), network::mojom::ReferrerPolicy::kDefault); } std::string user_agent; if (options.Get("userAgent", &user_agent)) web_contents()->SetUserAgentOverride( blink::UserAgentOverride::UserAgentOnly(user_agent), false); std::string extra_headers; if (options.Get("extraHeaders", &extra_headers)) params.extra_headers = extra_headers; scoped_refptr<network::ResourceRequestBody> body; if (options.Get("postData", &body)) { params.post_data = body; params.load_type = content::NavigationController::LOAD_TYPE_HTTP_POST; } GURL base_url_for_data_url; if (options.Get("baseURLForDataURL", &base_url_for_data_url)) { params.base_url_for_data_url = base_url_for_data_url; params.load_type = content::NavigationController::LOAD_TYPE_DATA; } bool reload_ignoring_cache = false; if (options.Get("reloadIgnoringCache", &reload_ignoring_cache) && reload_ignoring_cache) { params.reload_type = content::ReloadType::BYPASSING_CACHE; } // Calling LoadURLWithParams() can trigger JS which destroys |this|. auto weak_this = GetWeakPtr(); params.transition_type = ui::PageTransitionFromInt( ui::PAGE_TRANSITION_TYPED | ui::PAGE_TRANSITION_FROM_ADDRESS_BAR); params.override_user_agent = content::NavigationController::UA_OVERRIDE_TRUE; // Discord non-committed entries to ensure that we don't re-use a pending // entry web_contents()->GetController().DiscardNonCommittedEntries(); web_contents()->GetController().LoadURLWithParams(params); // ⚠️WARNING!⚠️ // LoadURLWithParams() triggers JS events which can call destroy() on |this|. // It's not safe to assume that |this| points to valid memory at this point. if (!weak_this || !web_contents()) return; // Required to make beforeunload handler work. NotifyUserActivation(); } // TODO(MarshallOfSound): Figure out what we need to do with post data here, I // believe the default behavior when we pass "true" is to phone out to the // delegate and then the controller expects this method to be called again with // "false" if the user approves the reload. For now this would result in // ".reload()" calls on POST data domains failing silently. Passing false would // result in them succeeding, but reposting which although more correct could be // considering a breaking change. void WebContents::Reload() { web_contents()->GetController().Reload(content::ReloadType::NORMAL, /* check_for_repost */ true); } void WebContents::ReloadIgnoringCache() { web_contents()->GetController().Reload(content::ReloadType::BYPASSING_CACHE, /* check_for_repost */ true); } void WebContents::DownloadURL(const GURL& url) { auto* browser_context = web_contents()->GetBrowserContext(); auto* download_manager = browser_context->GetDownloadManager(); std::unique_ptr<download::DownloadUrlParameters> download_params( content::DownloadRequestUtils::CreateDownloadForWebContentsMainFrame( web_contents(), url, MISSING_TRAFFIC_ANNOTATION)); download_manager->DownloadUrl(std::move(download_params)); } std::u16string WebContents::GetTitle() const { return web_contents()->GetTitle(); } bool WebContents::IsLoading() const { return web_contents()->IsLoading(); } bool WebContents::IsLoadingMainFrame() const { return web_contents()->ShouldShowLoadingUI(); } bool WebContents::IsWaitingForResponse() const { return web_contents()->IsWaitingForResponse(); } void WebContents::Stop() { web_contents()->Stop(); } bool WebContents::CanGoBack() const { return web_contents()->GetController().CanGoBack(); } void WebContents::GoBack() { if (CanGoBack()) web_contents()->GetController().GoBack(); } bool WebContents::CanGoForward() const { return web_contents()->GetController().CanGoForward(); } void WebContents::GoForward() { if (CanGoForward()) web_contents()->GetController().GoForward(); } bool WebContents::CanGoToOffset(int offset) const { return web_contents()->GetController().CanGoToOffset(offset); } void WebContents::GoToOffset(int offset) { if (CanGoToOffset(offset)) web_contents()->GetController().GoToOffset(offset); } bool WebContents::CanGoToIndex(int index) const { return index >= 0 && index < GetHistoryLength(); } void WebContents::GoToIndex(int index) { if (CanGoToIndex(index)) web_contents()->GetController().GoToIndex(index); } int WebContents::GetActiveIndex() const { return web_contents()->GetController().GetCurrentEntryIndex(); } void WebContents::ClearHistory() { // In some rare cases (normally while there is no real history) we are in a // state where we can't prune navigation entries if (web_contents()->GetController().CanPruneAllButLastCommitted()) { web_contents()->GetController().PruneAllButLastCommitted(); } } int WebContents::GetHistoryLength() const { return web_contents()->GetController().GetEntryCount(); } const std::string WebContents::GetWebRTCIPHandlingPolicy() const { return web_contents()->GetMutableRendererPrefs()->webrtc_ip_handling_policy; } void WebContents::SetWebRTCIPHandlingPolicy( const std::string& webrtc_ip_handling_policy) { if (GetWebRTCIPHandlingPolicy() == webrtc_ip_handling_policy) return; web_contents()->GetMutableRendererPrefs()->webrtc_ip_handling_policy = webrtc_ip_handling_policy; web_contents()->SyncRendererPrefs(); } std::string WebContents::GetMediaSourceID( content::WebContents* request_web_contents) { auto* frame_host = web_contents()->GetMainFrame(); if (!frame_host) return std::string(); content::DesktopMediaID media_id( content::DesktopMediaID::TYPE_WEB_CONTENTS, content::DesktopMediaID::kNullId, content::WebContentsMediaCaptureId(frame_host->GetProcess()->GetID(), frame_host->GetRoutingID())); auto* request_frame_host = request_web_contents->GetMainFrame(); if (!request_frame_host) return std::string(); std::string id = content::DesktopStreamsRegistry::GetInstance()->RegisterStream( request_frame_host->GetProcess()->GetID(), request_frame_host->GetRoutingID(), url::Origin::Create(request_frame_host->GetLastCommittedURL() .DeprecatedGetOriginAsURL()), media_id, "", content::kRegistryStreamTypeTab); return id; } bool WebContents::IsCrashed() const { return web_contents()->IsCrashed(); } void WebContents::ForcefullyCrashRenderer() { content::RenderWidgetHostView* view = web_contents()->GetRenderWidgetHostView(); if (!view) return; content::RenderWidgetHost* rwh = view->GetRenderWidgetHost(); if (!rwh) return; content::RenderProcessHost* rph = rwh->GetProcess(); if (rph) { #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) // A generic |CrashDumpHungChildProcess()| is not implemented for Linux. // Instead we send an explicit IPC to crash on the renderer's IO thread. rph->ForceCrash(); #else // Try to generate a crash report for the hung process. #ifndef MAS_BUILD CrashDumpHungChildProcess(rph->GetProcess().Handle()); #endif rph->Shutdown(content::RESULT_CODE_HUNG); #endif } } void WebContents::SetUserAgent(const std::string& user_agent) { web_contents()->SetUserAgentOverride( blink::UserAgentOverride::UserAgentOnly(user_agent), false); } std::string WebContents::GetUserAgent() { return web_contents()->GetUserAgentOverride().ua_string_override; } v8::Local<v8::Promise> WebContents::SavePage( const base::FilePath& full_file_path, const content::SavePageType& save_type) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); gin_helper::Promise<void> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); if (!full_file_path.IsAbsolute()) { promise.RejectWithErrorMessage("Path must be absolute"); return handle; } auto* handler = new SavePageHandler(web_contents(), std::move(promise)); handler->Handle(full_file_path, save_type); return handle; } void WebContents::OpenDevTools(gin::Arguments* args) { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; std::string state; if (type_ == Type::kWebView || type_ == Type::kBackgroundPage || !owner_window()) { state = "detach"; } bool activate = true; if (args && args->Length() == 1) { gin_helper::Dictionary options; if (args->GetNext(&options)) { options.Get("mode", &state); options.Get("activate", &activate); } } DCHECK(inspectable_web_contents_); inspectable_web_contents_->SetDockState(state); inspectable_web_contents_->ShowDevTools(activate); } void WebContents::CloseDevTools() { if (type_ == Type::kRemote) return; DCHECK(inspectable_web_contents_); inspectable_web_contents_->CloseDevTools(); } bool WebContents::IsDevToolsOpened() { if (type_ == Type::kRemote) return false; DCHECK(inspectable_web_contents_); return inspectable_web_contents_->IsDevToolsViewShowing(); } bool WebContents::IsDevToolsFocused() { if (type_ == Type::kRemote) return false; DCHECK(inspectable_web_contents_); return inspectable_web_contents_->GetView()->IsDevToolsViewFocused(); } void WebContents::EnableDeviceEmulation( const blink::DeviceEmulationParams& params) { if (type_ == Type::kRemote) return; DCHECK(web_contents()); auto* frame_host = web_contents()->GetMainFrame(); if (frame_host) { auto* widget_host_impl = static_cast<content::RenderWidgetHostImpl*>( frame_host->GetView()->GetRenderWidgetHost()); if (widget_host_impl) { auto& frame_widget = widget_host_impl->GetAssociatedFrameWidget(); frame_widget->EnableDeviceEmulation(params); } } } void WebContents::DisableDeviceEmulation() { if (type_ == Type::kRemote) return; DCHECK(web_contents()); auto* frame_host = web_contents()->GetMainFrame(); if (frame_host) { auto* widget_host_impl = static_cast<content::RenderWidgetHostImpl*>( frame_host->GetView()->GetRenderWidgetHost()); if (widget_host_impl) { auto& frame_widget = widget_host_impl->GetAssociatedFrameWidget(); frame_widget->DisableDeviceEmulation(); } } } void WebContents::ToggleDevTools() { if (IsDevToolsOpened()) CloseDevTools(); else OpenDevTools(nullptr); } void WebContents::InspectElement(int x, int y) { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; DCHECK(inspectable_web_contents_); if (!inspectable_web_contents_->GetDevToolsWebContents()) OpenDevTools(nullptr); inspectable_web_contents_->InspectElement(x, y); } void WebContents::InspectSharedWorkerById(const std::string& workerId) { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) { if (agent_host->GetType() == content::DevToolsAgentHost::kTypeSharedWorker) { if (agent_host->GetId() == workerId) { OpenDevTools(nullptr); inspectable_web_contents_->AttachTo(agent_host); break; } } } } std::vector<scoped_refptr<content::DevToolsAgentHost>> WebContents::GetAllSharedWorkers() { std::vector<scoped_refptr<content::DevToolsAgentHost>> shared_workers; if (type_ == Type::kRemote) return shared_workers; if (!enable_devtools_) return shared_workers; for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) { if (agent_host->GetType() == content::DevToolsAgentHost::kTypeSharedWorker) { shared_workers.push_back(agent_host); } } return shared_workers; } void WebContents::InspectSharedWorker() { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) { if (agent_host->GetType() == content::DevToolsAgentHost::kTypeSharedWorker) { OpenDevTools(nullptr); inspectable_web_contents_->AttachTo(agent_host); break; } } } void WebContents::InspectServiceWorker() { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) { if (agent_host->GetType() == content::DevToolsAgentHost::kTypeServiceWorker) { OpenDevTools(nullptr); inspectable_web_contents_->AttachTo(agent_host); break; } } } void WebContents::SetIgnoreMenuShortcuts(bool ignore) { auto* web_preferences = WebContentsPreferences::From(web_contents()); DCHECK(web_preferences); web_preferences->SetIgnoreMenuShortcuts(ignore); } void WebContents::SetAudioMuted(bool muted) { web_contents()->SetAudioMuted(muted); } bool WebContents::IsAudioMuted() { return web_contents()->IsAudioMuted(); } bool WebContents::IsCurrentlyAudible() { return web_contents()->IsCurrentlyAudible(); } #if BUILDFLAG(ENABLE_PRINTING) void WebContents::OnGetDefaultPrinter( base::Value print_settings, printing::CompletionCallback print_callback, std::u16string device_name, bool silent, // <error, default_printer> std::pair<std::string, std::u16string> info) { // The content::WebContents might be already deleted at this point, and the // PrintViewManagerElectron class does not do null check. if (!web_contents()) { if (print_callback) std::move(print_callback).Run(false, "failed"); return; } if (!info.first.empty()) { if (print_callback) std::move(print_callback).Run(false, info.first); return; } // If the user has passed a deviceName use it, otherwise use default printer. std::u16string printer_name = device_name.empty() ? info.second : device_name; // If there are no valid printers available on the network, we bail. if (printer_name.empty() || !IsDeviceNameValid(printer_name)) { if (print_callback) std::move(print_callback).Run(false, "no valid printers available"); return; } print_settings.SetStringKey(printing::kSettingDeviceName, printer_name); auto* print_view_manager = PrintViewManagerElectron::FromWebContents(web_contents()); if (!print_view_manager) return; auto* focused_frame = web_contents()->GetFocusedFrame(); auto* rfh = focused_frame && focused_frame->HasSelection() ? focused_frame : web_contents()->GetMainFrame(); print_view_manager->PrintNow(rfh, silent, std::move(print_settings), std::move(print_callback)); } void WebContents::Print(gin::Arguments* args) { gin_helper::Dictionary options = gin::Dictionary::CreateEmpty(args->isolate()); base::Value settings(base::Value::Type::DICTIONARY); if (args->Length() >= 1 && !args->GetNext(&options)) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("webContents.print(): Invalid print settings specified."); return; } printing::CompletionCallback callback; if (args->Length() == 2 && !args->GetNext(&callback)) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("webContents.print(): Invalid optional callback provided."); return; } // Set optional silent printing bool silent = false; options.Get("silent", &silent); bool print_background = false; options.Get("printBackground", &print_background); settings.SetBoolKey(printing::kSettingShouldPrintBackgrounds, print_background); // Set custom margin settings gin_helper::Dictionary margins = gin::Dictionary::CreateEmpty(args->isolate()); if (options.Get("margins", &margins)) { printing::mojom::MarginType margin_type = printing::mojom::MarginType::kDefaultMargins; margins.Get("marginType", &margin_type); settings.SetIntKey(printing::kSettingMarginsType, static_cast<int>(margin_type)); if (margin_type == printing::mojom::MarginType::kCustomMargins) { base::Value custom_margins(base::Value::Type::DICTIONARY); int top = 0; margins.Get("top", &top); custom_margins.SetIntKey(printing::kSettingMarginTop, top); int bottom = 0; margins.Get("bottom", &bottom); custom_margins.SetIntKey(printing::kSettingMarginBottom, bottom); int left = 0; margins.Get("left", &left); custom_margins.SetIntKey(printing::kSettingMarginLeft, left); int right = 0; margins.Get("right", &right); custom_margins.SetIntKey(printing::kSettingMarginRight, right); settings.SetPath(printing::kSettingMarginsCustom, std::move(custom_margins)); } } else { settings.SetIntKey( printing::kSettingMarginsType, static_cast<int>(printing::mojom::MarginType::kDefaultMargins)); } // Set whether to print color or greyscale bool print_color = true; options.Get("color", &print_color); auto const color_model = print_color ? printing::mojom::ColorModel::kColor : printing::mojom::ColorModel::kGray; settings.SetIntKey(printing::kSettingColor, static_cast<int>(color_model)); // Is the orientation landscape or portrait. bool landscape = false; options.Get("landscape", &landscape); settings.SetBoolKey(printing::kSettingLandscape, landscape); // We set the default to the system's default printer and only update // if at the Chromium level if the user overrides. // Printer device name as opened by the OS. std::u16string device_name; options.Get("deviceName", &device_name); if (!device_name.empty() && !IsDeviceNameValid(device_name)) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("webContents.print(): Invalid deviceName provided."); return; } int scale_factor = 100; options.Get("scaleFactor", &scale_factor); settings.SetIntKey(printing::kSettingScaleFactor, scale_factor); int pages_per_sheet = 1; options.Get("pagesPerSheet", &pages_per_sheet); settings.SetIntKey(printing::kSettingPagesPerSheet, pages_per_sheet); // True if the user wants to print with collate. bool collate = true; options.Get("collate", &collate); settings.SetBoolKey(printing::kSettingCollate, collate); // The number of individual copies to print int copies = 1; options.Get("copies", &copies); settings.SetIntKey(printing::kSettingCopies, copies); // Strings to be printed as headers and footers if requested by the user. std::string header; options.Get("header", &header); std::string footer; options.Get("footer", &footer); if (!(header.empty() && footer.empty())) { settings.SetBoolKey(printing::kSettingHeaderFooterEnabled, true); settings.SetStringKey(printing::kSettingHeaderFooterTitle, header); settings.SetStringKey(printing::kSettingHeaderFooterURL, footer); } else { settings.SetBoolKey(printing::kSettingHeaderFooterEnabled, false); } // We don't want to allow the user to enable these settings // but we need to set them or a CHECK is hit. settings.SetIntKey(printing::kSettingPrinterType, static_cast<int>(printing::mojom::PrinterType::kLocal)); settings.SetBoolKey(printing::kSettingShouldPrintSelectionOnly, false); settings.SetBoolKey(printing::kSettingRasterizePdf, false); // Set custom page ranges to print std::vector<gin_helper::Dictionary> page_ranges; if (options.Get("pageRanges", &page_ranges)) { base::Value page_range_list(base::Value::Type::LIST); for (auto& range : page_ranges) { int from, to; if (range.Get("from", &from) && range.Get("to", &to)) { base::Value range(base::Value::Type::DICTIONARY); // Chromium uses 1-based page ranges, so increment each by 1. range.SetIntKey(printing::kSettingPageRangeFrom, from + 1); range.SetIntKey(printing::kSettingPageRangeTo, to + 1); page_range_list.Append(std::move(range)); } else { continue; } } if (!page_range_list.GetListDeprecated().empty()) settings.SetPath(printing::kSettingPageRange, std::move(page_range_list)); } // Duplex type user wants to use. printing::mojom::DuplexMode duplex_mode = printing::mojom::DuplexMode::kSimplex; options.Get("duplexMode", &duplex_mode); settings.SetIntKey(printing::kSettingDuplexMode, static_cast<int>(duplex_mode)); // We've already done necessary parameter sanitization at the // JS level, so we can simply pass this through. base::Value media_size(base::Value::Type::DICTIONARY); if (options.Get("mediaSize", &media_size)) settings.SetKey(printing::kSettingMediaSize, std::move(media_size)); // Set custom dots per inch (dpi) gin_helper::Dictionary dpi_settings; int dpi = 72; if (options.Get("dpi", &dpi_settings)) { int horizontal = 72; dpi_settings.Get("horizontal", &horizontal); settings.SetIntKey(printing::kSettingDpiHorizontal, horizontal); int vertical = 72; dpi_settings.Get("vertical", &vertical); settings.SetIntKey(printing::kSettingDpiVertical, vertical); } else { settings.SetIntKey(printing::kSettingDpiHorizontal, dpi); settings.SetIntKey(printing::kSettingDpiVertical, dpi); } print_task_runner_->PostTaskAndReplyWithResult( FROM_HERE, base::BindOnce(&GetDefaultPrinterAsync), base::BindOnce(&WebContents::OnGetDefaultPrinter, weak_factory_.GetWeakPtr(), std::move(settings), std::move(callback), device_name, silent)); } v8::Local<v8::Promise> WebContents::PrintToPDF(base::DictionaryValue settings) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); gin_helper::Promise<v8::Local<v8::Value>> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); PrintPreviewMessageHandler::FromWebContents(web_contents()) ->PrintToPDF(std::move(settings), std::move(promise)); return handle; } #endif void WebContents::AddWorkSpace(gin::Arguments* args, const base::FilePath& path) { if (path.empty()) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("path cannot be empty"); return; } DevToolsAddFileSystem(std::string(), path); } void WebContents::RemoveWorkSpace(gin::Arguments* args, const base::FilePath& path) { if (path.empty()) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("path cannot be empty"); return; } DevToolsRemoveFileSystem(path); } void WebContents::Undo() { web_contents()->Undo(); } void WebContents::Redo() { web_contents()->Redo(); } void WebContents::Cut() { web_contents()->Cut(); } void WebContents::Copy() { web_contents()->Copy(); } void WebContents::Paste() { web_contents()->Paste(); } void WebContents::PasteAndMatchStyle() { web_contents()->PasteAndMatchStyle(); } void WebContents::Delete() { web_contents()->Delete(); } void WebContents::SelectAll() { web_contents()->SelectAll(); } void WebContents::Unselect() { web_contents()->CollapseSelection(); } void WebContents::Replace(const std::u16string& word) { web_contents()->Replace(word); } void WebContents::ReplaceMisspelling(const std::u16string& word) { web_contents()->ReplaceMisspelling(word); } uint32_t WebContents::FindInPage(gin::Arguments* args) { std::u16string search_text; if (!args->GetNext(&search_text) || search_text.empty()) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("Must provide a non-empty search content"); return 0; } uint32_t request_id = ++find_in_page_request_id_; gin_helper::Dictionary dict; auto options = blink::mojom::FindOptions::New(); if (args->GetNext(&dict)) { dict.Get("forward", &options->forward); dict.Get("matchCase", &options->match_case); dict.Get("findNext", &options->new_session); } web_contents()->Find(request_id, search_text, std::move(options)); return request_id; } void WebContents::StopFindInPage(content::StopFindAction action) { web_contents()->StopFinding(action); } void WebContents::ShowDefinitionForSelection() { #if BUILDFLAG(IS_MAC) auto* const view = web_contents()->GetRenderWidgetHostView(); if (view) view->ShowDefinitionForSelection(); #endif } void WebContents::CopyImageAt(int x, int y) { auto* const host = web_contents()->GetMainFrame(); if (host) host->CopyImageAt(x, y); } void WebContents::Focus() { // Focusing on WebContents does not automatically focus the window on macOS // and Linux, do it manually to match the behavior on Windows. #if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX) if (owner_window()) owner_window()->Focus(true); #endif web_contents()->Focus(); } #if !BUILDFLAG(IS_MAC) bool WebContents::IsFocused() const { auto* view = web_contents()->GetRenderWidgetHostView(); if (!view) return false; if (GetType() != Type::kBackgroundPage) { auto* window = web_contents()->GetNativeView()->GetToplevelWindow(); if (window && !window->IsVisible()) return false; } return view->HasFocus(); } #endif void WebContents::SendInputEvent(v8::Isolate* isolate, v8::Local<v8::Value> input_event) { content::RenderWidgetHostView* view = web_contents()->GetRenderWidgetHostView(); if (!view) return; content::RenderWidgetHost* rwh = view->GetRenderWidgetHost(); blink::WebInputEvent::Type type = gin::GetWebInputEventType(isolate, input_event); if (blink::WebInputEvent::IsMouseEventType(type)) { blink::WebMouseEvent mouse_event; if (gin::ConvertFromV8(isolate, input_event, &mouse_event)) { if (IsOffScreen()) { #if BUILDFLAG(ENABLE_OSR) GetOffScreenRenderWidgetHostView()->SendMouseEvent(mouse_event); #endif } else { rwh->ForwardMouseEvent(mouse_event); } return; } } else if (blink::WebInputEvent::IsKeyboardEventType(type)) { content::NativeWebKeyboardEvent keyboard_event( blink::WebKeyboardEvent::Type::kRawKeyDown, blink::WebInputEvent::Modifiers::kNoModifiers, ui::EventTimeForNow()); if (gin::ConvertFromV8(isolate, input_event, &keyboard_event)) { rwh->ForwardKeyboardEvent(keyboard_event); return; } } else if (type == blink::WebInputEvent::Type::kMouseWheel) { blink::WebMouseWheelEvent mouse_wheel_event; if (gin::ConvertFromV8(isolate, input_event, &mouse_wheel_event)) { if (IsOffScreen()) { #if BUILDFLAG(ENABLE_OSR) GetOffScreenRenderWidgetHostView()->SendMouseWheelEvent( mouse_wheel_event); #endif } else { // Chromium expects phase info in wheel events (and applies a // DCHECK to verify it). See: https://crbug.com/756524. mouse_wheel_event.phase = blink::WebMouseWheelEvent::kPhaseBegan; mouse_wheel_event.dispatch_type = blink::WebInputEvent::DispatchType::kBlocking; rwh->ForwardWheelEvent(mouse_wheel_event); // Send a synthetic wheel event with phaseEnded to finish scrolling. mouse_wheel_event.has_synthetic_phase = true; mouse_wheel_event.delta_x = 0; mouse_wheel_event.delta_y = 0; mouse_wheel_event.phase = blink::WebMouseWheelEvent::kPhaseEnded; mouse_wheel_event.dispatch_type = blink::WebInputEvent::DispatchType::kEventNonBlocking; rwh->ForwardWheelEvent(mouse_wheel_event); } return; } } isolate->ThrowException( v8::Exception::Error(gin::StringToV8(isolate, "Invalid event object"))); } void WebContents::BeginFrameSubscription(gin::Arguments* args) { bool only_dirty = false; FrameSubscriber::FrameCaptureCallback callback; if (args->Length() > 1) { if (!args->GetNext(&only_dirty)) { args->ThrowError(); return; } } if (!args->GetNext(&callback)) { args->ThrowError(); return; } frame_subscriber_ = std::make_unique<FrameSubscriber>(web_contents(), callback, only_dirty); } void WebContents::EndFrameSubscription() { frame_subscriber_.reset(); } void WebContents::StartDrag(const gin_helper::Dictionary& item, gin::Arguments* args) { base::FilePath file; std::vector<base::FilePath> files; if (!item.Get("files", &files) && item.Get("file", &file)) { files.push_back(file); } v8::Local<v8::Value> icon_value; if (!item.Get("icon", &icon_value)) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("'icon' parameter is required"); return; } NativeImage* icon = nullptr; if (!NativeImage::TryConvertNativeImage(args->isolate(), icon_value, &icon) || icon->image().IsEmpty()) { return; } // Start dragging. if (!files.empty()) { base::CurrentThread::ScopedNestableTaskAllower allow; DragFileItems(files, icon->image(), web_contents()->GetNativeView()); } else { gin_helper::ErrorThrower(args->isolate()) .ThrowError("Must specify either 'file' or 'files' option"); } } v8::Local<v8::Promise> WebContents::CapturePage(gin::Arguments* args) { gfx::Rect rect; gin_helper::Promise<gfx::Image> promise(args->isolate()); v8::Local<v8::Promise> handle = promise.GetHandle(); // get rect arguments if they exist args->GetNext(&rect); auto* const view = web_contents()->GetRenderWidgetHostView(); if (!view) { promise.Resolve(gfx::Image()); return handle; } #if !BUILDFLAG(IS_MAC) // If the view's renderer is suspended this may fail on Windows/Linux - // bail if so. See CopyFromSurface in // content/public/browser/render_widget_host_view.h. auto* rfh = web_contents()->GetMainFrame(); if (rfh && rfh->GetVisibilityState() == blink::mojom::PageVisibilityState::kHidden) { promise.Resolve(gfx::Image()); return handle; } #endif // BUILDFLAG(IS_MAC) // Capture full page if user doesn't specify a |rect|. const gfx::Size view_size = rect.IsEmpty() ? view->GetViewBounds().size() : rect.size(); // By default, the requested bitmap size is the view size in screen // coordinates. However, if there's more pixel detail available on the // current system, increase the requested bitmap size to capture it all. gfx::Size bitmap_size = view_size; const gfx::NativeView native_view = view->GetNativeView(); const float scale = display::Screen::GetScreen() ->GetDisplayNearestView(native_view) .device_scale_factor(); if (scale > 1.0f) bitmap_size = gfx::ScaleToCeiledSize(view_size, scale); view->CopyFromSurface(gfx::Rect(rect.origin(), view_size), bitmap_size, base::BindOnce(&OnCapturePageDone, std::move(promise))); return handle; } void WebContents::IncrementCapturerCount(gin::Arguments* args) { gfx::Size size; bool stay_hidden = false; bool stay_awake = false; // get size arguments if they exist args->GetNext(&size); // get stayHidden arguments if they exist args->GetNext(&stay_hidden); // get stayAwake arguments if they exist args->GetNext(&stay_awake); std::ignore = web_contents() ->IncrementCapturerCount(size, stay_hidden, stay_awake) .Release(); } void WebContents::DecrementCapturerCount(gin::Arguments* args) { bool stay_hidden = false; bool stay_awake = false; // get stayHidden arguments if they exist args->GetNext(&stay_hidden); // get stayAwake arguments if they exist args->GetNext(&stay_awake); web_contents()->DecrementCapturerCount(stay_hidden, stay_awake); } bool WebContents::IsBeingCaptured() { return web_contents()->IsBeingCaptured(); } void WebContents::OnCursorChanged(const content::WebCursor& webcursor) { const ui::Cursor& cursor = webcursor.cursor(); if (cursor.type() == ui::mojom::CursorType::kCustom) { Emit("cursor-changed", CursorTypeToString(cursor), gfx::Image::CreateFrom1xBitmap(cursor.custom_bitmap()), cursor.image_scale_factor(), gfx::Size(cursor.custom_bitmap().width(), cursor.custom_bitmap().height()), cursor.custom_hotspot()); } else { Emit("cursor-changed", CursorTypeToString(cursor)); } } bool WebContents::IsGuest() const { return type_ == Type::kWebView; } void WebContents::AttachToIframe(content::WebContents* embedder_web_contents, int embedder_frame_id) { attached_ = true; if (guest_delegate_) guest_delegate_->AttachToIframe(embedder_web_contents, embedder_frame_id); } bool WebContents::IsOffScreen() const { #if BUILDFLAG(ENABLE_OSR) return type_ == Type::kOffScreen; #else return false; #endif } #if BUILDFLAG(ENABLE_OSR) void WebContents::OnPaint(const gfx::Rect& dirty_rect, const SkBitmap& bitmap) { Emit("paint", dirty_rect, gfx::Image::CreateFrom1xBitmap(bitmap)); } void WebContents::StartPainting() { auto* osr_wcv = GetOffScreenWebContentsView(); if (osr_wcv) osr_wcv->SetPainting(true); } void WebContents::StopPainting() { auto* osr_wcv = GetOffScreenWebContentsView(); if (osr_wcv) osr_wcv->SetPainting(false); } bool WebContents::IsPainting() const { auto* osr_wcv = GetOffScreenWebContentsView(); return osr_wcv && osr_wcv->IsPainting(); } void WebContents::SetFrameRate(int frame_rate) { auto* osr_wcv = GetOffScreenWebContentsView(); if (osr_wcv) osr_wcv->SetFrameRate(frame_rate); } int WebContents::GetFrameRate() const { auto* osr_wcv = GetOffScreenWebContentsView(); return osr_wcv ? osr_wcv->GetFrameRate() : 0; } #endif void WebContents::Invalidate() { if (IsOffScreen()) { #if BUILDFLAG(ENABLE_OSR) auto* osr_rwhv = GetOffScreenRenderWidgetHostView(); if (osr_rwhv) osr_rwhv->Invalidate(); #endif } else { auto* const window = owner_window(); if (window) window->Invalidate(); } } gfx::Size WebContents::GetSizeForNewRenderView(content::WebContents* wc) { if (IsOffScreen() && wc == web_contents()) { auto* relay = NativeWindowRelay::FromWebContents(web_contents()); if (relay) { auto* owner_window = relay->GetNativeWindow(); return owner_window ? owner_window->GetSize() : gfx::Size(); } } return gfx::Size(); } void WebContents::SetZoomLevel(double level) { zoom_controller_->SetZoomLevel(level); } double WebContents::GetZoomLevel() const { return zoom_controller_->GetZoomLevel(); } void WebContents::SetZoomFactor(gin_helper::ErrorThrower thrower, double factor) { if (factor < std::numeric_limits<double>::epsilon()) { thrower.ThrowError("'zoomFactor' must be a double greater than 0.0"); return; } auto level = blink::PageZoomFactorToZoomLevel(factor); SetZoomLevel(level); } double WebContents::GetZoomFactor() const { auto level = GetZoomLevel(); return blink::PageZoomLevelToZoomFactor(level); } void WebContents::SetTemporaryZoomLevel(double level) { zoom_controller_->SetTemporaryZoomLevel(level); } void WebContents::DoGetZoomLevel( electron::mojom::ElectronWebContentsUtility::DoGetZoomLevelCallback callback) { std::move(callback).Run(GetZoomLevel()); } std::vector<base::FilePath> WebContents::GetPreloadPaths() const { auto result = SessionPreferences::GetValidPreloads(GetBrowserContext()); if (auto* web_preferences = WebContentsPreferences::From(web_contents())) { base::FilePath preload; if (web_preferences->GetPreloadPath(&preload)) { result.emplace_back(preload); } } return result; } v8::Local<v8::Value> WebContents::GetLastWebPreferences( v8::Isolate* isolate) const { auto* web_preferences = WebContentsPreferences::From(web_contents()); if (!web_preferences) return v8::Null(isolate); return gin::ConvertToV8(isolate, *web_preferences->last_preference()); } v8::Local<v8::Value> WebContents::GetOwnerBrowserWindow( v8::Isolate* isolate) const { if (owner_window()) return BrowserWindow::From(isolate, owner_window()); else return v8::Null(isolate); } v8::Local<v8::Value> WebContents::Session(v8::Isolate* isolate) { return v8::Local<v8::Value>::New(isolate, session_); } content::WebContents* WebContents::HostWebContents() const { if (!embedder_) return nullptr; return embedder_->web_contents(); } void WebContents::SetEmbedder(const WebContents* embedder) { if (embedder) { NativeWindow* owner_window = nullptr; auto* relay = NativeWindowRelay::FromWebContents(embedder->web_contents()); if (relay) { owner_window = relay->GetNativeWindow(); } if (owner_window) SetOwnerWindow(owner_window); content::RenderWidgetHostView* rwhv = web_contents()->GetRenderWidgetHostView(); if (rwhv) { rwhv->Hide(); rwhv->Show(); } } } void WebContents::SetDevToolsWebContents(const WebContents* devtools) { if (inspectable_web_contents_) inspectable_web_contents_->SetDevToolsWebContents(devtools->web_contents()); } v8::Local<v8::Value> WebContents::GetNativeView(v8::Isolate* isolate) const { gfx::NativeView ptr = web_contents()->GetNativeView(); auto buffer = node::Buffer::Copy(isolate, reinterpret_cast<char*>(&ptr), sizeof(gfx::NativeView)); if (buffer.IsEmpty()) return v8::Null(isolate); else return buffer.ToLocalChecked(); } v8::Local<v8::Value> WebContents::DevToolsWebContents(v8::Isolate* isolate) { if (devtools_web_contents_.IsEmpty()) return v8::Null(isolate); else return v8::Local<v8::Value>::New(isolate, devtools_web_contents_); } v8::Local<v8::Value> WebContents::Debugger(v8::Isolate* isolate) { if (debugger_.IsEmpty()) { auto handle = electron::api::Debugger::Create(isolate, web_contents()); debugger_.Reset(isolate, handle.ToV8()); } return v8::Local<v8::Value>::New(isolate, debugger_); } content::RenderFrameHost* WebContents::MainFrame() { return web_contents()->GetMainFrame(); } void WebContents::NotifyUserActivation() { content::RenderFrameHost* frame = web_contents()->GetMainFrame(); if (frame) frame->NotifyUserActivation( blink::mojom::UserActivationNotificationType::kInteraction); } void WebContents::SetImageAnimationPolicy(const std::string& new_policy) { auto* web_preferences = WebContentsPreferences::From(web_contents()); web_preferences->SetImageAnimationPolicy(new_policy); web_contents()->OnWebPreferencesChanged(); } v8::Local<v8::Promise> WebContents::GetProcessMemoryInfo(v8::Isolate* isolate) { gin_helper::Promise<gin_helper::Dictionary> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); auto* frame_host = web_contents()->GetMainFrame(); if (!frame_host) { promise.RejectWithErrorMessage("Failed to create memory dump"); return handle; } auto pid = frame_host->GetProcess()->GetProcess().Pid(); v8::Global<v8::Context> context(isolate, isolate->GetCurrentContext()); memory_instrumentation::MemoryInstrumentation::GetInstance() ->RequestGlobalDumpForPid( pid, std::vector<std::string>(), base::BindOnce(&ElectronBindings::DidReceiveMemoryDump, std::move(context), std::move(promise), pid)); return handle; } v8::Local<v8::Promise> WebContents::TakeHeapSnapshot( v8::Isolate* isolate, const base::FilePath& file_path) { gin_helper::Promise<void> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); base::ThreadRestrictions::ScopedAllowIO allow_io; base::File file(file_path, base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE); if (!file.IsValid()) { promise.RejectWithErrorMessage("takeHeapSnapshot failed"); return handle; } auto* frame_host = web_contents()->GetMainFrame(); if (!frame_host) { promise.RejectWithErrorMessage("takeHeapSnapshot failed"); return handle; } if (!frame_host->IsRenderFrameCreated()) { promise.RejectWithErrorMessage("takeHeapSnapshot failed"); return handle; } // This dance with `base::Owned` is to ensure that the interface stays alive // until the callback is called. Otherwise it would be closed at the end of // this function. auto electron_renderer = std::make_unique<mojo::Remote<mojom::ElectronRenderer>>(); frame_host->GetRemoteInterfaces()->GetInterface( electron_renderer->BindNewPipeAndPassReceiver()); auto* raw_ptr = electron_renderer.get(); (*raw_ptr)->TakeHeapSnapshot( mojo::WrapPlatformFile(base::ScopedPlatformFile(file.TakePlatformFile())), base::BindOnce( [](mojo::Remote<mojom::ElectronRenderer>* ep, gin_helper::Promise<void> promise, bool success) { if (success) { promise.Resolve(); } else { promise.RejectWithErrorMessage("takeHeapSnapshot failed"); } }, base::Owned(std::move(electron_renderer)), std::move(promise))); return handle; } void WebContents::GrantDevicePermission( const url::Origin& origin, const base::Value* device, blink::PermissionType permissionType, content::RenderFrameHost* render_frame_host) { granted_devices_[render_frame_host->GetFrameTreeNodeId()][permissionType] [origin] .push_back( std::make_unique<base::Value>(device->Clone())); } std::vector<base::Value> WebContents::GetGrantedDevices( const url::Origin& origin, blink::PermissionType permissionType, content::RenderFrameHost* render_frame_host) { const auto& devices_for_frame_host_it = granted_devices_.find(render_frame_host->GetFrameTreeNodeId()); if (devices_for_frame_host_it == granted_devices_.end()) return {}; const auto& current_devices_it = devices_for_frame_host_it->second.find(permissionType); if (current_devices_it == devices_for_frame_host_it->second.end()) return {}; const auto& origin_devices_it = current_devices_it->second.find(origin); if (origin_devices_it == current_devices_it->second.end()) return {}; std::vector<base::Value> results; for (const auto& object : origin_devices_it->second) results.push_back(object->Clone()); return results; } void WebContents::UpdatePreferredSize(content::WebContents* web_contents, const gfx::Size& pref_size) { Emit("preferred-size-changed", pref_size); } bool WebContents::CanOverscrollContent() { return false; } std::unique_ptr<content::EyeDropper> WebContents::OpenEyeDropper( content::RenderFrameHost* frame, content::EyeDropperListener* listener) { return ShowEyeDropper(frame, listener); } void WebContents::RunFileChooser( content::RenderFrameHost* render_frame_host, scoped_refptr<content::FileSelectListener> listener, const blink::mojom::FileChooserParams& params) { FileSelectHelper::RunFileChooser(render_frame_host, std::move(listener), params); } void WebContents::EnumerateDirectory( content::WebContents* web_contents, scoped_refptr<content::FileSelectListener> listener, const base::FilePath& path) { FileSelectHelper::EnumerateDirectory(web_contents, std::move(listener), path); } bool WebContents::IsFullscreenForTabOrPending( const content::WebContents* source) { return html_fullscreen_; } bool WebContents::TakeFocus(content::WebContents* source, bool reverse) { if (source && source->GetOutermostWebContents() == source) { // If this is the outermost web contents and the user has tabbed or // shift + tabbed through all the elements, reset the focus back to // the first or last element so that it doesn't stay in the body. source->FocusThroughTabTraversal(reverse); return true; } return false; } content::PictureInPictureResult WebContents::EnterPictureInPicture( content::WebContents* web_contents) { #if BUILDFLAG(ENABLE_PICTURE_IN_PICTURE) return PictureInPictureWindowManager::GetInstance() ->EnterVideoPictureInPicture(web_contents); #else return content::PictureInPictureResult::kNotSupported; #endif } void WebContents::ExitPictureInPicture() { #if BUILDFLAG(ENABLE_PICTURE_IN_PICTURE) PictureInPictureWindowManager::GetInstance()->ExitPictureInPicture(); #endif } void WebContents::DevToolsSaveToFile(const std::string& url, const std::string& content, bool save_as) { base::FilePath path; auto it = saved_files_.find(url); if (it != saved_files_.end() && !save_as) { path = it->second; } else { file_dialog::DialogSettings settings; settings.parent_window = owner_window(); settings.force_detached = offscreen_; settings.title = url; settings.default_path = base::FilePath::FromUTF8Unsafe(url); if (!file_dialog::ShowSaveDialogSync(settings, &path)) { base::Value url_value(url); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.canceledSaveURL", &url_value, nullptr, nullptr); return; } } saved_files_[url] = path; // Notify DevTools. base::Value url_value(url); base::Value file_system_path_value(path.AsUTF8Unsafe()); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.savedURL", &url_value, &file_system_path_value, nullptr); file_task_runner_->PostTask(FROM_HERE, base::BindOnce(&WriteToFile, path, content)); } void WebContents::DevToolsAppendToFile(const std::string& url, const std::string& content) { auto it = saved_files_.find(url); if (it == saved_files_.end()) return; // Notify DevTools. base::Value url_value(url); inspectable_web_contents_->CallClientFunction("DevToolsAPI.appendedToURL", &url_value, nullptr, nullptr); file_task_runner_->PostTask( FROM_HERE, base::BindOnce(&AppendToFile, it->second, content)); } void WebContents::DevToolsRequestFileSystems() { auto file_system_paths = GetAddedFileSystemPaths(GetDevToolsWebContents()); if (file_system_paths.empty()) { base::ListValue empty_file_system_value; inspectable_web_contents_->CallClientFunction( "DevToolsAPI.fileSystemsLoaded", &empty_file_system_value, nullptr, nullptr); return; } std::vector<FileSystem> file_systems; for (const auto& file_system_path : file_system_paths) { base::FilePath path = base::FilePath::FromUTF8Unsafe(file_system_path.first); std::string file_system_id = RegisterFileSystem(GetDevToolsWebContents(), path); FileSystem file_system = CreateFileSystemStruct(GetDevToolsWebContents(), file_system_id, file_system_path.first, file_system_path.second); file_systems.push_back(file_system); } base::ListValue file_system_value; for (const auto& file_system : file_systems) file_system_value.Append(CreateFileSystemValue(file_system)); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.fileSystemsLoaded", &file_system_value, nullptr, nullptr); } void WebContents::DevToolsAddFileSystem( const std::string& type, const base::FilePath& file_system_path) { base::FilePath path = file_system_path; if (path.empty()) { std::vector<base::FilePath> paths; file_dialog::DialogSettings settings; settings.parent_window = owner_window(); settings.force_detached = offscreen_; settings.properties = file_dialog::OPEN_DIALOG_OPEN_DIRECTORY; if (!file_dialog::ShowOpenDialogSync(settings, &paths)) return; path = paths[0]; } std::string file_system_id = RegisterFileSystem(GetDevToolsWebContents(), path); if (IsDevToolsFileSystemAdded(GetDevToolsWebContents(), path.AsUTF8Unsafe())) return; FileSystem file_system = CreateFileSystemStruct( GetDevToolsWebContents(), file_system_id, path.AsUTF8Unsafe(), type); std::unique_ptr<base::DictionaryValue> file_system_value( CreateFileSystemValue(file_system)); auto* pref_service = GetPrefService(GetDevToolsWebContents()); DictionaryPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths); update.Get()->SetKey(path.AsUTF8Unsafe(), base::Value(type)); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.fileSystemAdded", nullptr, file_system_value.get(), nullptr); } void WebContents::DevToolsRemoveFileSystem( const base::FilePath& file_system_path) { if (!inspectable_web_contents_) return; std::string path = file_system_path.AsUTF8Unsafe(); storage::IsolatedContext::GetInstance()->RevokeFileSystemByPath( file_system_path); auto* pref_service = GetPrefService(GetDevToolsWebContents()); DictionaryPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths); update.Get()->RemoveKey(path); base::Value file_system_path_value(path); inspectable_web_contents_->CallClientFunction("DevToolsAPI.fileSystemRemoved", &file_system_path_value, nullptr, nullptr); } void WebContents::DevToolsIndexPath( int request_id, const std::string& file_system_path, const std::string& excluded_folders_message) { if (!IsDevToolsFileSystemAdded(GetDevToolsWebContents(), file_system_path)) { OnDevToolsIndexingDone(request_id, file_system_path); return; } if (devtools_indexing_jobs_.count(request_id) != 0) return; std::vector<std::string> excluded_folders; std::unique_ptr<base::Value> parsed_excluded_folders = base::JSONReader::ReadDeprecated(excluded_folders_message); if (parsed_excluded_folders && parsed_excluded_folders->is_list()) { for (const base::Value& folder_path : parsed_excluded_folders->GetListDeprecated()) { if (folder_path.is_string()) excluded_folders.push_back(folder_path.GetString()); } } devtools_indexing_jobs_[request_id] = scoped_refptr<DevToolsFileSystemIndexer::FileSystemIndexingJob>( devtools_file_system_indexer_->IndexPath( file_system_path, excluded_folders, base::BindRepeating( &WebContents::OnDevToolsIndexingWorkCalculated, weak_factory_.GetWeakPtr(), request_id, file_system_path), base::BindRepeating(&WebContents::OnDevToolsIndexingWorked, weak_factory_.GetWeakPtr(), request_id, file_system_path), base::BindRepeating(&WebContents::OnDevToolsIndexingDone, weak_factory_.GetWeakPtr(), request_id, file_system_path))); } void WebContents::DevToolsStopIndexing(int request_id) { auto it = devtools_indexing_jobs_.find(request_id); if (it == devtools_indexing_jobs_.end()) return; it->second->Stop(); devtools_indexing_jobs_.erase(it); } void WebContents::DevToolsSearchInPath(int request_id, const std::string& file_system_path, const std::string& query) { if (!IsDevToolsFileSystemAdded(GetDevToolsWebContents(), file_system_path)) { OnDevToolsSearchCompleted(request_id, file_system_path, std::vector<std::string>()); return; } devtools_file_system_indexer_->SearchInPath( file_system_path, query, base::BindRepeating(&WebContents::OnDevToolsSearchCompleted, weak_factory_.GetWeakPtr(), request_id, file_system_path)); } void WebContents::DevToolsSetEyeDropperActive(bool active) { auto* web_contents = GetWebContents(); if (!web_contents) return; if (active) { eye_dropper_ = std::make_unique<DevToolsEyeDropper>( web_contents, base::BindRepeating(&WebContents::ColorPickedInEyeDropper, base::Unretained(this))); } else { eye_dropper_.reset(); } } void WebContents::ColorPickedInEyeDropper(int r, int g, int b, int a) { base::DictionaryValue color; color.SetInteger("r", r); color.SetInteger("g", g); color.SetInteger("b", b); color.SetInteger("a", a); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.eyeDropperPickedColor", &color, nullptr, nullptr); } #if defined(TOOLKIT_VIEWS) && !BUILDFLAG(IS_MAC) ui::ImageModel WebContents::GetDevToolsWindowIcon() { return owner_window() ? owner_window()->GetWindowAppIcon() : ui::ImageModel{}; } #endif #if BUILDFLAG(IS_LINUX) void WebContents::GetDevToolsWindowWMClass(std::string* name, std::string* class_name) { *class_name = Browser::Get()->GetName(); *name = base::ToLowerASCII(*class_name); } #endif void WebContents::OnDevToolsIndexingWorkCalculated( int request_id, const std::string& file_system_path, int total_work) { base::Value request_id_value(request_id); base::Value file_system_path_value(file_system_path); base::Value total_work_value(total_work); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.indexingTotalWorkCalculated", &request_id_value, &file_system_path_value, &total_work_value); } void WebContents::OnDevToolsIndexingWorked(int request_id, const std::string& file_system_path, int worked) { base::Value request_id_value(request_id); base::Value file_system_path_value(file_system_path); base::Value worked_value(worked); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.indexingWorked", &request_id_value, &file_system_path_value, &worked_value); } void WebContents::OnDevToolsIndexingDone(int request_id, const std::string& file_system_path) { devtools_indexing_jobs_.erase(request_id); base::Value request_id_value(request_id); base::Value file_system_path_value(file_system_path); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.indexingDone", &request_id_value, &file_system_path_value, nullptr); } void WebContents::OnDevToolsSearchCompleted( int request_id, const std::string& file_system_path, const std::vector<std::string>& file_paths) { base::ListValue file_paths_value; for (const auto& file_path : file_paths) { file_paths_value.Append(file_path); } base::Value request_id_value(request_id); base::Value file_system_path_value(file_system_path); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.searchCompleted", &request_id_value, &file_system_path_value, &file_paths_value); } void WebContents::SetHtmlApiFullscreen(bool enter_fullscreen) { // Window is already in fullscreen mode, save the state. if (enter_fullscreen && owner_window_->IsFullscreen()) { native_fullscreen_ = true; UpdateHtmlApiFullscreen(true); return; } // Exit html fullscreen state but not window's fullscreen mode. if (!enter_fullscreen && native_fullscreen_) { UpdateHtmlApiFullscreen(false); return; } // Set fullscreen on window if allowed. auto* web_preferences = WebContentsPreferences::From(GetWebContents()); bool html_fullscreenable = web_preferences ? !web_preferences->ShouldDisableHtmlFullscreenWindowResize() : true; if (html_fullscreenable) { owner_window_->SetFullScreen(enter_fullscreen); } UpdateHtmlApiFullscreen(enter_fullscreen); native_fullscreen_ = false; } void WebContents::UpdateHtmlApiFullscreen(bool fullscreen) { if (fullscreen == is_html_fullscreen()) return; html_fullscreen_ = fullscreen; // Notify renderer of the html fullscreen change. web_contents() ->GetRenderViewHost() ->GetWidget() ->SynchronizeVisualProperties(); // The embedder WebContents is separated from the frame tree of webview, so // we must manually sync their fullscreen states. if (embedder_) embedder_->SetHtmlApiFullscreen(fullscreen); if (fullscreen) { Emit("enter-html-full-screen"); owner_window_->NotifyWindowEnterHtmlFullScreen(); } else { Emit("leave-html-full-screen"); owner_window_->NotifyWindowLeaveHtmlFullScreen(); } // Make sure all child webviews quit html fullscreen. if (!fullscreen && !IsGuest()) { auto* manager = WebViewManager::GetWebViewManager(web_contents()); manager->ForEachGuest( web_contents(), base::BindRepeating([](content::WebContents* guest) { WebContents* api_web_contents = WebContents::From(guest); api_web_contents->SetHtmlApiFullscreen(false); return false; })); } } // static v8::Local<v8::ObjectTemplate> WebContents::FillObjectTemplate( v8::Isolate* isolate, v8::Local<v8::ObjectTemplate> templ) { gin::InvokerOptions options; options.holder_is_first_argument = true; options.holder_type = "WebContents"; templ->Set( gin::StringToSymbol(isolate, "isDestroyed"), gin::CreateFunctionTemplate( isolate, base::BindRepeating(&gin_helper::Destroyable::IsDestroyed), options)); // We use gin_helper::ObjectTemplateBuilder instead of // gin::ObjectTemplateBuilder here to handle the fact that WebContents is // destroyable. return gin_helper::ObjectTemplateBuilder(isolate, templ) .SetMethod("destroy", &WebContents::Destroy) .SetMethod("getBackgroundThrottling", &WebContents::GetBackgroundThrottling) .SetMethod("setBackgroundThrottling", &WebContents::SetBackgroundThrottling) .SetMethod("getProcessId", &WebContents::GetProcessID) .SetMethod("getOSProcessId", &WebContents::GetOSProcessID) .SetMethod("equal", &WebContents::Equal) .SetMethod("_loadURL", &WebContents::LoadURL) .SetMethod("reload", &WebContents::Reload) .SetMethod("reloadIgnoringCache", &WebContents::ReloadIgnoringCache) .SetMethod("downloadURL", &WebContents::DownloadURL) .SetMethod("getURL", &WebContents::GetURL) .SetMethod("getTitle", &WebContents::GetTitle) .SetMethod("isLoading", &WebContents::IsLoading) .SetMethod("isLoadingMainFrame", &WebContents::IsLoadingMainFrame) .SetMethod("isWaitingForResponse", &WebContents::IsWaitingForResponse) .SetMethod("stop", &WebContents::Stop) .SetMethod("canGoBack", &WebContents::CanGoBack) .SetMethod("goBack", &WebContents::GoBack) .SetMethod("canGoForward", &WebContents::CanGoForward) .SetMethod("goForward", &WebContents::GoForward) .SetMethod("canGoToOffset", &WebContents::CanGoToOffset) .SetMethod("goToOffset", &WebContents::GoToOffset) .SetMethod("canGoToIndex", &WebContents::CanGoToIndex) .SetMethod("goToIndex", &WebContents::GoToIndex) .SetMethod("getActiveIndex", &WebContents::GetActiveIndex) .SetMethod("clearHistory", &WebContents::ClearHistory) .SetMethod("length", &WebContents::GetHistoryLength) .SetMethod("isCrashed", &WebContents::IsCrashed) .SetMethod("forcefullyCrashRenderer", &WebContents::ForcefullyCrashRenderer) .SetMethod("setUserAgent", &WebContents::SetUserAgent) .SetMethod("getUserAgent", &WebContents::GetUserAgent) .SetMethod("savePage", &WebContents::SavePage) .SetMethod("openDevTools", &WebContents::OpenDevTools) .SetMethod("closeDevTools", &WebContents::CloseDevTools) .SetMethod("isDevToolsOpened", &WebContents::IsDevToolsOpened) .SetMethod("isDevToolsFocused", &WebContents::IsDevToolsFocused) .SetMethod("enableDeviceEmulation", &WebContents::EnableDeviceEmulation) .SetMethod("disableDeviceEmulation", &WebContents::DisableDeviceEmulation) .SetMethod("toggleDevTools", &WebContents::ToggleDevTools) .SetMethod("inspectElement", &WebContents::InspectElement) .SetMethod("setIgnoreMenuShortcuts", &WebContents::SetIgnoreMenuShortcuts) .SetMethod("setAudioMuted", &WebContents::SetAudioMuted) .SetMethod("isAudioMuted", &WebContents::IsAudioMuted) .SetMethod("isCurrentlyAudible", &WebContents::IsCurrentlyAudible) .SetMethod("undo", &WebContents::Undo) .SetMethod("redo", &WebContents::Redo) .SetMethod("cut", &WebContents::Cut) .SetMethod("copy", &WebContents::Copy) .SetMethod("paste", &WebContents::Paste) .SetMethod("pasteAndMatchStyle", &WebContents::PasteAndMatchStyle) .SetMethod("delete", &WebContents::Delete) .SetMethod("selectAll", &WebContents::SelectAll) .SetMethod("unselect", &WebContents::Unselect) .SetMethod("replace", &WebContents::Replace) .SetMethod("replaceMisspelling", &WebContents::ReplaceMisspelling) .SetMethod("findInPage", &WebContents::FindInPage) .SetMethod("stopFindInPage", &WebContents::StopFindInPage) .SetMethod("focus", &WebContents::Focus) .SetMethod("isFocused", &WebContents::IsFocused) .SetMethod("sendInputEvent", &WebContents::SendInputEvent) .SetMethod("beginFrameSubscription", &WebContents::BeginFrameSubscription) .SetMethod("endFrameSubscription", &WebContents::EndFrameSubscription) .SetMethod("startDrag", &WebContents::StartDrag) .SetMethod("attachToIframe", &WebContents::AttachToIframe) .SetMethod("detachFromOuterFrame", &WebContents::DetachFromOuterFrame) .SetMethod("isOffscreen", &WebContents::IsOffScreen) #if BUILDFLAG(ENABLE_OSR) .SetMethod("startPainting", &WebContents::StartPainting) .SetMethod("stopPainting", &WebContents::StopPainting) .SetMethod("isPainting", &WebContents::IsPainting) .SetMethod("setFrameRate", &WebContents::SetFrameRate) .SetMethod("getFrameRate", &WebContents::GetFrameRate) #endif .SetMethod("invalidate", &WebContents::Invalidate) .SetMethod("setZoomLevel", &WebContents::SetZoomLevel) .SetMethod("getZoomLevel", &WebContents::GetZoomLevel) .SetMethod("setZoomFactor", &WebContents::SetZoomFactor) .SetMethod("getZoomFactor", &WebContents::GetZoomFactor) .SetMethod("getType", &WebContents::GetType) .SetMethod("_getPreloadPaths", &WebContents::GetPreloadPaths) .SetMethod("getLastWebPreferences", &WebContents::GetLastWebPreferences) .SetMethod("getOwnerBrowserWindow", &WebContents::GetOwnerBrowserWindow) .SetMethod("inspectServiceWorker", &WebContents::InspectServiceWorker) .SetMethod("inspectSharedWorker", &WebContents::InspectSharedWorker) .SetMethod("inspectSharedWorkerById", &WebContents::InspectSharedWorkerById) .SetMethod("getAllSharedWorkers", &WebContents::GetAllSharedWorkers) #if BUILDFLAG(ENABLE_PRINTING) .SetMethod("_print", &WebContents::Print) .SetMethod("_printToPDF", &WebContents::PrintToPDF) #endif .SetMethod("_setNextChildWebPreferences", &WebContents::SetNextChildWebPreferences) .SetMethod("addWorkSpace", &WebContents::AddWorkSpace) .SetMethod("removeWorkSpace", &WebContents::RemoveWorkSpace) .SetMethod("showDefinitionForSelection", &WebContents::ShowDefinitionForSelection) .SetMethod("copyImageAt", &WebContents::CopyImageAt) .SetMethod("capturePage", &WebContents::CapturePage) .SetMethod("setEmbedder", &WebContents::SetEmbedder) .SetMethod("setDevToolsWebContents", &WebContents::SetDevToolsWebContents) .SetMethod("getNativeView", &WebContents::GetNativeView) .SetMethod("incrementCapturerCount", &WebContents::IncrementCapturerCount) .SetMethod("decrementCapturerCount", &WebContents::DecrementCapturerCount) .SetMethod("isBeingCaptured", &WebContents::IsBeingCaptured) .SetMethod("setWebRTCIPHandlingPolicy", &WebContents::SetWebRTCIPHandlingPolicy) .SetMethod("getMediaSourceId", &WebContents::GetMediaSourceID) .SetMethod("getWebRTCIPHandlingPolicy", &WebContents::GetWebRTCIPHandlingPolicy) .SetMethod("takeHeapSnapshot", &WebContents::TakeHeapSnapshot) .SetMethod("setImageAnimationPolicy", &WebContents::SetImageAnimationPolicy) .SetMethod("_getProcessMemoryInfo", &WebContents::GetProcessMemoryInfo) .SetProperty("id", &WebContents::ID) .SetProperty("session", &WebContents::Session) .SetProperty("hostWebContents", &WebContents::HostWebContents) .SetProperty("devToolsWebContents", &WebContents::DevToolsWebContents) .SetProperty("debugger", &WebContents::Debugger) .SetProperty("mainFrame", &WebContents::MainFrame) .Build(); } const char* WebContents::GetTypeName() { return "WebContents"; } ElectronBrowserContext* WebContents::GetBrowserContext() const { return static_cast<ElectronBrowserContext*>( web_contents()->GetBrowserContext()); } // static gin::Handle<WebContents> WebContents::New( v8::Isolate* isolate, const gin_helper::Dictionary& options) { gin::Handle<WebContents> handle = gin::CreateHandle(isolate, new WebContents(isolate, options)); v8::TryCatch try_catch(isolate); gin_helper::CallMethod(isolate, handle.get(), "_init"); if (try_catch.HasCaught()) { node::errors::TriggerUncaughtException(isolate, try_catch); } return handle; } // static gin::Handle<WebContents> WebContents::CreateAndTake( v8::Isolate* isolate, std::unique_ptr<content::WebContents> web_contents, Type type) { gin::Handle<WebContents> handle = gin::CreateHandle( isolate, new WebContents(isolate, std::move(web_contents), type)); v8::TryCatch try_catch(isolate); gin_helper::CallMethod(isolate, handle.get(), "_init"); if (try_catch.HasCaught()) { node::errors::TriggerUncaughtException(isolate, try_catch); } return handle; } // static WebContents* WebContents::From(content::WebContents* web_contents) { if (!web_contents) return nullptr; auto* data = static_cast<UserDataLink*>( web_contents->GetUserData(kElectronApiWebContentsKey)); return data ? data->web_contents.get() : nullptr; } // static gin::Handle<WebContents> WebContents::FromOrCreate( v8::Isolate* isolate, content::WebContents* web_contents) { WebContents* api_web_contents = From(web_contents); if (!api_web_contents) { api_web_contents = new WebContents(isolate, web_contents); v8::TryCatch try_catch(isolate); gin_helper::CallMethod(isolate, api_web_contents, "_init"); if (try_catch.HasCaught()) { node::errors::TriggerUncaughtException(isolate, try_catch); } } return gin::CreateHandle(isolate, api_web_contents); } // static gin::Handle<WebContents> WebContents::CreateFromWebPreferences( v8::Isolate* isolate, const gin_helper::Dictionary& web_preferences) { // Check if webPreferences has |webContents| option. gin::Handle<WebContents> web_contents; if (web_preferences.GetHidden("webContents", &web_contents) && !web_contents.IsEmpty()) { // Set webPreferences from options if using an existing webContents. // These preferences will be used when the webContent launches new // render processes. auto* existing_preferences = WebContentsPreferences::From(web_contents->web_contents()); gin_helper::Dictionary web_preferences_dict; if (gin::ConvertFromV8(isolate, web_preferences.GetHandle(), &web_preferences_dict)) { existing_preferences->SetFromDictionary(web_preferences_dict); absl::optional<SkColor> color = existing_preferences->GetBackgroundColor(); web_contents->web_contents()->SetPageBaseBackgroundColor(color); // Because web preferences don't recognize transparency, // only set rwhv background color if a color exists auto* rwhv = web_contents->web_contents()->GetRenderWidgetHostView(); if (rwhv && color.has_value()) SetBackgroundColor(rwhv, color.value()); } } else { // Create one if not. web_contents = WebContents::New(isolate, web_preferences); } return web_contents; } // static WebContents* WebContents::FromID(int32_t id) { return GetAllWebContents().Lookup(id); } // static gin::WrapperInfo WebContents::kWrapperInfo = {gin::kEmbedderNativeGin}; } // namespace api } // namespace electron namespace { using electron::api::GetAllWebContents; using electron::api::WebContents; gin::Handle<WebContents> WebContentsFromID(v8::Isolate* isolate, int32_t id) { WebContents* contents = WebContents::FromID(id); return contents ? gin::CreateHandle(isolate, contents) : gin::Handle<WebContents>(); } gin::Handle<WebContents> WebContentsFromDevToolsTargetID( v8::Isolate* isolate, std::string target_id) { auto agent_host = content::DevToolsAgentHost::GetForId(target_id); WebContents* contents = agent_host ? WebContents::From(agent_host->GetWebContents()) : nullptr; return contents ? gin::CreateHandle(isolate, contents) : gin::Handle<WebContents>(); } std::vector<gin::Handle<WebContents>> GetAllWebContentsAsV8( v8::Isolate* isolate) { std::vector<gin::Handle<WebContents>> list; for (auto iter = base::IDMap<WebContents*>::iterator(&GetAllWebContents()); !iter.IsAtEnd(); iter.Advance()) { list.push_back(gin::CreateHandle(isolate, iter.GetCurrentValue())); } return list; } void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused, v8::Local<v8::Context> context, void* priv) { v8::Isolate* isolate = context->GetIsolate(); gin_helper::Dictionary dict(isolate, exports); dict.Set("WebContents", WebContents::GetConstructor(context)); dict.SetMethod("fromId", &WebContentsFromID); dict.SetMethod("fromDevToolsTargetId", &WebContentsFromDevToolsTargetID); dict.SetMethod("getAllWebContents", &GetAllWebContentsAsV8); } } // namespace NODE_LINKED_MODULE_CONTEXT_AWARE(electron_browser_web_contents, Initialize)
closed
electron/electron
https://github.com/electron/electron
34,270
DCHECK on `webContents.print()`
Introduced by https://github.com/electron/electron/pull/33906. Root Cause: https://chromium-review.googlesource.com/c/chromium/src/+/3579297 <details> <summary> Stacktrace </summary> ``` [46358:0518/110313.131061:FATAL:values_mojom_traits.h(100)] Check failed: value.is_dict(). 0 Electron Framework 0x000000012ef92ba9 base::debug::CollectStackTrace(void**, unsigned long) + 9 1 Electron Framework 0x000000012eeb3ac3 base::debug::StackTrace::StackTrace() + 19 2 Electron Framework 0x000000012eecccdf logging::LogMessage::~LogMessage() + 175 3 Electron Framework 0x000000012eecdd2e logging::LogMessage::~LogMessage() + 14 4 Electron Framework 0x000000012a9ed02a mojo::internal::Serializer<mojo_base::mojom::DeprecatedDictionaryValueDataView, base::Value>::Serialize(base::Value&, mojo::internal::MessageFragment<mojo_base::mojom::internal::DeprecatedDictionaryValue_Data>&) + 90 5 Electron Framework 0x000000012e7582da printing::mojom::PrintRenderFrameProxy::PrintRequestedPages(bool, base::Value) + 362 6 Electron Framework 0x0000000133f15232 printing::PrintViewManagerBase::CompletePrintNow(content::RenderFrameHost*) + 146 7 Electron Framework 0x0000000133f14f3b printing::PrintViewManagerBase::PrintNow(content::RenderFrameHost*, bool, base::Value, base::OnceCallback<void (bool, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)>) + 395 8 Electron Framework 0x000000012a56ed16 electron::api::WebContents::OnGetDefaultPrinter(base::Value, base::OnceCallback<void (bool, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)>, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> >, bool, std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > >) + 1686 9 Electron Framework 0x000000012a580b93 void base::internal::FunctorTraits<void (electron::api::WebContents::*)(base::Value, base::OnceCallback<void (bool, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)>, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> >, bool, std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > >), void>::Invoke<void (electron::api::WebContents::*)(base::Value, base::OnceCallback<void (bool, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)>, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> >, bool, std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > >), base::WeakPtr<electron::api::WebContents>, base::Value, base::OnceCallback<void (bool, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)>, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> >, bool, std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > > >(void (electron::api::WebContents::*)(base::Value, base::OnceCallback<void (bool, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)>, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> >, bool, std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > >), base::WeakPtr<electron::api::WebContents>&&, base::Value&&, base::OnceCallback<void (bool, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)>&&, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> >&&, bool&&, std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > >&&) + 291 10 Electron Framework 0x000000012a58099d base::internal::Invoker<base::internal::BindState<void (electron::api::WebContents::*)(base::Value, base::OnceCallback<void (bool, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)>, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> >, bool, std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > >), base::WeakPtr<electron::api::WebContents>, base::Value, base::OnceCallback<void (bool, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)>, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> >, bool>, void (std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > >)>::RunOnce(base::internal::BindStateBase*, std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > >&&) + 77 11 Electron Framework 0x000000012a581102 void base::internal::ReplyAdapter<std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > >, std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > > >(base::OnceCallback<void (std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > >)>, std::__1::unique_ptr<std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > >, std::__1::default_delete<std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char16_t, std::__1::char_traits<char16_t>, std::__1::allocator<char16_t> > > > >*) + 210 12 Electron Framework 0x000000012a4f9627 base::internal::Invoker<base::internal::BindState<void (*)(base::OnceCallback<(anonymous namespace)::CloseFileResult ()>, std::__1::unique_ptr<(anonymous namespace)::CloseFileResult, std::__1::default_delete<(anonymous namespace)::CloseFileResult> >*), base::OnceCallback<(anonymous namespace)::CloseFileResult ()>, base::internal::UnretainedWrapper<std::__1::unique_ptr<(anonymous namespace)::CloseFileResult, std::__1::default_delete<(anonymous namespace)::CloseFileResult> > > >, void ()>::RunOnce(base::internal::BindStateBase*) + 39 13 Electron Framework 0x000000012ef74403 base::(anonymous namespace)::PostTaskAndReplyRelay::RunReply(base::(anonymous namespace)::PostTaskAndReplyRelay) + 211 14 Electron Framework 0x000000012ef74499 base::internal::Invoker<base::internal::BindState<void (*)(base::(anonymous namespace)::PostTaskAndReplyRelay), base::(anonymous namespace)::PostTaskAndReplyRelay>, void ()>::RunOnce(base::internal::BindStateBase*) + 73 15 Electron Framework 0x000000012ef261f9 base::TaskAnnotator::RunTaskImpl(base::PendingTask&) + 313 16 Electron Framework 0x000000012ef4e1ca base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::DoWorkImpl(base::sequence_manager::LazyNow*) + 1066 17 Electron Framework 0x000000012ef4d88e base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::DoWork() + 126 18 Electron Framework 0x000000012ef4e9e2 non-virtual thunk to base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::DoWork() + 18 19 Electron Framework 0x000000012efa83e1 base::MessagePumpCFRunLoopBase::RunWork() + 97 20 Electron Framework 0x000000012efa78c2 base::mac::CallWithEHFrame(void () block_pointer) + 10 21 Electron Framework 0x000000012efa7e0f base::MessagePumpCFRunLoopBase::RunWorkSource(void*) + 63 22 CoreFoundation 0x00007ff80b673aeb __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17 23 CoreFoundation 0x00007ff80b673a53 __CFRunLoopDoSource0 + 180 24 CoreFoundation 0x00007ff80b6737cd __CFRunLoopDoSources0 + 242 25 CoreFoundation 0x00007ff80b6721e8 __CFRunLoopRun + 892 26 CoreFoundation 0x00007ff80b6717ac CFRunLoopRunSpecific + 562 27 HIToolbox 0x00007ff8142f8ce6 RunCurrentEventLoopInMode + 292 28 HIToolbox 0x00007ff8142f8a4a ReceiveNextEventCommon + 594 29 HIToolbox 0x00007ff8142f87e5 _BlockUntilNextEventMatchingListInModeWithFilter + 70 30 AppKit 0x00007ff80e09853d _DPSNextEvent + 927 31 AppKit 0x00007ff80e096bfa -[NSApplication(NSEvent) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] + 1394 32 AppKit 0x00007ff80e0892a9 -[NSApplication run] + 586 33 Electron Framework 0x000000012efa8e7c base::MessagePumpNSApplication::DoRun(base::MessagePump::Delegate*) + 348 34 Electron Framework 0x000000012efa796b base::MessagePumpCFRunLoopBase::Run(base::MessagePump::Delegate*) + 155 35 Electron Framework 0x000000012ef4ef97 base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::Run(bool, base::TimeDelta) + 695 36 Electron Framework 0x000000012ef01dc6 base::RunLoop::Run(base::Location const&) + 726 37 Electron Framework 0x000000012dac4c83 content::BrowserMainLoop::RunMainMessageLoop() + 243 38 Electron Framework 0x000000012dac6822 content::BrowserMainRunnerImpl::Run() + 82 39 Electron Framework 0x000000012dac1fce content::BrowserMain(content::MainFunctionParams) + 270 40 Electron Framework 0x000000012a90bd12 content::RunBrowserProcessMain(content::MainFunctionParams, content::ContentMainDelegate*) + 258 41 Electron Framework 0x000000012a90d28b content::ContentMainRunnerImpl::RunBrowser(content::MainFunctionParams, bool) + 1403 42 Electron Framework 0x000000012a90cc90 content::ContentMainRunnerImpl::Run() + 736 43 Electron Framework 0x000000012a90b637 content::RunContentProcess(content::ContentMainParams, content::ContentMainRunner*) + 2679 44 Electron Framework 0x000000012a90b752 content::ContentMain(content::ContentMainParams) + 98 45 Electron Framework 0x000000012a4b883d ElectronMain + 157 46 dyld 0x0000000114aee51e start + 462 Task trace: 0 Electron Framework 0x000000012a56f8b0 electron::api::WebContents::Print(gin::Arguments*) + 2832 1 Electron Framework 0x000000012a56f8b0 electron::api::WebContents::Print(gin::Arguments*) + 2832 2 Electron Framework 0x000000012f718430 IPC::(anonymous namespace)::ChannelAssociatedGroupController::Accept(mojo::Message*) + 784 3 Electron Framework 0x000000012f2f4f9e mojo::SimpleWatcher::Context::Notify(unsigned int, MojoHandleSignalsState, unsigned int) + 430 Crash keys: "ui_scheduler_async_stack" = "0x12A56F8B0 0x12A56F8B0" "io_scheduler_async_stack" = "0x12BEBEDDB 0x0" "platform" = "darwin" "process_type" = "browser" ``` </details>
https://github.com/electron/electron/issues/34270
https://github.com/electron/electron/pull/34271
73e0bf973d2b7835290d61cab6638309a21a2719
588005a9d5a74b953961605579cf4ad6f8dc2b20
2022-05-18T09:05:02Z
c++
2022-05-19T08:05:07Z
shell/browser/api/electron_api_web_contents.h
// Copyright (c) 2014 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #ifndef ELECTRON_SHELL_BROWSER_API_ELECTRON_API_WEB_CONTENTS_H_ #define ELECTRON_SHELL_BROWSER_API_ELECTRON_API_WEB_CONTENTS_H_ #include <map> #include <memory> #include <string> #include <utility> #include <vector> #include "base/memory/weak_ptr.h" #include "base/observer_list.h" #include "base/observer_list_types.h" #include "chrome/browser/devtools/devtools_eye_dropper.h" #include "chrome/browser/devtools/devtools_file_system_indexer.h" #include "chrome/browser/ui/exclusive_access/exclusive_access_context.h" // nogncheck #include "content/common/cursors/webcursor.h" #include "content/common/frame.mojom.h" #include "content/public/browser/devtools_agent_host.h" #include "content/public/browser/keyboard_event_processing_result.h" #include "content/public/browser/render_widget_host.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_contents_delegate.h" #include "content/public/browser/web_contents_observer.h" #include "electron/buildflags/buildflags.h" #include "electron/shell/common/api/api.mojom.h" #include "gin/handle.h" #include "gin/wrappable.h" #include "mojo/public/cpp/bindings/receiver_set.h" #include "printing/buildflags/buildflags.h" #include "shell/browser/api/frame_subscriber.h" #include "shell/browser/api/save_page_handler.h" #include "shell/browser/event_emitter_mixin.h" #include "shell/browser/extended_web_contents_observer.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/ui/inspectable_web_contents_delegate.h" #include "shell/browser/ui/inspectable_web_contents_view_delegate.h" #include "shell/common/gin_helper/cleaned_up_at_exit.h" #include "shell/common/gin_helper/constructible.h" #include "shell/common/gin_helper/error_thrower.h" #include "shell/common/gin_helper/pinnable.h" #include "third_party/blink/public/common/permissions/permission_utils.h" #include "ui/base/models/image_model.h" #include "ui/gfx/image/image.h" #if BUILDFLAG(ENABLE_PRINTING) #include "shell/browser/printing/print_preview_message_handler.h" #include "shell/browser/printing/print_view_manager_electron.h" #endif #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #include "extensions/common/mojom/view_type.mojom.h" namespace extensions { class ScriptExecutor; } #endif namespace blink { struct DeviceEmulationParams; // enum class PermissionType; } // namespace blink namespace gin_helper { class Dictionary; } namespace network { class ResourceRequestBody; } namespace gin { class Arguments; } class ExclusiveAccessManager; namespace electron { class ElectronBrowserContext; class ElectronJavaScriptDialogManager; class InspectableWebContents; class WebContentsZoomController; class WebViewGuestDelegate; class FrameSubscriber; class WebDialogHelper; class NativeWindow; #if BUILDFLAG(ENABLE_OSR) class OffScreenRenderWidgetHostView; class OffScreenWebContentsView; #endif namespace api { using DevicePermissionMap = std::map< int, std::map<blink::PermissionType, std::map<url::Origin, std::vector<std::unique_ptr<base::Value>>>>>; // Wrapper around the content::WebContents. class WebContents : public ExclusiveAccessContext, public gin::Wrappable<WebContents>, public gin_helper::EventEmitterMixin<WebContents>, public gin_helper::Constructible<WebContents>, public gin_helper::Pinnable<WebContents>, public gin_helper::CleanedUpAtExit, public content::WebContentsObserver, public content::WebContentsDelegate, public InspectableWebContentsDelegate, public InspectableWebContentsViewDelegate { public: enum class Type { kBackgroundPage, // An extension background page. kBrowserWindow, // Used by BrowserWindow. kBrowserView, // Used by BrowserView. kRemote, // Thin wrap around an existing WebContents. kWebView, // Used by <webview>. kOffScreen, // Used for offscreen rendering }; // Create a new WebContents and return the V8 wrapper of it. static gin::Handle<WebContents> New(v8::Isolate* isolate, const gin_helper::Dictionary& options); // Create a new V8 wrapper for an existing |web_content|. // // The lifetime of |web_contents| will be managed by this class. static gin::Handle<WebContents> CreateAndTake( v8::Isolate* isolate, std::unique_ptr<content::WebContents> web_contents, Type type); // Get the api::WebContents associated with |web_contents|. Returns nullptr // if there is no associated wrapper. static WebContents* From(content::WebContents* web_contents); static WebContents* FromID(int32_t id); // Get the V8 wrapper of the |web_contents|, or create one if not existed. // // The lifetime of |web_contents| is NOT managed by this class, and the type // of this wrapper is always REMOTE. static gin::Handle<WebContents> FromOrCreate( v8::Isolate* isolate, content::WebContents* web_contents); static gin::Handle<WebContents> CreateFromWebPreferences( v8::Isolate* isolate, const gin_helper::Dictionary& web_preferences); // gin::Wrappable static gin::WrapperInfo kWrapperInfo; static v8::Local<v8::ObjectTemplate> FillObjectTemplate( v8::Isolate*, v8::Local<v8::ObjectTemplate>); const char* GetTypeName() override; void Destroy(); base::WeakPtr<WebContents> GetWeakPtr() { return weak_factory_.GetWeakPtr(); } bool GetBackgroundThrottling() const; void SetBackgroundThrottling(bool allowed); int GetProcessID() const; base::ProcessId GetOSProcessID() const; Type GetType() const; bool Equal(const WebContents* web_contents) const; void LoadURL(const GURL& url, const gin_helper::Dictionary& options); void Reload(); void ReloadIgnoringCache(); void DownloadURL(const GURL& url); GURL GetURL() const; std::u16string GetTitle() const; bool IsLoading() const; bool IsLoadingMainFrame() const; bool IsWaitingForResponse() const; void Stop(); bool CanGoBack() const; void GoBack(); bool CanGoForward() const; void GoForward(); bool CanGoToOffset(int offset) const; void GoToOffset(int offset); bool CanGoToIndex(int index) const; void GoToIndex(int index); int GetActiveIndex() const; void ClearHistory(); int GetHistoryLength() const; const std::string GetWebRTCIPHandlingPolicy() const; void SetWebRTCIPHandlingPolicy(const std::string& webrtc_ip_handling_policy); std::string GetMediaSourceID(content::WebContents* request_web_contents); bool IsCrashed() const; void ForcefullyCrashRenderer(); void SetUserAgent(const std::string& user_agent); std::string GetUserAgent(); void InsertCSS(const std::string& css); v8::Local<v8::Promise> SavePage(const base::FilePath& full_file_path, const content::SavePageType& save_type); void OpenDevTools(gin::Arguments* args); void CloseDevTools(); bool IsDevToolsOpened(); bool IsDevToolsFocused(); void ToggleDevTools(); void EnableDeviceEmulation(const blink::DeviceEmulationParams& params); void DisableDeviceEmulation(); void InspectElement(int x, int y); void InspectSharedWorker(); void InspectSharedWorkerById(const std::string& workerId); std::vector<scoped_refptr<content::DevToolsAgentHost>> GetAllSharedWorkers(); void InspectServiceWorker(); void SetIgnoreMenuShortcuts(bool ignore); void SetAudioMuted(bool muted); bool IsAudioMuted(); bool IsCurrentlyAudible(); void SetEmbedder(const WebContents* embedder); void SetDevToolsWebContents(const WebContents* devtools); v8::Local<v8::Value> GetNativeView(v8::Isolate* isolate) const; void IncrementCapturerCount(gin::Arguments* args); void DecrementCapturerCount(gin::Arguments* args); bool IsBeingCaptured(); void HandleNewRenderFrame(content::RenderFrameHost* render_frame_host); #if BUILDFLAG(ENABLE_PRINTING) void OnGetDefaultPrinter(base::Value print_settings, printing::CompletionCallback print_callback, std::u16string device_name, bool silent, // <error, default_printer_name> std::pair<std::string, std::u16string> info); void Print(gin::Arguments* args); // Print current page as PDF. v8::Local<v8::Promise> PrintToPDF(base::DictionaryValue settings); #endif void SetNextChildWebPreferences(const gin_helper::Dictionary); // DevTools workspace api. void AddWorkSpace(gin::Arguments* args, const base::FilePath& path); void RemoveWorkSpace(gin::Arguments* args, const base::FilePath& path); // Editing commands. void Undo(); void Redo(); void Cut(); void Copy(); void Paste(); void PasteAndMatchStyle(); void Delete(); void SelectAll(); void Unselect(); void Replace(const std::u16string& word); void ReplaceMisspelling(const std::u16string& word); uint32_t FindInPage(gin::Arguments* args); void StopFindInPage(content::StopFindAction action); void ShowDefinitionForSelection(); void CopyImageAt(int x, int y); // Focus. void Focus(); bool IsFocused() const; // Send WebInputEvent to the page. void SendInputEvent(v8::Isolate* isolate, v8::Local<v8::Value> input_event); // Subscribe to the frame updates. void BeginFrameSubscription(gin::Arguments* args); void EndFrameSubscription(); // Dragging native items. void StartDrag(const gin_helper::Dictionary& item, gin::Arguments* args); // Captures the page with |rect|, |callback| would be called when capturing is // done. v8::Local<v8::Promise> CapturePage(gin::Arguments* args); // Methods for creating <webview>. bool IsGuest() const; void AttachToIframe(content::WebContents* embedder_web_contents, int embedder_frame_id); void DetachFromOuterFrame(); // Methods for offscreen rendering bool IsOffScreen() const; #if BUILDFLAG(ENABLE_OSR) void OnPaint(const gfx::Rect& dirty_rect, const SkBitmap& bitmap); void StartPainting(); void StopPainting(); bool IsPainting() const; void SetFrameRate(int frame_rate); int GetFrameRate() const; #endif void Invalidate(); gfx::Size GetSizeForNewRenderView(content::WebContents*) override; // Methods for zoom handling. void SetZoomLevel(double level); double GetZoomLevel() const; void SetZoomFactor(gin_helper::ErrorThrower thrower, double factor); double GetZoomFactor() const; // Callback triggered on permission response. void OnEnterFullscreenModeForTab( content::RenderFrameHost* requesting_frame, const blink::mojom::FullscreenOptions& options, bool allowed); // Create window with the given disposition. void OnCreateWindow(const GURL& target_url, const content::Referrer& referrer, const std::string& frame_name, WindowOpenDisposition disposition, const std::string& features, const scoped_refptr<network::ResourceRequestBody>& body); // Returns the preload script path of current WebContents. std::vector<base::FilePath> GetPreloadPaths() const; // Returns the web preferences of current WebContents. v8::Local<v8::Value> GetLastWebPreferences(v8::Isolate* isolate) const; // Returns the owner window. v8::Local<v8::Value> GetOwnerBrowserWindow(v8::Isolate* isolate) const; // Notifies the web page that there is user interaction. void NotifyUserActivation(); v8::Local<v8::Promise> TakeHeapSnapshot(v8::Isolate* isolate, const base::FilePath& file_path); v8::Local<v8::Promise> GetProcessMemoryInfo(v8::Isolate* isolate); // Properties. int32_t ID() const { return id_; } v8::Local<v8::Value> Session(v8::Isolate* isolate); content::WebContents* HostWebContents() const; v8::Local<v8::Value> DevToolsWebContents(v8::Isolate* isolate); v8::Local<v8::Value> Debugger(v8::Isolate* isolate); content::RenderFrameHost* MainFrame(); WebContentsZoomController* GetZoomController() { return zoom_controller_; } void AddObserver(ExtendedWebContentsObserver* obs) { observers_.AddObserver(obs); } void RemoveObserver(ExtendedWebContentsObserver* obs) { // Trying to remove from an empty collection leads to an access violation if (!observers_.empty()) observers_.RemoveObserver(obs); } bool EmitNavigationEvent(const std::string& event, content::NavigationHandle* navigation_handle); // this.emit(name, new Event(sender, message), args...); template <typename... Args> bool EmitWithSender(base::StringPiece name, content::RenderFrameHost* sender, electron::mojom::ElectronApiIPC::InvokeCallback callback, Args&&... args) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); v8::Local<v8::Object> wrapper; if (!GetWrapper(isolate).ToLocal(&wrapper)) return false; v8::Local<v8::Object> event = gin_helper::internal::CreateNativeEvent( isolate, wrapper, sender, std::move(callback)); return EmitCustomEvent(name, event, std::forward<Args>(args)...); } WebContents* embedder() { return embedder_; } #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) extensions::ScriptExecutor* script_executor() { return script_executor_.get(); } #endif // Set the window as owner window. void SetOwnerWindow(NativeWindow* owner_window); void SetOwnerWindow(content::WebContents* web_contents, NativeWindow* owner_window); // Returns the WebContents managed by this delegate. content::WebContents* GetWebContents() const; // Returns the WebContents of devtools. content::WebContents* GetDevToolsWebContents() const; InspectableWebContents* inspectable_web_contents() const { return inspectable_web_contents_.get(); } NativeWindow* owner_window() const { return owner_window_.get(); } bool is_html_fullscreen() const { return html_fullscreen_; } void set_fullscreen_frame(content::RenderFrameHost* rfh) { fullscreen_frame_ = rfh; } // mojom::ElectronApiIPC void Message(bool internal, const std::string& channel, blink::CloneableMessage arguments, content::RenderFrameHost* render_frame_host); void Invoke(bool internal, const std::string& channel, blink::CloneableMessage arguments, electron::mojom::ElectronApiIPC::InvokeCallback callback, content::RenderFrameHost* render_frame_host); void ReceivePostMessage(const std::string& channel, blink::TransferableMessage message, content::RenderFrameHost* render_frame_host); void MessageSync( bool internal, const std::string& channel, blink::CloneableMessage arguments, electron::mojom::ElectronApiIPC::MessageSyncCallback callback, content::RenderFrameHost* render_frame_host); void MessageTo(int32_t web_contents_id, const std::string& channel, blink::CloneableMessage arguments); void MessageHost(const std::string& channel, blink::CloneableMessage arguments, content::RenderFrameHost* render_frame_host); // mojom::ElectronWebContentsUtility void OnFirstNonEmptyLayout(content::RenderFrameHost* render_frame_host); void UpdateDraggableRegions(std::vector<mojom::DraggableRegionPtr> regions); void SetTemporaryZoomLevel(double level); void DoGetZoomLevel( electron::mojom::ElectronWebContentsUtility::DoGetZoomLevelCallback callback); void SetImageAnimationPolicy(const std::string& new_policy); // Grants |origin| access to |device|. // To be used in place of ObjectPermissionContextBase::GrantObjectPermission. void GrantDevicePermission(const url::Origin& origin, const base::Value* device, blink::PermissionType permissionType, content::RenderFrameHost* render_frame_host); // Returns the list of devices that |origin| has been granted permission to // access. To be used in place of // ObjectPermissionContextBase::GetGrantedObjects. std::vector<base::Value> GetGrantedDevices( const url::Origin& origin, blink::PermissionType permissionType, content::RenderFrameHost* render_frame_host); // disable copy WebContents(const WebContents&) = delete; WebContents& operator=(const WebContents&) = delete; private: // Does not manage lifetime of |web_contents|. WebContents(v8::Isolate* isolate, content::WebContents* web_contents); // Takes over ownership of |web_contents|. WebContents(v8::Isolate* isolate, std::unique_ptr<content::WebContents> web_contents, Type type); // Creates a new content::WebContents. WebContents(v8::Isolate* isolate, const gin_helper::Dictionary& options); ~WebContents() override; // Delete this if garbage collection has not started. void DeleteThisIfAlive(); // Creates a InspectableWebContents object and takes ownership of // |web_contents|. void InitWithWebContents(std::unique_ptr<content::WebContents> web_contents, ElectronBrowserContext* browser_context, bool is_guest); void InitWithSessionAndOptions( v8::Isolate* isolate, std::unique_ptr<content::WebContents> web_contents, gin::Handle<class Session> session, const gin_helper::Dictionary& options); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) void InitWithExtensionView(v8::Isolate* isolate, content::WebContents* web_contents, extensions::mojom::ViewType view_type); #endif // content::WebContentsDelegate: bool DidAddMessageToConsole(content::WebContents* source, blink::mojom::ConsoleMessageLevel level, const std::u16string& message, int32_t line_no, const std::u16string& source_id) override; bool IsWebContentsCreationOverridden( content::SiteInstance* source_site_instance, content::mojom::WindowContainerType window_container_type, const GURL& opener_url, const content::mojom::CreateNewWindowParams& params) override; content::WebContents* CreateCustomWebContents( content::RenderFrameHost* opener, content::SiteInstance* source_site_instance, bool is_new_browsing_instance, const GURL& opener_url, const std::string& frame_name, const GURL& target_url, const content::StoragePartitionConfig& partition_config, content::SessionStorageNamespace* session_storage_namespace) override; void WebContentsCreatedWithFullParams( content::WebContents* source_contents, int opener_render_process_id, int opener_render_frame_id, const content::mojom::CreateNewWindowParams& params, content::WebContents* new_contents) override; void AddNewContents(content::WebContents* source, std::unique_ptr<content::WebContents> new_contents, const GURL& target_url, WindowOpenDisposition disposition, const gfx::Rect& initial_rect, bool user_gesture, bool* was_blocked) override; content::WebContents* OpenURLFromTab( content::WebContents* source, const content::OpenURLParams& params) override; void BeforeUnloadFired(content::WebContents* tab, bool proceed, bool* proceed_to_fire_unload) override; void SetContentsBounds(content::WebContents* source, const gfx::Rect& pos) override; void CloseContents(content::WebContents* source) override; void ActivateContents(content::WebContents* contents) override; void UpdateTargetURL(content::WebContents* source, const GURL& url) override; bool HandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) override; bool PlatformHandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event); content::KeyboardEventProcessingResult PreHandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) override; void ContentsZoomChange(bool zoom_in) override; void EnterFullscreenModeForTab( content::RenderFrameHost* requesting_frame, const blink::mojom::FullscreenOptions& options) override; void ExitFullscreenModeForTab(content::WebContents* source) override; void RendererUnresponsive( content::WebContents* source, content::RenderWidgetHost* render_widget_host, base::RepeatingClosure hang_monitor_restarter) override; void RendererResponsive( content::WebContents* source, content::RenderWidgetHost* render_widget_host) override; bool HandleContextMenu(content::RenderFrameHost& render_frame_host, const content::ContextMenuParams& params) override; bool OnGoToEntryOffset(int offset) override; void FindReply(content::WebContents* web_contents, int request_id, int number_of_matches, const gfx::Rect& selection_rect, int active_match_ordinal, bool final_update) override; void RequestExclusivePointerAccess(content::WebContents* web_contents, bool user_gesture, bool last_unlocked_by_target, bool allowed); void RequestToLockMouse(content::WebContents* web_contents, bool user_gesture, bool last_unlocked_by_target) override; void LostMouseLock() override; void RequestKeyboardLock(content::WebContents* web_contents, bool esc_key_locked) override; void CancelKeyboardLockRequest(content::WebContents* web_contents) override; bool CheckMediaAccessPermission(content::RenderFrameHost* render_frame_host, const GURL& security_origin, blink::mojom::MediaStreamType type) override; void RequestMediaAccessPermission( content::WebContents* web_contents, const content::MediaStreamRequest& request, content::MediaResponseCallback callback) override; content::JavaScriptDialogManager* GetJavaScriptDialogManager( content::WebContents* source) override; void OnAudioStateChanged(bool audible) override; void UpdatePreferredSize(content::WebContents* web_contents, const gfx::Size& pref_size) override; // content::WebContentsObserver: void BeforeUnloadFired(bool proceed, const base::TimeTicks& proceed_time) override; void OnBackgroundColorChanged() override; void RenderFrameCreated(content::RenderFrameHost* render_frame_host) override; void RenderFrameDeleted(content::RenderFrameHost* render_frame_host) override; void RenderFrameHostChanged(content::RenderFrameHost* old_host, content::RenderFrameHost* new_host) override; void FrameDeleted(int frame_tree_node_id) override; void RenderViewDeleted(content::RenderViewHost*) override; void PrimaryMainFrameRenderProcessGone( base::TerminationStatus status) override; void DOMContentLoaded(content::RenderFrameHost* render_frame_host) override; void DidFinishLoad(content::RenderFrameHost* render_frame_host, const GURL& validated_url) override; void DidFailLoad(content::RenderFrameHost* render_frame_host, const GURL& validated_url, int error_code) override; void DidStartLoading() override; void DidStopLoading() override; void DidStartNavigation( content::NavigationHandle* navigation_handle) override; void DidRedirectNavigation( content::NavigationHandle* navigation_handle) override; void ReadyToCommitNavigation( content::NavigationHandle* navigation_handle) override; void DidFinishNavigation( content::NavigationHandle* navigation_handle) override; void WebContentsDestroyed() override; void NavigationEntryCommitted( const content::LoadCommittedDetails& load_details) override; void TitleWasSet(content::NavigationEntry* entry) override; void DidUpdateFaviconURL( content::RenderFrameHost* render_frame_host, const std::vector<blink::mojom::FaviconURLPtr>& urls) override; void PluginCrashed(const base::FilePath& plugin_path, base::ProcessId plugin_pid) override; void MediaStartedPlaying(const MediaPlayerInfo& video_type, const content::MediaPlayerId& id) override; void MediaStoppedPlaying( const MediaPlayerInfo& video_type, const content::MediaPlayerId& id, content::WebContentsObserver::MediaStoppedReason reason) override; void DidChangeThemeColor() override; void OnCursorChanged(const content::WebCursor& cursor) override; void DidAcquireFullscreen(content::RenderFrameHost* rfh) override; void OnWebContentsFocused( content::RenderWidgetHost* render_widget_host) override; void OnWebContentsLostFocus( content::RenderWidgetHost* render_widget_host) override; // InspectableWebContentsDelegate: void DevToolsReloadPage() override; // InspectableWebContentsViewDelegate: void DevToolsFocused() override; void DevToolsOpened() override; void DevToolsClosed() override; void DevToolsResized() override; ElectronBrowserContext* GetBrowserContext() const; void OnElectronBrowserConnectionError(); #if BUILDFLAG(ENABLE_OSR) OffScreenWebContentsView* GetOffScreenWebContentsView() const; OffScreenRenderWidgetHostView* GetOffScreenRenderWidgetHostView() const; #endif // Called when received a synchronous message from renderer to // get the zoom level. void OnGetZoomLevel(content::RenderFrameHost* frame_host, IPC::Message* reply_msg); void InitZoomController(content::WebContents* web_contents, const gin_helper::Dictionary& options); // content::WebContentsDelegate: bool CanOverscrollContent() override; std::unique_ptr<content::EyeDropper> OpenEyeDropper( content::RenderFrameHost* frame, content::EyeDropperListener* listener) override; void RunFileChooser(content::RenderFrameHost* render_frame_host, scoped_refptr<content::FileSelectListener> listener, const blink::mojom::FileChooserParams& params) override; void EnumerateDirectory(content::WebContents* web_contents, scoped_refptr<content::FileSelectListener> listener, const base::FilePath& path) override; // ExclusiveAccessContext: Profile* GetProfile() override; bool IsFullscreen() const override; void EnterFullscreen(const GURL& url, ExclusiveAccessBubbleType bubble_type, const int64_t display_id) override; void ExitFullscreen() override; void UpdateExclusiveAccessExitBubbleContent( const GURL& url, ExclusiveAccessBubbleType bubble_type, ExclusiveAccessBubbleHideCallback bubble_first_hide_callback, bool force_update) override; void OnExclusiveAccessUserInput() override; content::WebContents* GetActiveWebContents() override; bool CanUserExitFullscreen() const override; bool IsExclusiveAccessBubbleDisplayed() const override; bool IsFullscreenForTabOrPending(const content::WebContents* source) override; bool TakeFocus(content::WebContents* source, bool reverse) override; content::PictureInPictureResult EnterPictureInPicture( content::WebContents* web_contents) override; void ExitPictureInPicture() override; // InspectableWebContentsDelegate: void DevToolsSaveToFile(const std::string& url, const std::string& content, bool save_as) override; void DevToolsAppendToFile(const std::string& url, const std::string& content) override; void DevToolsRequestFileSystems() override; void DevToolsAddFileSystem(const std::string& type, const base::FilePath& file_system_path) override; void DevToolsRemoveFileSystem( const base::FilePath& file_system_path) override; void DevToolsIndexPath(int request_id, const std::string& file_system_path, const std::string& excluded_folders_message) override; void DevToolsStopIndexing(int request_id) override; void DevToolsSearchInPath(int request_id, const std::string& file_system_path, const std::string& query) override; void DevToolsSetEyeDropperActive(bool active) override; // InspectableWebContentsViewDelegate: #if defined(TOOLKIT_VIEWS) && !BUILDFLAG(IS_MAC) ui::ImageModel GetDevToolsWindowIcon() override; #endif #if BUILDFLAG(IS_LINUX) void GetDevToolsWindowWMClass(std::string* name, std::string* class_name) override; #endif void ColorPickedInEyeDropper(int r, int g, int b, int a); // DevTools index event callbacks. void OnDevToolsIndexingWorkCalculated(int request_id, const std::string& file_system_path, int total_work); void OnDevToolsIndexingWorked(int request_id, const std::string& file_system_path, int worked); void OnDevToolsIndexingDone(int request_id, const std::string& file_system_path); void OnDevToolsSearchCompleted(int request_id, const std::string& file_system_path, const std::vector<std::string>& file_paths); // Set fullscreen mode triggered by html api. void SetHtmlApiFullscreen(bool enter_fullscreen); // Update the html fullscreen flag in both browser and renderer. void UpdateHtmlApiFullscreen(bool fullscreen); v8::Global<v8::Value> session_; v8::Global<v8::Value> devtools_web_contents_; v8::Global<v8::Value> debugger_; std::unique_ptr<ElectronJavaScriptDialogManager> dialog_manager_; std::unique_ptr<WebViewGuestDelegate> guest_delegate_; std::unique_ptr<FrameSubscriber> frame_subscriber_; #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) std::unique_ptr<extensions::ScriptExecutor> script_executor_; #endif // The host webcontents that may contain this webcontents. WebContents* embedder_ = nullptr; // Whether the guest view has been attached. bool attached_ = false; // The zoom controller for this webContents. WebContentsZoomController* zoom_controller_ = nullptr; // The type of current WebContents. Type type_ = Type::kBrowserWindow; int32_t id_; // Request id used for findInPage request. uint32_t find_in_page_request_id_ = 0; // Whether background throttling is disabled. bool background_throttling_ = true; // Whether to enable devtools. bool enable_devtools_ = true; // Observers of this WebContents. base::ObserverList<ExtendedWebContentsObserver> observers_; v8::Global<v8::Value> pending_child_web_preferences_; // The window that this WebContents belongs to. base::WeakPtr<NativeWindow> owner_window_; bool offscreen_ = false; // Whether window is fullscreened by HTML5 api. bool html_fullscreen_ = false; // Whether window is fullscreened by window api. bool native_fullscreen_ = false; scoped_refptr<DevToolsFileSystemIndexer> devtools_file_system_indexer_; std::unique_ptr<ExclusiveAccessManager> exclusive_access_manager_; std::unique_ptr<DevToolsEyeDropper> eye_dropper_; ElectronBrowserContext* browser_context_; // The stored InspectableWebContents object. // Notice that inspectable_web_contents_ must be placed after // dialog_manager_, so we can make sure inspectable_web_contents_ is // destroyed before dialog_manager_, otherwise a crash would happen. std::unique_ptr<InspectableWebContents> inspectable_web_contents_; // Maps url to file path, used by the file requests sent from devtools. typedef std::map<std::string, base::FilePath> PathsMap; PathsMap saved_files_; // Map id to index job, used for file system indexing requests from devtools. typedef std:: map<int, scoped_refptr<DevToolsFileSystemIndexer::FileSystemIndexingJob>> DevToolsIndexingJobsMap; DevToolsIndexingJobsMap devtools_indexing_jobs_; scoped_refptr<base::SequencedTaskRunner> file_task_runner_; #if BUILDFLAG(ENABLE_PRINTING) scoped_refptr<base::TaskRunner> print_task_runner_; #endif // Stores the frame thats currently in fullscreen, nullptr if there is none. content::RenderFrameHost* fullscreen_frame_ = nullptr; // In-memory cache that holds objects that have been granted permissions. DevicePermissionMap granted_devices_; base::WeakPtrFactory<WebContents> weak_factory_{this}; }; } // namespace api } // namespace electron #endif // ELECTRON_SHELL_BROWSER_API_ELECTRON_API_WEB_CONTENTS_H_
closed
electron/electron
https://github.com/electron/electron
33,880
[Bug]: Crash in WebFrameMain::Connect() -> GetInterface -> GetInterfaceByName
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17, 18 ### What operating system are you using? Windows ### Operating System Version Windows 10 19042.985 ### What arch are you using? x64 ### Last Known Working Electron version 14 ### Expected Behavior No crash ### Actual Behavior Electron crashes ![2022-04-21 10_07_53-Source Not Found (Debugging) - Microsoft Visual Studio](https://user-images.githubusercontent.com/10595986/164416772-c4800f31-d165-4639-88e3-23be25d8fe8c.png) This does not happen consistently but fairly often and can be reproduced in the app. I have not been able yet to make a small/standalone reproducable example ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/33880
https://github.com/electron/electron/pull/33919
17c8ec765bd40add42e22bd72a56317bfb9b2dbd
5ff94e7f2becc435e4e7c66e112686461b74e95b
2022-04-21T08:50:39Z
c++
2022-05-19T18:34:58Z
shell/browser/api/electron_api_web_contents.cc
// Copyright (c) 2014 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/api/electron_api_web_contents.h" #include <limits> #include <memory> #include <set> #include <string> #include <unordered_set> #include <utility> #include <vector> #include "base/containers/id_map.h" #include "base/files/file_util.h" #include "base/json/json_reader.h" #include "base/no_destructor.h" #include "base/strings/utf_string_conversions.h" #include "base/task/current_thread.h" #include "base/task/thread_pool.h" #include "base/threading/scoped_blocking_call.h" #include "base/threading/sequenced_task_runner_handle.h" #include "base/threading/thread_restrictions.h" #include "base/threading/thread_task_runner_handle.h" #include "base/values.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/ui/exclusive_access/exclusive_access_manager.h" #include "chrome/browser/ui/views/eye_dropper/eye_dropper.h" #include "chrome/common/pref_names.h" #include "components/prefs/pref_service.h" #include "components/prefs/scoped_user_pref_update.h" #include "components/security_state/content/content_utils.h" #include "components/security_state/core/security_state.h" #include "content/browser/renderer_host/frame_tree_node.h" // nogncheck #include "content/browser/renderer_host/render_frame_host_manager.h" // nogncheck #include "content/browser/renderer_host/render_widget_host_impl.h" // nogncheck #include "content/browser/renderer_host/render_widget_host_view_base.h" // nogncheck #include "content/public/browser/child_process_security_policy.h" #include "content/public/browser/context_menu_params.h" #include "content/public/browser/desktop_media_id.h" #include "content/public/browser/desktop_streams_registry.h" #include "content/public/browser/download_request_utils.h" #include "content/public/browser/favicon_status.h" #include "content/public/browser/file_select_listener.h" #include "content/public/browser/native_web_keyboard_event.h" #include "content/public/browser/navigation_details.h" #include "content/public/browser/navigation_entry.h" #include "content/public/browser/navigation_handle.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/render_widget_host.h" #include "content/public/browser/render_widget_host_view.h" #include "content/public/browser/service_worker_context.h" #include "content/public/browser/site_instance.h" #include "content/public/browser/storage_partition.h" #include "content/public/browser/web_contents.h" #include "content/public/common/referrer_type_converters.h" #include "content/public/common/webplugininfo.h" #include "electron/buildflags/buildflags.h" #include "electron/shell/common/api/api.mojom.h" #include "gin/arguments.h" #include "gin/data_object_builder.h" #include "gin/handle.h" #include "gin/object_template_builder.h" #include "gin/wrappable.h" #include "mojo/public/cpp/bindings/associated_remote.h" #include "mojo/public/cpp/bindings/pending_receiver.h" #include "mojo/public/cpp/bindings/remote.h" #include "mojo/public/cpp/system/platform_handle.h" #include "ppapi/buildflags/buildflags.h" #include "printing/buildflags/buildflags.h" #include "printing/print_job_constants.h" #include "services/resource_coordinator/public/cpp/memory_instrumentation/memory_instrumentation.h" #include "services/service_manager/public/cpp/interface_provider.h" #include "shell/browser/api/electron_api_browser_window.h" #include "shell/browser/api/electron_api_debugger.h" #include "shell/browser/api/electron_api_session.h" #include "shell/browser/api/electron_api_web_frame_main.h" #include "shell/browser/api/message_port.h" #include "shell/browser/browser.h" #include "shell/browser/child_web_contents_tracker.h" #include "shell/browser/electron_autofill_driver_factory.h" #include "shell/browser/electron_browser_client.h" #include "shell/browser/electron_browser_context.h" #include "shell/browser/electron_browser_main_parts.h" #include "shell/browser/electron_javascript_dialog_manager.h" #include "shell/browser/electron_navigation_throttle.h" #include "shell/browser/file_select_helper.h" #include "shell/browser/native_window.h" #include "shell/browser/session_preferences.h" #include "shell/browser/ui/drag_util.h" #include "shell/browser/ui/file_dialog.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/ui/inspectable_web_contents_view.h" #include "shell/browser/web_contents_permission_helper.h" #include "shell/browser/web_contents_preferences.h" #include "shell/browser/web_contents_zoom_controller.h" #include "shell/browser/web_view_guest_delegate.h" #include "shell/browser/web_view_manager.h" #include "shell/common/api/electron_api_native_image.h" #include "shell/common/api/electron_bindings.h" #include "shell/common/color_util.h" #include "shell/common/electron_constants.h" #include "shell/common/gin_converters/base_converter.h" #include "shell/common/gin_converters/blink_converter.h" #include "shell/common/gin_converters/callback_converter.h" #include "shell/common/gin_converters/content_converter.h" #include "shell/common/gin_converters/file_path_converter.h" #include "shell/common/gin_converters/frame_converter.h" #include "shell/common/gin_converters/gfx_converter.h" #include "shell/common/gin_converters/gurl_converter.h" #include "shell/common/gin_converters/image_converter.h" #include "shell/common/gin_converters/net_converter.h" #include "shell/common/gin_converters/value_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/gin_helper/object_template_builder.h" #include "shell/common/language_util.h" #include "shell/common/mouse_util.h" #include "shell/common/node_includes.h" #include "shell/common/options_switches.h" #include "shell/common/process_util.h" #include "shell/common/v8_value_serializer.h" #include "storage/browser/file_system/isolated_context.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h" #include "third_party/blink/public/common/input/web_input_event.h" #include "third_party/blink/public/common/messaging/transferable_message_mojom_traits.h" #include "third_party/blink/public/common/page/page_zoom.h" #include "third_party/blink/public/mojom/frame/find_in_page.mojom.h" #include "third_party/blink/public/mojom/frame/fullscreen.mojom.h" #include "third_party/blink/public/mojom/messaging/transferable_message.mojom.h" #include "third_party/blink/public/mojom/renderer_preferences.mojom.h" #include "ui/base/cursor/cursor.h" #include "ui/base/cursor/mojom/cursor_type.mojom-shared.h" #include "ui/display/screen.h" #include "ui/events/base_event_utils.h" #if BUILDFLAG(ENABLE_OSR) #include "shell/browser/osr/osr_render_widget_host_view.h" #include "shell/browser/osr/osr_web_contents_view.h" #endif #if !BUILDFLAG(IS_MAC) #include "ui/aura/window.h" #else #include "ui/base/cocoa/defaults_utils.h" #endif #if BUILDFLAG(IS_LINUX) #include "ui/views/linux_ui/linux_ui.h" #endif #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_WIN) #include "ui/gfx/font_render_params.h" #endif #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #include "extensions/browser/script_executor.h" #include "extensions/browser/view_type_utils.h" #include "extensions/common/mojom/view_type.mojom.h" #include "shell/browser/extensions/electron_extension_web_contents_observer.h" #endif #if BUILDFLAG(ENABLE_PRINTING) #include "components/printing/browser/print_manager_utils.h" #include "printing/backend/print_backend.h" // nogncheck #include "printing/mojom/print.mojom.h" // nogncheck #include "shell/browser/printing/print_preview_message_handler.h" #include "shell/browser/printing/print_view_manager_electron.h" #if BUILDFLAG(IS_WIN) #include "printing/backend/win_helper.h" #endif #endif #if BUILDFLAG(ENABLE_PICTURE_IN_PICTURE) #include "chrome/browser/picture_in_picture/picture_in_picture_window_manager.h" #endif #if BUILDFLAG(ENABLE_PDF_VIEWER) #include "components/pdf/browser/pdf_web_contents_helper.h" // nogncheck #include "shell/browser/electron_pdf_web_contents_helper_client.h" #endif #if BUILDFLAG(ENABLE_PLUGINS) #include "content/public/browser/plugin_service.h" #endif #ifndef MAS_BUILD #include "chrome/browser/hang_monitor/hang_crash_dump.h" // nogncheck #endif namespace gin { #if BUILDFLAG(ENABLE_PRINTING) template <> struct Converter<printing::mojom::MarginType> { static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, printing::mojom::MarginType* out) { std::string type; if (ConvertFromV8(isolate, val, &type)) { if (type == "default") { *out = printing::mojom::MarginType::kDefaultMargins; return true; } if (type == "none") { *out = printing::mojom::MarginType::kNoMargins; return true; } if (type == "printableArea") { *out = printing::mojom::MarginType::kPrintableAreaMargins; return true; } if (type == "custom") { *out = printing::mojom::MarginType::kCustomMargins; return true; } } return false; } }; template <> struct Converter<printing::mojom::DuplexMode> { static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, printing::mojom::DuplexMode* out) { std::string mode; if (ConvertFromV8(isolate, val, &mode)) { if (mode == "simplex") { *out = printing::mojom::DuplexMode::kSimplex; return true; } if (mode == "longEdge") { *out = printing::mojom::DuplexMode::kLongEdge; return true; } if (mode == "shortEdge") { *out = printing::mojom::DuplexMode::kShortEdge; return true; } } return false; } }; #endif template <> struct Converter<WindowOpenDisposition> { static v8::Local<v8::Value> ToV8(v8::Isolate* isolate, WindowOpenDisposition val) { std::string disposition = "other"; switch (val) { case WindowOpenDisposition::CURRENT_TAB: disposition = "default"; break; case WindowOpenDisposition::NEW_FOREGROUND_TAB: disposition = "foreground-tab"; break; case WindowOpenDisposition::NEW_BACKGROUND_TAB: disposition = "background-tab"; break; case WindowOpenDisposition::NEW_POPUP: case WindowOpenDisposition::NEW_WINDOW: disposition = "new-window"; break; case WindowOpenDisposition::SAVE_TO_DISK: disposition = "save-to-disk"; break; default: break; } return gin::ConvertToV8(isolate, disposition); } }; template <> struct Converter<content::SavePageType> { static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, content::SavePageType* out) { std::string save_type; if (!ConvertFromV8(isolate, val, &save_type)) return false; save_type = base::ToLowerASCII(save_type); if (save_type == "htmlonly") { *out = content::SAVE_PAGE_TYPE_AS_ONLY_HTML; } else if (save_type == "htmlcomplete") { *out = content::SAVE_PAGE_TYPE_AS_COMPLETE_HTML; } else if (save_type == "mhtml") { *out = content::SAVE_PAGE_TYPE_AS_MHTML; } else { return false; } return true; } }; template <> struct Converter<electron::api::WebContents::Type> { static v8::Local<v8::Value> ToV8(v8::Isolate* isolate, electron::api::WebContents::Type val) { using Type = electron::api::WebContents::Type; std::string type; switch (val) { case Type::kBackgroundPage: type = "backgroundPage"; break; case Type::kBrowserWindow: type = "window"; break; case Type::kBrowserView: type = "browserView"; break; case Type::kRemote: type = "remote"; break; case Type::kWebView: type = "webview"; break; case Type::kOffScreen: type = "offscreen"; break; default: break; } return gin::ConvertToV8(isolate, type); } static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, electron::api::WebContents::Type* out) { using Type = electron::api::WebContents::Type; std::string type; if (!ConvertFromV8(isolate, val, &type)) return false; if (type == "backgroundPage") { *out = Type::kBackgroundPage; } else if (type == "browserView") { *out = Type::kBrowserView; } else if (type == "webview") { *out = Type::kWebView; #if BUILDFLAG(ENABLE_OSR) } else if (type == "offscreen") { *out = Type::kOffScreen; #endif } else { return false; } return true; } }; template <> struct Converter<scoped_refptr<content::DevToolsAgentHost>> { static v8::Local<v8::Value> ToV8( v8::Isolate* isolate, const scoped_refptr<content::DevToolsAgentHost>& val) { gin_helper::Dictionary dict(isolate, v8::Object::New(isolate)); dict.Set("id", val->GetId()); dict.Set("url", val->GetURL().spec()); return dict.GetHandle(); } }; } // namespace gin namespace electron { namespace api { namespace { base::IDMap<WebContents*>& GetAllWebContents() { static base::NoDestructor<base::IDMap<WebContents*>> s_all_web_contents; return *s_all_web_contents; } // Called when CapturePage is done. void OnCapturePageDone(gin_helper::Promise<gfx::Image> promise, const SkBitmap& bitmap) { // Hack to enable transparency in captured image promise.Resolve(gfx::Image::CreateFrom1xBitmap(bitmap)); } absl::optional<base::TimeDelta> GetCursorBlinkInterval() { #if BUILDFLAG(IS_MAC) absl::optional<base::TimeDelta> system_value( ui::TextInsertionCaretBlinkPeriodFromDefaults()); if (system_value) return *system_value; #elif BUILDFLAG(IS_LINUX) if (auto* linux_ui = views::LinuxUI::instance()) return linux_ui->GetCursorBlinkInterval(); #elif BUILDFLAG(IS_WIN) const auto system_msec = ::GetCaretBlinkTime(); if (system_msec != 0) { return (system_msec == INFINITE) ? base::TimeDelta() : base::Milliseconds(system_msec); } #endif return absl::nullopt; } #if BUILDFLAG(ENABLE_PRINTING) // This will return false if no printer with the provided device_name can be // found on the network. We need to check this because Chromium does not do // sanity checking of device_name validity and so will crash on invalid names. bool IsDeviceNameValid(const std::u16string& device_name) { #if BUILDFLAG(IS_MAC) base::ScopedCFTypeRef<CFStringRef> new_printer_id( base::SysUTF16ToCFStringRef(device_name)); PMPrinter new_printer = PMPrinterCreateFromPrinterID(new_printer_id.get()); bool printer_exists = new_printer != nullptr; PMRelease(new_printer); return printer_exists; #elif BUILDFLAG(IS_WIN) printing::ScopedPrinterHandle printer; return printer.OpenPrinterWithName(base::as_wcstr(device_name)); #else return true; #endif } std::pair<std::string, std::u16string> GetDefaultPrinterAsync() { #if BUILDFLAG(IS_WIN) // Blocking is needed here because Windows printer drivers are oftentimes // not thread-safe and have to be accessed on the UI thread. base::ThreadRestrictions::ScopedAllowIO allow_io; #endif scoped_refptr<printing::PrintBackend> print_backend = printing::PrintBackend::CreateInstance( g_browser_process->GetApplicationLocale()); std::string printer_name; printing::mojom::ResultCode code = print_backend->GetDefaultPrinterName(printer_name); // We don't want to return if this fails since some devices won't have a // default printer. if (code != printing::mojom::ResultCode::kSuccess) LOG(ERROR) << "Failed to get default printer name"; // Check for existing printers and pick the first one should it exist. if (printer_name.empty()) { printing::PrinterList printers; if (print_backend->EnumeratePrinters(&printers) != printing::mojom::ResultCode::kSuccess) return std::make_pair("Failed to enumerate printers", std::u16string()); if (!printers.empty()) printer_name = printers.front().printer_name; } return std::make_pair(std::string(), base::UTF8ToUTF16(printer_name)); } // Copied from // chrome/browser/ui/webui/print_preview/local_printer_handler_default.cc:L36-L54 scoped_refptr<base::TaskRunner> CreatePrinterHandlerTaskRunner() { // USER_VISIBLE because the result is displayed in the print preview dialog. #if !BUILDFLAG(IS_WIN) static constexpr base::TaskTraits kTraits = { base::MayBlock(), base::TaskPriority::USER_VISIBLE}; #endif #if defined(USE_CUPS) // CUPS is thread safe. return base::ThreadPool::CreateTaskRunner(kTraits); #elif BUILDFLAG(IS_WIN) // Windows drivers are likely not thread-safe and need to be accessed on the // UI thread. return content::GetUIThreadTaskRunner( {base::MayBlock(), base::TaskPriority::USER_VISIBLE}); #else // Be conservative on unsupported platforms. return base::ThreadPool::CreateSingleThreadTaskRunner(kTraits); #endif } #endif struct UserDataLink : public base::SupportsUserData::Data { explicit UserDataLink(base::WeakPtr<WebContents> contents) : web_contents(contents) {} base::WeakPtr<WebContents> web_contents; }; const void* kElectronApiWebContentsKey = &kElectronApiWebContentsKey; const char kRootName[] = "<root>"; struct FileSystem { FileSystem() = default; FileSystem(const std::string& type, const std::string& file_system_name, const std::string& root_url, const std::string& file_system_path) : type(type), file_system_name(file_system_name), root_url(root_url), file_system_path(file_system_path) {} std::string type; std::string file_system_name; std::string root_url; std::string file_system_path; }; std::string RegisterFileSystem(content::WebContents* web_contents, const base::FilePath& path) { auto* isolated_context = storage::IsolatedContext::GetInstance(); std::string root_name(kRootName); storage::IsolatedContext::ScopedFSHandle file_system = isolated_context->RegisterFileSystemForPath( storage::kFileSystemTypeLocal, std::string(), path, &root_name); content::ChildProcessSecurityPolicy* policy = content::ChildProcessSecurityPolicy::GetInstance(); content::RenderViewHost* render_view_host = web_contents->GetRenderViewHost(); int renderer_id = render_view_host->GetProcess()->GetID(); policy->GrantReadFileSystem(renderer_id, file_system.id()); policy->GrantWriteFileSystem(renderer_id, file_system.id()); policy->GrantCreateFileForFileSystem(renderer_id, file_system.id()); policy->GrantDeleteFromFileSystem(renderer_id, file_system.id()); if (!policy->CanReadFile(renderer_id, path)) policy->GrantReadFile(renderer_id, path); return file_system.id(); } FileSystem CreateFileSystemStruct(content::WebContents* web_contents, const std::string& file_system_id, const std::string& file_system_path, const std::string& type) { const GURL origin = web_contents->GetURL().DeprecatedGetOriginAsURL(); std::string file_system_name = storage::GetIsolatedFileSystemName(origin, file_system_id); std::string root_url = storage::GetIsolatedFileSystemRootURIString( origin, file_system_id, kRootName); return FileSystem(type, file_system_name, root_url, file_system_path); } std::unique_ptr<base::DictionaryValue> CreateFileSystemValue( const FileSystem& file_system) { auto file_system_value = std::make_unique<base::DictionaryValue>(); file_system_value->SetString("type", file_system.type); file_system_value->SetString("fileSystemName", file_system.file_system_name); file_system_value->SetString("rootURL", file_system.root_url); file_system_value->SetString("fileSystemPath", file_system.file_system_path); return file_system_value; } void WriteToFile(const base::FilePath& path, const std::string& content) { base::ScopedBlockingCall scoped_blocking_call(FROM_HERE, base::BlockingType::WILL_BLOCK); DCHECK(!path.empty()); base::WriteFile(path, content.data(), content.size()); } void AppendToFile(const base::FilePath& path, const std::string& content) { base::ScopedBlockingCall scoped_blocking_call(FROM_HERE, base::BlockingType::WILL_BLOCK); DCHECK(!path.empty()); base::AppendToFile(path, content); } PrefService* GetPrefService(content::WebContents* web_contents) { auto* context = web_contents->GetBrowserContext(); return static_cast<electron::ElectronBrowserContext*>(context)->prefs(); } std::map<std::string, std::string> GetAddedFileSystemPaths( content::WebContents* web_contents) { auto* pref_service = GetPrefService(web_contents); const base::Value* file_system_paths_value = pref_service->GetDictionary(prefs::kDevToolsFileSystemPaths); std::map<std::string, std::string> result; if (file_system_paths_value) { const base::DictionaryValue* file_system_paths_dict; file_system_paths_value->GetAsDictionary(&file_system_paths_dict); for (auto it : file_system_paths_dict->DictItems()) { std::string type = it.second.is_string() ? it.second.GetString() : std::string(); result[it.first] = type; } } return result; } bool IsDevToolsFileSystemAdded(content::WebContents* web_contents, const std::string& file_system_path) { auto file_system_paths = GetAddedFileSystemPaths(web_contents); return file_system_paths.find(file_system_path) != file_system_paths.end(); } void SetBackgroundColor(content::RenderWidgetHostView* rwhv, SkColor color) { rwhv->SetBackgroundColor(color); static_cast<content::RenderWidgetHostViewBase*>(rwhv) ->SetContentBackgroundColor(color); } } // namespace #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) WebContents::Type GetTypeFromViewType(extensions::mojom::ViewType view_type) { switch (view_type) { case extensions::mojom::ViewType::kExtensionBackgroundPage: return WebContents::Type::kBackgroundPage; case extensions::mojom::ViewType::kAppWindow: case extensions::mojom::ViewType::kComponent: case extensions::mojom::ViewType::kExtensionDialog: case extensions::mojom::ViewType::kExtensionPopup: case extensions::mojom::ViewType::kBackgroundContents: case extensions::mojom::ViewType::kExtensionGuest: case extensions::mojom::ViewType::kTabContents: case extensions::mojom::ViewType::kInvalid: return WebContents::Type::kRemote; } } #endif WebContents::WebContents(v8::Isolate* isolate, content::WebContents* web_contents) : content::WebContentsObserver(web_contents), type_(Type::kRemote), id_(GetAllWebContents().Add(this)), devtools_file_system_indexer_( base::MakeRefCounted<DevToolsFileSystemIndexer>()), exclusive_access_manager_(std::make_unique<ExclusiveAccessManager>(this)), file_task_runner_( base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()})) #if BUILDFLAG(ENABLE_PRINTING) , print_task_runner_(CreatePrinterHandlerTaskRunner()) #endif { #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) // WebContents created by extension host will have valid ViewType set. extensions::mojom::ViewType view_type = extensions::GetViewType(web_contents); if (view_type != extensions::mojom::ViewType::kInvalid) { InitWithExtensionView(isolate, web_contents, view_type); } extensions::ElectronExtensionWebContentsObserver::CreateForWebContents( web_contents); script_executor_ = std::make_unique<extensions::ScriptExecutor>(web_contents); #endif auto session = Session::CreateFrom(isolate, GetBrowserContext()); session_.Reset(isolate, session.ToV8()); web_contents->SetUserAgentOverride(blink::UserAgentOverride::UserAgentOnly( GetBrowserContext()->GetUserAgent()), false); web_contents->SetUserData(kElectronApiWebContentsKey, std::make_unique<UserDataLink>(GetWeakPtr())); InitZoomController(web_contents, gin::Dictionary::CreateEmpty(isolate)); } WebContents::WebContents(v8::Isolate* isolate, std::unique_ptr<content::WebContents> web_contents, Type type) : content::WebContentsObserver(web_contents.get()), type_(type), id_(GetAllWebContents().Add(this)), devtools_file_system_indexer_( base::MakeRefCounted<DevToolsFileSystemIndexer>()), exclusive_access_manager_(std::make_unique<ExclusiveAccessManager>(this)), file_task_runner_( base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()})) #if BUILDFLAG(ENABLE_PRINTING) , print_task_runner_(CreatePrinterHandlerTaskRunner()) #endif { DCHECK(type != Type::kRemote) << "Can't take ownership of a remote WebContents"; auto session = Session::CreateFrom(isolate, GetBrowserContext()); session_.Reset(isolate, session.ToV8()); InitWithSessionAndOptions(isolate, std::move(web_contents), session, gin::Dictionary::CreateEmpty(isolate)); } WebContents::WebContents(v8::Isolate* isolate, const gin_helper::Dictionary& options) : id_(GetAllWebContents().Add(this)), devtools_file_system_indexer_( base::MakeRefCounted<DevToolsFileSystemIndexer>()), exclusive_access_manager_(std::make_unique<ExclusiveAccessManager>(this)), file_task_runner_( base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()})) #if BUILDFLAG(ENABLE_PRINTING) , print_task_runner_(CreatePrinterHandlerTaskRunner()) #endif { // Read options. options.Get("backgroundThrottling", &background_throttling_); // Get type options.Get("type", &type_); #if BUILDFLAG(ENABLE_OSR) bool b = false; if (options.Get(options::kOffscreen, &b) && b) type_ = Type::kOffScreen; #endif // Init embedder earlier options.Get("embedder", &embedder_); // Whether to enable DevTools. options.Get("devTools", &enable_devtools_); // BrowserViews are not attached to a window initially so they should start // off as hidden. This is also important for compositor recycling. See: // https://github.com/electron/electron/pull/21372 bool initially_shown = type_ != Type::kBrowserView; options.Get(options::kShow, &initially_shown); // Obtain the session. std::string partition; gin::Handle<api::Session> session; if (options.Get("session", &session) && !session.IsEmpty()) { } else if (options.Get("partition", &partition)) { session = Session::FromPartition(isolate, partition); } else { // Use the default session if not specified. session = Session::FromPartition(isolate, ""); } session_.Reset(isolate, session.ToV8()); std::unique_ptr<content::WebContents> web_contents; if (IsGuest()) { scoped_refptr<content::SiteInstance> site_instance = content::SiteInstance::CreateForURL(session->browser_context(), GURL("chrome-guest://fake-host")); content::WebContents::CreateParams params(session->browser_context(), site_instance); guest_delegate_ = std::make_unique<WebViewGuestDelegate>(embedder_->web_contents(), this); params.guest_delegate = guest_delegate_.get(); #if BUILDFLAG(ENABLE_OSR) if (embedder_ && embedder_->IsOffScreen()) { auto* view = new OffScreenWebContentsView( false, base::BindRepeating(&WebContents::OnPaint, base::Unretained(this))); params.view = view; params.delegate_view = view; web_contents = content::WebContents::Create(params); view->SetWebContents(web_contents.get()); } else { #endif web_contents = content::WebContents::Create(params); #if BUILDFLAG(ENABLE_OSR) } } else if (IsOffScreen()) { // webPreferences does not have a transparent option, so if the window needs // to be transparent, that will be set at electron_api_browser_window.cc#L57 // and we then need to pull it back out and check it here. std::string background_color; options.GetHidden(options::kBackgroundColor, &background_color); bool transparent = ParseCSSColor(background_color) == SK_ColorTRANSPARENT; content::WebContents::CreateParams params(session->browser_context()); auto* view = new OffScreenWebContentsView( transparent, base::BindRepeating(&WebContents::OnPaint, base::Unretained(this))); params.view = view; params.delegate_view = view; web_contents = content::WebContents::Create(params); view->SetWebContents(web_contents.get()); #endif } else { content::WebContents::CreateParams params(session->browser_context()); params.initially_hidden = !initially_shown; web_contents = content::WebContents::Create(params); } InitWithSessionAndOptions(isolate, std::move(web_contents), session, options); } void WebContents::InitZoomController(content::WebContents* web_contents, const gin_helper::Dictionary& options) { WebContentsZoomController::CreateForWebContents(web_contents); zoom_controller_ = WebContentsZoomController::FromWebContents(web_contents); double zoom_factor; if (options.Get(options::kZoomFactor, &zoom_factor)) zoom_controller_->SetDefaultZoomFactor(zoom_factor); } void WebContents::InitWithSessionAndOptions( v8::Isolate* isolate, std::unique_ptr<content::WebContents> owned_web_contents, gin::Handle<api::Session> session, const gin_helper::Dictionary& options) { Observe(owned_web_contents.get()); InitWithWebContents(std::move(owned_web_contents), session->browser_context(), IsGuest()); inspectable_web_contents_->GetView()->SetDelegate(this); auto* prefs = web_contents()->GetMutableRendererPrefs(); // Collect preferred languages from OS and browser process. accept_languages // effects HTTP header, navigator.languages, and CJK fallback font selection. // // Note that an application locale set to the browser process might be // different with the one set to the preference list. // (e.g. overridden with --lang) std::string accept_languages = g_browser_process->GetApplicationLocale() + ","; for (auto const& language : electron::GetPreferredLanguages()) { if (language == g_browser_process->GetApplicationLocale()) continue; accept_languages += language + ","; } accept_languages.pop_back(); prefs->accept_languages = accept_languages; #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_WIN) // Update font settings. static const gfx::FontRenderParams params( gfx::GetFontRenderParams(gfx::FontRenderParamsQuery(), nullptr)); prefs->should_antialias_text = params.antialiasing; prefs->use_subpixel_positioning = params.subpixel_positioning; prefs->hinting = params.hinting; prefs->use_autohinter = params.autohinter; prefs->use_bitmaps = params.use_bitmaps; prefs->subpixel_rendering = params.subpixel_rendering; #endif // Honor the system's cursor blink rate settings if (auto interval = GetCursorBlinkInterval()) prefs->caret_blink_interval = *interval; // Save the preferences in C++. // If there's already a WebContentsPreferences object, we created it as part // of the webContents.setWindowOpenHandler path, so don't overwrite it. if (!WebContentsPreferences::From(web_contents())) { new WebContentsPreferences(web_contents(), options); } // Trigger re-calculation of webkit prefs. web_contents()->NotifyPreferencesChanged(); WebContentsPermissionHelper::CreateForWebContents(web_contents()); InitZoomController(web_contents(), options); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) extensions::ElectronExtensionWebContentsObserver::CreateForWebContents( web_contents()); script_executor_ = std::make_unique<extensions::ScriptExecutor>(web_contents()); #endif AutofillDriverFactory::CreateForWebContents(web_contents()); web_contents()->SetUserAgentOverride(blink::UserAgentOverride::UserAgentOnly( GetBrowserContext()->GetUserAgent()), false); if (IsGuest()) { NativeWindow* owner_window = nullptr; if (embedder_) { // New WebContents's owner_window is the embedder's owner_window. auto* relay = NativeWindowRelay::FromWebContents(embedder_->web_contents()); if (relay) owner_window = relay->GetNativeWindow(); } if (owner_window) SetOwnerWindow(owner_window); } web_contents()->SetUserData(kElectronApiWebContentsKey, std::make_unique<UserDataLink>(GetWeakPtr())); } #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) void WebContents::InitWithExtensionView(v8::Isolate* isolate, content::WebContents* web_contents, extensions::mojom::ViewType view_type) { // Must reassign type prior to calling `Init`. type_ = GetTypeFromViewType(view_type); if (type_ == Type::kRemote) return; if (type_ == Type::kBackgroundPage) // non-background-page WebContents are retained by other classes. We need // to pin here to prevent background-page WebContents from being GC'd. // The background page api::WebContents will live until the underlying // content::WebContents is destroyed. Pin(isolate); // Allow toggling DevTools for background pages Observe(web_contents); InitWithWebContents(std::unique_ptr<content::WebContents>(web_contents), GetBrowserContext(), IsGuest()); inspectable_web_contents_->GetView()->SetDelegate(this); } #endif void WebContents::InitWithWebContents( std::unique_ptr<content::WebContents> web_contents, ElectronBrowserContext* browser_context, bool is_guest) { browser_context_ = browser_context; web_contents->SetDelegate(this); #if BUILDFLAG(ENABLE_PRINTING) PrintPreviewMessageHandler::CreateForWebContents(web_contents.get()); PrintViewManagerElectron::CreateForWebContents(web_contents.get()); printing::CreateCompositeClientIfNeeded(web_contents.get(), browser_context->GetUserAgent()); #endif #if BUILDFLAG(ENABLE_PDF_VIEWER) pdf::PDFWebContentsHelper::CreateForWebContentsWithClient( web_contents.get(), std::make_unique<ElectronPDFWebContentsHelperClient>()); #endif // Determine whether the WebContents is offscreen. auto* web_preferences = WebContentsPreferences::From(web_contents.get()); offscreen_ = web_preferences && web_preferences->IsOffscreen(); // Create InspectableWebContents. inspectable_web_contents_ = std::make_unique<InspectableWebContents>( std::move(web_contents), browser_context->prefs(), is_guest); inspectable_web_contents_->SetDelegate(this); } WebContents::~WebContents() { // clear out objects that have been granted permissions so that when // WebContents::RenderFrameDeleted is called as a result of WebContents // destruction it doesn't try to clear out a granted_devices_ // on a destructed object. granted_devices_.clear(); if (!inspectable_web_contents_) { WebContentsDestroyed(); return; } inspectable_web_contents_->GetView()->SetDelegate(nullptr); // This event is only for internal use, which is emitted when WebContents is // being destroyed. Emit("will-destroy"); // For guest view based on OOPIF, the WebContents is released by the embedder // frame, and we need to clear the reference to the memory. bool not_owned_by_this = IsGuest() && attached_; #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) // And background pages are owned by extensions::ExtensionHost. if (type_ == Type::kBackgroundPage) not_owned_by_this = true; #endif if (not_owned_by_this) { inspectable_web_contents_->ReleaseWebContents(); WebContentsDestroyed(); } // InspectableWebContents will be automatically destroyed. } void WebContents::DeleteThisIfAlive() { // It is possible that the FirstWeakCallback has been called but the // SecondWeakCallback has not, in this case the garbage collection of // WebContents has already started and we should not |delete this|. // Calling |GetWrapper| can detect this corner case. auto* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); v8::Local<v8::Object> wrapper; if (!GetWrapper(isolate).ToLocal(&wrapper)) return; delete this; } void WebContents::Destroy() { // The content::WebContents should be destroyed asyncronously when possible // as user may choose to destroy WebContents during an event of it. if (Browser::Get()->is_shutting_down() || IsGuest()) { DeleteThisIfAlive(); } else { content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce( [](base::WeakPtr<WebContents> contents) { if (contents) contents->DeleteThisIfAlive(); }, GetWeakPtr())); } } bool WebContents::DidAddMessageToConsole( content::WebContents* source, blink::mojom::ConsoleMessageLevel level, const std::u16string& message, int32_t line_no, const std::u16string& source_id) { return Emit("console-message", static_cast<int32_t>(level), message, line_no, source_id); } void WebContents::OnCreateWindow( const GURL& target_url, const content::Referrer& referrer, const std::string& frame_name, WindowOpenDisposition disposition, const std::string& features, const scoped_refptr<network::ResourceRequestBody>& body) { Emit("-new-window", target_url, frame_name, disposition, features, referrer, body); } void WebContents::WebContentsCreatedWithFullParams( content::WebContents* source_contents, int opener_render_process_id, int opener_render_frame_id, const content::mojom::CreateNewWindowParams& params, content::WebContents* new_contents) { ChildWebContentsTracker::CreateForWebContents(new_contents); auto* tracker = ChildWebContentsTracker::FromWebContents(new_contents); tracker->url = params.target_url; tracker->frame_name = params.frame_name; tracker->referrer = params.referrer.To<content::Referrer>(); tracker->raw_features = params.raw_features; tracker->body = params.body; v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); gin_helper::Dictionary dict; gin::ConvertFromV8(isolate, pending_child_web_preferences_.Get(isolate), &dict); pending_child_web_preferences_.Reset(); // Associate the preferences passed in via `setWindowOpenHandler` with the // content::WebContents that was just created for the child window. These // preferences will be picked up by the RenderWidgetHost via its call to the // delegate's OverrideWebkitPrefs. new WebContentsPreferences(new_contents, dict); } bool WebContents::IsWebContentsCreationOverridden( content::SiteInstance* source_site_instance, content::mojom::WindowContainerType window_container_type, const GURL& opener_url, const content::mojom::CreateNewWindowParams& params) { bool default_prevented = Emit( "-will-add-new-contents", params.target_url, params.frame_name, params.raw_features, params.disposition, *params.referrer, params.body); // If the app prevented the default, redirect to CreateCustomWebContents, // which always returns nullptr, which will result in the window open being // prevented (window.open() will return null in the renderer). return default_prevented; } void WebContents::SetNextChildWebPreferences( const gin_helper::Dictionary preferences) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); // Store these prefs for when Chrome calls WebContentsCreatedWithFullParams // with the new child contents. pending_child_web_preferences_.Reset(isolate, preferences.GetHandle()); } content::WebContents* WebContents::CreateCustomWebContents( content::RenderFrameHost* opener, content::SiteInstance* source_site_instance, bool is_new_browsing_instance, const GURL& opener_url, const std::string& frame_name, const GURL& target_url, const content::StoragePartitionConfig& partition_config, content::SessionStorageNamespace* session_storage_namespace) { return nullptr; } void WebContents::AddNewContents( content::WebContents* source, std::unique_ptr<content::WebContents> new_contents, const GURL& target_url, WindowOpenDisposition disposition, const gfx::Rect& initial_rect, bool user_gesture, bool* was_blocked) { auto* tracker = ChildWebContentsTracker::FromWebContents(new_contents.get()); DCHECK(tracker); v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); auto api_web_contents = CreateAndTake(isolate, std::move(new_contents), Type::kBrowserWindow); // We call RenderFrameCreated here as at this point the empty "about:blank" // render frame has already been created. If the window never navigates again // RenderFrameCreated won't be called and certain prefs like // "kBackgroundColor" will not be applied. auto* frame = api_web_contents->MainFrame(); if (frame) { api_web_contents->HandleNewRenderFrame(frame); } if (Emit("-add-new-contents", api_web_contents, disposition, user_gesture, initial_rect.x(), initial_rect.y(), initial_rect.width(), initial_rect.height(), tracker->url, tracker->frame_name, tracker->referrer, tracker->raw_features, tracker->body)) { api_web_contents->Destroy(); } } content::WebContents* WebContents::OpenURLFromTab( content::WebContents* source, const content::OpenURLParams& params) { auto weak_this = GetWeakPtr(); if (params.disposition != WindowOpenDisposition::CURRENT_TAB) { Emit("-new-window", params.url, "", params.disposition, "", params.referrer, params.post_data); return nullptr; } if (!weak_this || !web_contents()) return nullptr; content::NavigationController::LoadURLParams load_url_params(params.url); load_url_params.referrer = params.referrer; load_url_params.transition_type = params.transition; load_url_params.extra_headers = params.extra_headers; load_url_params.should_replace_current_entry = params.should_replace_current_entry; load_url_params.is_renderer_initiated = params.is_renderer_initiated; load_url_params.started_from_context_menu = params.started_from_context_menu; load_url_params.initiator_origin = params.initiator_origin; load_url_params.source_site_instance = params.source_site_instance; load_url_params.frame_tree_node_id = params.frame_tree_node_id; load_url_params.redirect_chain = params.redirect_chain; load_url_params.has_user_gesture = params.user_gesture; load_url_params.blob_url_loader_factory = params.blob_url_loader_factory; load_url_params.href_translate = params.href_translate; load_url_params.reload_type = params.reload_type; if (params.post_data) { load_url_params.load_type = content::NavigationController::LOAD_TYPE_HTTP_POST; load_url_params.post_data = params.post_data; } source->GetController().LoadURLWithParams(load_url_params); return source; } void WebContents::BeforeUnloadFired(content::WebContents* tab, bool proceed, bool* proceed_to_fire_unload) { if (type_ == Type::kBrowserWindow || type_ == Type::kOffScreen || type_ == Type::kBrowserView) *proceed_to_fire_unload = proceed; else *proceed_to_fire_unload = true; // Note that Chromium does not emit this for navigations. Emit("before-unload-fired", proceed); } void WebContents::SetContentsBounds(content::WebContents* source, const gfx::Rect& rect) { for (ExtendedWebContentsObserver& observer : observers_) observer.OnSetContentBounds(rect); } void WebContents::CloseContents(content::WebContents* source) { Emit("close"); auto* autofill_driver_factory = AutofillDriverFactory::FromWebContents(web_contents()); if (autofill_driver_factory) { autofill_driver_factory->CloseAllPopups(); } for (ExtendedWebContentsObserver& observer : observers_) observer.OnCloseContents(); } void WebContents::ActivateContents(content::WebContents* source) { for (ExtendedWebContentsObserver& observer : observers_) observer.OnActivateContents(); } void WebContents::UpdateTargetURL(content::WebContents* source, const GURL& url) { Emit("update-target-url", url); } bool WebContents::HandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) { if (type_ == Type::kWebView && embedder_) { // Send the unhandled keyboard events back to the embedder. return embedder_->HandleKeyboardEvent(source, event); } else { return PlatformHandleKeyboardEvent(source, event); } } #if !BUILDFLAG(IS_MAC) // NOTE: The macOS version of this function is found in // electron_api_web_contents_mac.mm, as it requires calling into objective-C // code. bool WebContents::PlatformHandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) { // Escape exits tabbed fullscreen mode. if (event.windows_key_code == ui::VKEY_ESCAPE && is_html_fullscreen()) { ExitFullscreenModeForTab(source); return true; } // Check if the webContents has preferences and to ignore shortcuts auto* web_preferences = WebContentsPreferences::From(source); if (web_preferences && web_preferences->ShouldIgnoreMenuShortcuts()) return false; // Let the NativeWindow handle other parts. if (owner_window()) { owner_window()->HandleKeyboardEvent(source, event); return true; } return false; } #endif content::KeyboardEventProcessingResult WebContents::PreHandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) { if (exclusive_access_manager_->HandleUserKeyEvent(event)) return content::KeyboardEventProcessingResult::HANDLED; if (event.GetType() == blink::WebInputEvent::Type::kRawKeyDown || event.GetType() == blink::WebInputEvent::Type::kKeyUp) { bool prevent_default = Emit("before-input-event", event); if (prevent_default) { return content::KeyboardEventProcessingResult::HANDLED; } } return content::KeyboardEventProcessingResult::NOT_HANDLED; } void WebContents::ContentsZoomChange(bool zoom_in) { Emit("zoom-changed", zoom_in ? "in" : "out"); } Profile* WebContents::GetProfile() { return nullptr; } bool WebContents::IsFullscreen() const { return owner_window_ && owner_window_->IsFullscreen(); } void WebContents::EnterFullscreen(const GURL& url, ExclusiveAccessBubbleType bubble_type, const int64_t display_id) {} void WebContents::ExitFullscreen() {} void WebContents::UpdateExclusiveAccessExitBubbleContent( const GURL& url, ExclusiveAccessBubbleType bubble_type, ExclusiveAccessBubbleHideCallback bubble_first_hide_callback, bool force_update) {} void WebContents::OnExclusiveAccessUserInput() {} content::WebContents* WebContents::GetActiveWebContents() { return web_contents(); } bool WebContents::CanUserExitFullscreen() const { return true; } bool WebContents::IsExclusiveAccessBubbleDisplayed() const { return false; } void WebContents::EnterFullscreenModeForTab( content::RenderFrameHost* requesting_frame, const blink::mojom::FullscreenOptions& options) { auto* source = content::WebContents::FromRenderFrameHost(requesting_frame); auto* permission_helper = WebContentsPermissionHelper::FromWebContents(source); auto callback = base::BindRepeating(&WebContents::OnEnterFullscreenModeForTab, base::Unretained(this), requesting_frame, options); permission_helper->RequestFullscreenPermission(callback); exclusive_access_manager_->fullscreen_controller()->EnterFullscreenModeForTab( requesting_frame, options.display_id); } void WebContents::OnEnterFullscreenModeForTab( content::RenderFrameHost* requesting_frame, const blink::mojom::FullscreenOptions& options, bool allowed) { if (!allowed || !owner_window_) return; auto* source = content::WebContents::FromRenderFrameHost(requesting_frame); if (IsFullscreenForTabOrPending(source)) { DCHECK_EQ(fullscreen_frame_, source->GetFocusedFrame()); return; } SetHtmlApiFullscreen(true); if (native_fullscreen_) { // Explicitly trigger a view resize, as the size is not actually changing if // the browser is fullscreened, too. source->GetRenderViewHost()->GetWidget()->SynchronizeVisualProperties(); } } void WebContents::ExitFullscreenModeForTab(content::WebContents* source) { if (!owner_window_) return; // This needs to be called before we exit fullscreen on the native window, // or the controller will incorrectly think we weren't fullscreen and bail. exclusive_access_manager_->fullscreen_controller()->ExitFullscreenModeForTab( source); SetHtmlApiFullscreen(false); if (native_fullscreen_) { // Explicitly trigger a view resize, as the size is not actually changing if // the browser is fullscreened, too. Chrome does this indirectly from // `chrome/browser/ui/exclusive_access/fullscreen_controller.cc`. source->GetRenderViewHost()->GetWidget()->SynchronizeVisualProperties(); } } void WebContents::RendererUnresponsive( content::WebContents* source, content::RenderWidgetHost* render_widget_host, base::RepeatingClosure hang_monitor_restarter) { Emit("unresponsive"); } void WebContents::RendererResponsive( content::WebContents* source, content::RenderWidgetHost* render_widget_host) { Emit("responsive"); } bool WebContents::HandleContextMenu(content::RenderFrameHost& render_frame_host, const content::ContextMenuParams& params) { Emit("context-menu", std::make_pair(params, &render_frame_host)); return true; } bool WebContents::OnGoToEntryOffset(int offset) { GoToOffset(offset); return false; } void WebContents::FindReply(content::WebContents* web_contents, int request_id, int number_of_matches, const gfx::Rect& selection_rect, int active_match_ordinal, bool final_update) { if (!final_update) return; v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); gin_helper::Dictionary result = gin::Dictionary::CreateEmpty(isolate); result.Set("requestId", request_id); result.Set("matches", number_of_matches); result.Set("selectionArea", selection_rect); result.Set("activeMatchOrdinal", active_match_ordinal); result.Set("finalUpdate", final_update); // Deprecate after 2.0 Emit("found-in-page", result.GetHandle()); } void WebContents::RequestExclusivePointerAccess( content::WebContents* web_contents, bool user_gesture, bool last_unlocked_by_target, bool allowed) { if (allowed) { exclusive_access_manager_->mouse_lock_controller()->RequestToLockMouse( web_contents, user_gesture, last_unlocked_by_target); } else { web_contents->GotResponseToLockMouseRequest( blink::mojom::PointerLockResult::kPermissionDenied); } } void WebContents::RequestToLockMouse(content::WebContents* web_contents, bool user_gesture, bool last_unlocked_by_target) { auto* permission_helper = WebContentsPermissionHelper::FromWebContents(web_contents); permission_helper->RequestPointerLockPermission( user_gesture, last_unlocked_by_target, base::BindOnce(&WebContents::RequestExclusivePointerAccess, base::Unretained(this))); } void WebContents::LostMouseLock() { exclusive_access_manager_->mouse_lock_controller()->LostMouseLock(); } void WebContents::RequestKeyboardLock(content::WebContents* web_contents, bool esc_key_locked) { exclusive_access_manager_->keyboard_lock_controller()->RequestKeyboardLock( web_contents, esc_key_locked); } void WebContents::CancelKeyboardLockRequest( content::WebContents* web_contents) { exclusive_access_manager_->keyboard_lock_controller() ->CancelKeyboardLockRequest(web_contents); } bool WebContents::CheckMediaAccessPermission( content::RenderFrameHost* render_frame_host, const GURL& security_origin, blink::mojom::MediaStreamType type) { auto* web_contents = content::WebContents::FromRenderFrameHost(render_frame_host); auto* permission_helper = WebContentsPermissionHelper::FromWebContents(web_contents); return permission_helper->CheckMediaAccessPermission(security_origin, type); } void WebContents::RequestMediaAccessPermission( content::WebContents* web_contents, const content::MediaStreamRequest& request, content::MediaResponseCallback callback) { auto* permission_helper = WebContentsPermissionHelper::FromWebContents(web_contents); permission_helper->RequestMediaAccessPermission(request, std::move(callback)); } content::JavaScriptDialogManager* WebContents::GetJavaScriptDialogManager( content::WebContents* source) { if (!dialog_manager_) dialog_manager_ = std::make_unique<ElectronJavaScriptDialogManager>(); return dialog_manager_.get(); } void WebContents::OnAudioStateChanged(bool audible) { Emit("-audio-state-changed", audible); } void WebContents::BeforeUnloadFired(bool proceed, const base::TimeTicks& proceed_time) { // Do nothing, we override this method just to avoid compilation error since // there are two virtual functions named BeforeUnloadFired. } void WebContents::HandleNewRenderFrame( content::RenderFrameHost* render_frame_host) { auto* rwhv = render_frame_host->GetView(); if (!rwhv) return; // Set the background color of RenderWidgetHostView. auto* web_preferences = WebContentsPreferences::From(web_contents()); if (web_preferences) { absl::optional<SkColor> maybe_color = web_preferences->GetBackgroundColor(); web_contents()->SetPageBaseBackgroundColor(maybe_color); bool guest = IsGuest() || type_ == Type::kBrowserView; SkColor color = maybe_color.value_or(guest ? SK_ColorTRANSPARENT : SK_ColorWHITE); SetBackgroundColor(rwhv, color); } if (!background_throttling_) render_frame_host->GetRenderViewHost()->SetSchedulerThrottling(false); auto* rwh_impl = static_cast<content::RenderWidgetHostImpl*>(rwhv->GetRenderWidgetHost()); if (rwh_impl) rwh_impl->disable_hidden_ = !background_throttling_; auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host); if (web_frame) web_frame->Connect(); } void WebContents::OnBackgroundColorChanged() { absl::optional<SkColor> color = web_contents()->GetBackgroundColor(); if (color.has_value()) { auto* const view = web_contents()->GetRenderWidgetHostView(); static_cast<content::RenderWidgetHostViewBase*>(view) ->SetContentBackgroundColor(color.value()); } } void WebContents::RenderFrameCreated( content::RenderFrameHost* render_frame_host) { HandleNewRenderFrame(render_frame_host); // RenderFrameCreated is called for speculative frames which may not be // used in certain cross-origin navigations. Invoking // RenderFrameHost::GetLifecycleState currently crashes when called for // speculative frames so we need to filter it out for now. Check // https://crbug.com/1183639 for details on when this can be removed. auto* rfh_impl = static_cast<content::RenderFrameHostImpl*>(render_frame_host); if (rfh_impl->lifecycle_state() == content::RenderFrameHostImpl::LifecycleStateImpl::kSpeculative) { return; } content::RenderFrameHost::LifecycleState lifecycle_state = render_frame_host->GetLifecycleState(); if (lifecycle_state == content::RenderFrameHost::LifecycleState::kActive) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); gin_helper::Dictionary details = gin_helper::Dictionary::CreateEmpty(isolate); details.SetGetter("frame", render_frame_host); Emit("frame-created", details); } } void WebContents::RenderFrameDeleted( content::RenderFrameHost* render_frame_host) { // A RenderFrameHost can be deleted when: // - A WebContents is removed and its containing frames are disposed. // - An <iframe> is removed from the DOM. // - Cross-origin navigation creates a new RFH in a separate process which // is swapped by content::RenderFrameHostManager. // // clear out objects that have been granted permissions if (!granted_devices_.empty()) { granted_devices_.erase(render_frame_host->GetFrameTreeNodeId()); } // WebFrameMain::FromRenderFrameHost(rfh) will use the RFH's FrameTreeNode ID // to find an existing instance of WebFrameMain. During a cross-origin // navigation, the deleted RFH will be the old host which was swapped out. In // this special case, we need to also ensure that WebFrameMain's internal RFH // matches before marking it as disposed. auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host); if (web_frame && web_frame->render_frame_host() == render_frame_host) web_frame->MarkRenderFrameDisposed(); } void WebContents::RenderFrameHostChanged(content::RenderFrameHost* old_host, content::RenderFrameHost* new_host) { // During cross-origin navigation, a FrameTreeNode will swap out its RFH. // If an instance of WebFrameMain exists, it will need to have its RFH // swapped as well. // // |old_host| can be a nullptr so we use |new_host| for looking up the // WebFrameMain instance. auto* web_frame = WebFrameMain::FromFrameTreeNodeId(new_host->GetFrameTreeNodeId()); if (web_frame) { web_frame->UpdateRenderFrameHost(new_host); } } void WebContents::FrameDeleted(int frame_tree_node_id) { auto* web_frame = WebFrameMain::FromFrameTreeNodeId(frame_tree_node_id); if (web_frame) web_frame->Destroyed(); } void WebContents::RenderViewDeleted(content::RenderViewHost* render_view_host) { // This event is necessary for tracking any states with respect to // intermediate render view hosts aka speculative render view hosts. Currently // used by object-registry.js to ref count remote objects. Emit("render-view-deleted", render_view_host->GetProcess()->GetID()); if (web_contents()->GetRenderViewHost() == render_view_host) { // When the RVH that has been deleted is the current RVH it means that the // the web contents are being closed. This is communicated by this event. // Currently tracked by guest-window-manager.ts to destroy the // BrowserWindow. Emit("current-render-view-deleted", render_view_host->GetProcess()->GetID()); } } void WebContents::PrimaryMainFrameRenderProcessGone( base::TerminationStatus status) { auto weak_this = GetWeakPtr(); Emit("crashed", status == base::TERMINATION_STATUS_PROCESS_WAS_KILLED); // User might destroy WebContents in the crashed event. if (!weak_this || !web_contents()) return; v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); gin_helper::Dictionary details = gin_helper::Dictionary::CreateEmpty(isolate); details.Set("reason", status); details.Set("exitCode", web_contents()->GetCrashedErrorCode()); Emit("render-process-gone", details); } void WebContents::PluginCrashed(const base::FilePath& plugin_path, base::ProcessId plugin_pid) { #if BUILDFLAG(ENABLE_PLUGINS) content::WebPluginInfo info; auto* plugin_service = content::PluginService::GetInstance(); plugin_service->GetPluginInfoByPath(plugin_path, &info); Emit("plugin-crashed", info.name, info.version); #endif // BUILDFLAG(ENABLE_PLUGINS) } void WebContents::MediaStartedPlaying(const MediaPlayerInfo& video_type, const content::MediaPlayerId& id) { Emit("media-started-playing"); } void WebContents::MediaStoppedPlaying( const MediaPlayerInfo& video_type, const content::MediaPlayerId& id, content::WebContentsObserver::MediaStoppedReason reason) { Emit("media-paused"); } void WebContents::DidChangeThemeColor() { auto theme_color = web_contents()->GetThemeColor(); if (theme_color) { Emit("did-change-theme-color", electron::ToRGBHex(theme_color.value())); } else { Emit("did-change-theme-color", nullptr); } } void WebContents::DidAcquireFullscreen(content::RenderFrameHost* rfh) { set_fullscreen_frame(rfh); } void WebContents::OnWebContentsFocused( content::RenderWidgetHost* render_widget_host) { Emit("focus"); } void WebContents::OnWebContentsLostFocus( content::RenderWidgetHost* render_widget_host) { Emit("blur"); } void WebContents::DOMContentLoaded( content::RenderFrameHost* render_frame_host) { auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host); if (web_frame) web_frame->DOMContentLoaded(); if (!render_frame_host->GetParent()) Emit("dom-ready"); } void WebContents::DidFinishLoad(content::RenderFrameHost* render_frame_host, const GURL& validated_url) { bool is_main_frame = !render_frame_host->GetParent(); int frame_process_id = render_frame_host->GetProcess()->GetID(); int frame_routing_id = render_frame_host->GetRoutingID(); auto weak_this = GetWeakPtr(); Emit("did-frame-finish-load", is_main_frame, frame_process_id, frame_routing_id); // ⚠️WARNING!⚠️ // Emit() triggers JS which can call destroy() on |this|. It's not safe to // assume that |this| points to valid memory at this point. if (is_main_frame && weak_this && web_contents()) Emit("did-finish-load"); } void WebContents::DidFailLoad(content::RenderFrameHost* render_frame_host, const GURL& url, int error_code) { bool is_main_frame = !render_frame_host->GetParent(); int frame_process_id = render_frame_host->GetProcess()->GetID(); int frame_routing_id = render_frame_host->GetRoutingID(); Emit("did-fail-load", error_code, "", url, is_main_frame, frame_process_id, frame_routing_id); } void WebContents::DidStartLoading() { Emit("did-start-loading"); } void WebContents::DidStopLoading() { auto* web_preferences = WebContentsPreferences::From(web_contents()); if (web_preferences && web_preferences->ShouldUsePreferredSizeMode()) web_contents()->GetRenderViewHost()->EnablePreferredSizeMode(); Emit("did-stop-loading"); } bool WebContents::EmitNavigationEvent( const std::string& event, content::NavigationHandle* navigation_handle) { bool is_main_frame = navigation_handle->IsInMainFrame(); int frame_tree_node_id = navigation_handle->GetFrameTreeNodeId(); content::FrameTreeNode* frame_tree_node = content::FrameTreeNode::GloballyFindByID(frame_tree_node_id); content::RenderFrameHostManager* render_manager = frame_tree_node->render_manager(); content::RenderFrameHost* frame_host = nullptr; if (render_manager) { frame_host = render_manager->speculative_frame_host(); if (!frame_host) frame_host = render_manager->current_frame_host(); } int frame_process_id = -1, frame_routing_id = -1; if (frame_host) { frame_process_id = frame_host->GetProcess()->GetID(); frame_routing_id = frame_host->GetRoutingID(); } bool is_same_document = navigation_handle->IsSameDocument(); auto url = navigation_handle->GetURL(); return Emit(event, url, is_same_document, is_main_frame, frame_process_id, frame_routing_id); } void WebContents::Message(bool internal, const std::string& channel, blink::CloneableMessage arguments, content::RenderFrameHost* render_frame_host) { TRACE_EVENT1("electron", "WebContents::Message", "channel", channel); // webContents.emit('-ipc-message', new Event(), internal, channel, // arguments); EmitWithSender("-ipc-message", render_frame_host, electron::mojom::ElectronApiIPC::InvokeCallback(), internal, channel, std::move(arguments)); } void WebContents::Invoke( bool internal, const std::string& channel, blink::CloneableMessage arguments, electron::mojom::ElectronApiIPC::InvokeCallback callback, content::RenderFrameHost* render_frame_host) { TRACE_EVENT1("electron", "WebContents::Invoke", "channel", channel); // webContents.emit('-ipc-invoke', new Event(), internal, channel, arguments); EmitWithSender("-ipc-invoke", render_frame_host, std::move(callback), internal, channel, std::move(arguments)); } void WebContents::OnFirstNonEmptyLayout( content::RenderFrameHost* render_frame_host) { if (render_frame_host == web_contents()->GetMainFrame()) { Emit("ready-to-show"); } } void WebContents::ReceivePostMessage( const std::string& channel, blink::TransferableMessage message, content::RenderFrameHost* render_frame_host) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); auto wrapped_ports = MessagePort::EntanglePorts(isolate, std::move(message.ports)); v8::Local<v8::Value> message_value = electron::DeserializeV8Value(isolate, message); EmitWithSender("-ipc-ports", render_frame_host, electron::mojom::ElectronApiIPC::InvokeCallback(), false, channel, message_value, std::move(wrapped_ports)); } void WebContents::MessageSync( bool internal, const std::string& channel, blink::CloneableMessage arguments, electron::mojom::ElectronApiIPC::MessageSyncCallback callback, content::RenderFrameHost* render_frame_host) { TRACE_EVENT1("electron", "WebContents::MessageSync", "channel", channel); // webContents.emit('-ipc-message-sync', new Event(sender, message), internal, // channel, arguments); EmitWithSender("-ipc-message-sync", render_frame_host, std::move(callback), internal, channel, std::move(arguments)); } void WebContents::MessageTo(int32_t web_contents_id, const std::string& channel, blink::CloneableMessage arguments) { TRACE_EVENT1("electron", "WebContents::MessageTo", "channel", channel); auto* target_web_contents = FromID(web_contents_id); if (target_web_contents) { content::RenderFrameHost* frame = target_web_contents->MainFrame(); DCHECK(frame); v8::HandleScope handle_scope(JavascriptEnvironment::GetIsolate()); gin::Handle<WebFrameMain> web_frame_main = WebFrameMain::From(JavascriptEnvironment::GetIsolate(), frame); if (!web_frame_main->CheckRenderFrame()) return; int32_t sender_id = ID(); web_frame_main->GetRendererApi()->Message(false /* internal */, channel, std::move(arguments), sender_id); } } void WebContents::MessageHost(const std::string& channel, blink::CloneableMessage arguments, content::RenderFrameHost* render_frame_host) { TRACE_EVENT1("electron", "WebContents::MessageHost", "channel", channel); // webContents.emit('ipc-message-host', new Event(), channel, args); EmitWithSender("ipc-message-host", render_frame_host, electron::mojom::ElectronApiIPC::InvokeCallback(), channel, std::move(arguments)); } void WebContents::UpdateDraggableRegions( std::vector<mojom::DraggableRegionPtr> regions) { for (ExtendedWebContentsObserver& observer : observers_) observer.OnDraggableRegionsUpdated(regions); } void WebContents::DidStartNavigation( content::NavigationHandle* navigation_handle) { EmitNavigationEvent("did-start-navigation", navigation_handle); } void WebContents::DidRedirectNavigation( content::NavigationHandle* navigation_handle) { EmitNavigationEvent("did-redirect-navigation", navigation_handle); } void WebContents::ReadyToCommitNavigation( content::NavigationHandle* navigation_handle) { // Don't focus content in an inactive window. if (!owner_window()) return; #if BUILDFLAG(IS_MAC) if (!owner_window()->IsActive()) return; #else if (!owner_window()->widget()->IsActive()) return; #endif // Don't focus content after subframe navigations. if (!navigation_handle->IsInMainFrame()) return; // Only focus for top-level contents. if (type_ != Type::kBrowserWindow) return; web_contents()->SetInitialFocus(); } void WebContents::DidFinishNavigation( content::NavigationHandle* navigation_handle) { if (owner_window_) { owner_window_->NotifyLayoutWindowControlsOverlay(); } if (!navigation_handle->HasCommitted()) return; bool is_main_frame = navigation_handle->IsInMainFrame(); content::RenderFrameHost* frame_host = navigation_handle->GetRenderFrameHost(); int frame_process_id = -1, frame_routing_id = -1; if (frame_host) { frame_process_id = frame_host->GetProcess()->GetID(); frame_routing_id = frame_host->GetRoutingID(); } if (!navigation_handle->IsErrorPage()) { // FIXME: All the Emit() calls below could potentially result in |this| // being destroyed (by JS listening for the event and calling // webContents.destroy()). auto url = navigation_handle->GetURL(); bool is_same_document = navigation_handle->IsSameDocument(); if (is_same_document) { Emit("did-navigate-in-page", url, is_main_frame, frame_process_id, frame_routing_id); } else { const net::HttpResponseHeaders* http_response = navigation_handle->GetResponseHeaders(); std::string http_status_text; int http_response_code = -1; if (http_response) { http_status_text = http_response->GetStatusText(); http_response_code = http_response->response_code(); } Emit("did-frame-navigate", url, http_response_code, http_status_text, is_main_frame, frame_process_id, frame_routing_id); if (is_main_frame) { Emit("did-navigate", url, http_response_code, http_status_text); } } if (IsGuest()) Emit("load-commit", url, is_main_frame); } else { auto url = navigation_handle->GetURL(); int code = navigation_handle->GetNetErrorCode(); auto description = net::ErrorToShortString(code); Emit("did-fail-provisional-load", code, description, url, is_main_frame, frame_process_id, frame_routing_id); // Do not emit "did-fail-load" for canceled requests. if (code != net::ERR_ABORTED) { EmitWarning( node::Environment::GetCurrent(JavascriptEnvironment::GetIsolate()), "Failed to load URL: " + url.possibly_invalid_spec() + " with error: " + description, "electron"); Emit("did-fail-load", code, description, url, is_main_frame, frame_process_id, frame_routing_id); } } content::NavigationEntry* entry = navigation_handle->GetNavigationEntry(); // This check is needed due to an issue in Chromium // Check the Chromium issue to keep updated: // https://bugs.chromium.org/p/chromium/issues/detail?id=1178663 // If a history entry has been made and the forward/back call has been made, // proceed with setting the new title if (entry && (entry->GetTransitionType() & ui::PAGE_TRANSITION_FORWARD_BACK)) WebContents::TitleWasSet(entry); } void WebContents::TitleWasSet(content::NavigationEntry* entry) { std::u16string final_title; bool explicit_set = true; if (entry) { auto title = entry->GetTitle(); auto url = entry->GetURL(); if (url.SchemeIsFile() && title.empty()) { final_title = base::UTF8ToUTF16(url.ExtractFileName()); explicit_set = false; } else { final_title = title; } } else { final_title = web_contents()->GetTitle(); } for (ExtendedWebContentsObserver& observer : observers_) observer.OnPageTitleUpdated(final_title, explicit_set); Emit("page-title-updated", final_title, explicit_set); } void WebContents::DidUpdateFaviconURL( content::RenderFrameHost* render_frame_host, const std::vector<blink::mojom::FaviconURLPtr>& urls) { std::set<GURL> unique_urls; for (const auto& iter : urls) { if (iter->icon_type != blink::mojom::FaviconIconType::kFavicon) continue; const GURL& url = iter->icon_url; if (url.is_valid()) unique_urls.insert(url); } Emit("page-favicon-updated", unique_urls); } void WebContents::DevToolsReloadPage() { Emit("devtools-reload-page"); } void WebContents::DevToolsFocused() { Emit("devtools-focused"); } void WebContents::DevToolsOpened() { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); DCHECK(inspectable_web_contents_); DCHECK(inspectable_web_contents_->GetDevToolsWebContents()); auto handle = FromOrCreate( isolate, inspectable_web_contents_->GetDevToolsWebContents()); devtools_web_contents_.Reset(isolate, handle.ToV8()); // Set inspected tabID. base::Value tab_id(ID()); inspectable_web_contents_->CallClientFunction("DevToolsAPI.setInspectedTabId", &tab_id, nullptr, nullptr); // Inherit owner window in devtools when it doesn't have one. auto* devtools = inspectable_web_contents_->GetDevToolsWebContents(); bool has_window = devtools->GetUserData(NativeWindowRelay::UserDataKey()); if (owner_window() && !has_window) handle->SetOwnerWindow(devtools, owner_window()); Emit("devtools-opened"); } void WebContents::DevToolsClosed() { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); devtools_web_contents_.Reset(); Emit("devtools-closed"); } void WebContents::DevToolsResized() { for (ExtendedWebContentsObserver& observer : observers_) observer.OnDevToolsResized(); } void WebContents::SetOwnerWindow(NativeWindow* owner_window) { SetOwnerWindow(GetWebContents(), owner_window); } void WebContents::SetOwnerWindow(content::WebContents* web_contents, NativeWindow* owner_window) { if (owner_window) { owner_window_ = owner_window->GetWeakPtr(); NativeWindowRelay::CreateForWebContents(web_contents, owner_window->GetWeakPtr()); } else { owner_window_ = nullptr; web_contents->RemoveUserData(NativeWindowRelay::UserDataKey()); } #if BUILDFLAG(ENABLE_OSR) auto* osr_wcv = GetOffScreenWebContentsView(); if (osr_wcv) osr_wcv->SetNativeWindow(owner_window); #endif } content::WebContents* WebContents::GetWebContents() const { if (!inspectable_web_contents_) return nullptr; return inspectable_web_contents_->GetWebContents(); } content::WebContents* WebContents::GetDevToolsWebContents() const { if (!inspectable_web_contents_) return nullptr; return inspectable_web_contents_->GetDevToolsWebContents(); } void WebContents::WebContentsDestroyed() { // Clear the pointer stored in wrapper. if (GetAllWebContents().Lookup(id_)) GetAllWebContents().Remove(id_); v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); v8::Local<v8::Object> wrapper; if (!GetWrapper(isolate).ToLocal(&wrapper)) return; wrapper->SetAlignedPointerInInternalField(0, nullptr); // Tell WebViewGuestDelegate that the WebContents has been destroyed. if (guest_delegate_) guest_delegate_->WillDestroy(); Observe(nullptr); Emit("destroyed"); } void WebContents::NavigationEntryCommitted( const content::LoadCommittedDetails& details) { Emit("navigation-entry-committed", details.entry->GetURL(), details.is_same_document, details.did_replace_entry); } bool WebContents::GetBackgroundThrottling() const { return background_throttling_; } void WebContents::SetBackgroundThrottling(bool allowed) { background_throttling_ = allowed; auto* rfh = web_contents()->GetMainFrame(); if (!rfh) return; auto* rwhv = rfh->GetView(); if (!rwhv) return; auto* rwh_impl = static_cast<content::RenderWidgetHostImpl*>(rwhv->GetRenderWidgetHost()); if (!rwh_impl) return; rwh_impl->disable_hidden_ = !background_throttling_; web_contents()->GetRenderViewHost()->SetSchedulerThrottling(allowed); if (rwh_impl->is_hidden()) { rwh_impl->WasShown({}); } } int WebContents::GetProcessID() const { return web_contents()->GetMainFrame()->GetProcess()->GetID(); } base::ProcessId WebContents::GetOSProcessID() const { base::ProcessHandle process_handle = web_contents()->GetMainFrame()->GetProcess()->GetProcess().Handle(); return base::GetProcId(process_handle); } WebContents::Type WebContents::GetType() const { return type_; } bool WebContents::Equal(const WebContents* web_contents) const { return ID() == web_contents->ID(); } GURL WebContents::GetURL() const { return web_contents()->GetLastCommittedURL(); } void WebContents::LoadURL(const GURL& url, const gin_helper::Dictionary& options) { if (!url.is_valid() || url.spec().size() > url::kMaxURLChars) { Emit("did-fail-load", static_cast<int>(net::ERR_INVALID_URL), net::ErrorToShortString(net::ERR_INVALID_URL), url.possibly_invalid_spec(), true); return; } content::NavigationController::LoadURLParams params(url); if (!options.Get("httpReferrer", &params.referrer)) { GURL http_referrer; if (options.Get("httpReferrer", &http_referrer)) params.referrer = content::Referrer(http_referrer.GetAsReferrer(), network::mojom::ReferrerPolicy::kDefault); } std::string user_agent; if (options.Get("userAgent", &user_agent)) web_contents()->SetUserAgentOverride( blink::UserAgentOverride::UserAgentOnly(user_agent), false); std::string extra_headers; if (options.Get("extraHeaders", &extra_headers)) params.extra_headers = extra_headers; scoped_refptr<network::ResourceRequestBody> body; if (options.Get("postData", &body)) { params.post_data = body; params.load_type = content::NavigationController::LOAD_TYPE_HTTP_POST; } GURL base_url_for_data_url; if (options.Get("baseURLForDataURL", &base_url_for_data_url)) { params.base_url_for_data_url = base_url_for_data_url; params.load_type = content::NavigationController::LOAD_TYPE_DATA; } bool reload_ignoring_cache = false; if (options.Get("reloadIgnoringCache", &reload_ignoring_cache) && reload_ignoring_cache) { params.reload_type = content::ReloadType::BYPASSING_CACHE; } // Calling LoadURLWithParams() can trigger JS which destroys |this|. auto weak_this = GetWeakPtr(); params.transition_type = ui::PageTransitionFromInt( ui::PAGE_TRANSITION_TYPED | ui::PAGE_TRANSITION_FROM_ADDRESS_BAR); params.override_user_agent = content::NavigationController::UA_OVERRIDE_TRUE; // Discord non-committed entries to ensure that we don't re-use a pending // entry web_contents()->GetController().DiscardNonCommittedEntries(); web_contents()->GetController().LoadURLWithParams(params); // ⚠️WARNING!⚠️ // LoadURLWithParams() triggers JS events which can call destroy() on |this|. // It's not safe to assume that |this| points to valid memory at this point. if (!weak_this || !web_contents()) return; // Required to make beforeunload handler work. NotifyUserActivation(); } // TODO(MarshallOfSound): Figure out what we need to do with post data here, I // believe the default behavior when we pass "true" is to phone out to the // delegate and then the controller expects this method to be called again with // "false" if the user approves the reload. For now this would result in // ".reload()" calls on POST data domains failing silently. Passing false would // result in them succeeding, but reposting which although more correct could be // considering a breaking change. void WebContents::Reload() { web_contents()->GetController().Reload(content::ReloadType::NORMAL, /* check_for_repost */ true); } void WebContents::ReloadIgnoringCache() { web_contents()->GetController().Reload(content::ReloadType::BYPASSING_CACHE, /* check_for_repost */ true); } void WebContents::DownloadURL(const GURL& url) { auto* browser_context = web_contents()->GetBrowserContext(); auto* download_manager = browser_context->GetDownloadManager(); std::unique_ptr<download::DownloadUrlParameters> download_params( content::DownloadRequestUtils::CreateDownloadForWebContentsMainFrame( web_contents(), url, MISSING_TRAFFIC_ANNOTATION)); download_manager->DownloadUrl(std::move(download_params)); } std::u16string WebContents::GetTitle() const { return web_contents()->GetTitle(); } bool WebContents::IsLoading() const { return web_contents()->IsLoading(); } bool WebContents::IsLoadingMainFrame() const { return web_contents()->ShouldShowLoadingUI(); } bool WebContents::IsWaitingForResponse() const { return web_contents()->IsWaitingForResponse(); } void WebContents::Stop() { web_contents()->Stop(); } bool WebContents::CanGoBack() const { return web_contents()->GetController().CanGoBack(); } void WebContents::GoBack() { if (CanGoBack()) web_contents()->GetController().GoBack(); } bool WebContents::CanGoForward() const { return web_contents()->GetController().CanGoForward(); } void WebContents::GoForward() { if (CanGoForward()) web_contents()->GetController().GoForward(); } bool WebContents::CanGoToOffset(int offset) const { return web_contents()->GetController().CanGoToOffset(offset); } void WebContents::GoToOffset(int offset) { if (CanGoToOffset(offset)) web_contents()->GetController().GoToOffset(offset); } bool WebContents::CanGoToIndex(int index) const { return index >= 0 && index < GetHistoryLength(); } void WebContents::GoToIndex(int index) { if (CanGoToIndex(index)) web_contents()->GetController().GoToIndex(index); } int WebContents::GetActiveIndex() const { return web_contents()->GetController().GetCurrentEntryIndex(); } void WebContents::ClearHistory() { // In some rare cases (normally while there is no real history) we are in a // state where we can't prune navigation entries if (web_contents()->GetController().CanPruneAllButLastCommitted()) { web_contents()->GetController().PruneAllButLastCommitted(); } } int WebContents::GetHistoryLength() const { return web_contents()->GetController().GetEntryCount(); } const std::string WebContents::GetWebRTCIPHandlingPolicy() const { return web_contents()->GetMutableRendererPrefs()->webrtc_ip_handling_policy; } void WebContents::SetWebRTCIPHandlingPolicy( const std::string& webrtc_ip_handling_policy) { if (GetWebRTCIPHandlingPolicy() == webrtc_ip_handling_policy) return; web_contents()->GetMutableRendererPrefs()->webrtc_ip_handling_policy = webrtc_ip_handling_policy; web_contents()->SyncRendererPrefs(); } std::string WebContents::GetMediaSourceID( content::WebContents* request_web_contents) { auto* frame_host = web_contents()->GetMainFrame(); if (!frame_host) return std::string(); content::DesktopMediaID media_id( content::DesktopMediaID::TYPE_WEB_CONTENTS, content::DesktopMediaID::kNullId, content::WebContentsMediaCaptureId(frame_host->GetProcess()->GetID(), frame_host->GetRoutingID())); auto* request_frame_host = request_web_contents->GetMainFrame(); if (!request_frame_host) return std::string(); std::string id = content::DesktopStreamsRegistry::GetInstance()->RegisterStream( request_frame_host->GetProcess()->GetID(), request_frame_host->GetRoutingID(), url::Origin::Create(request_frame_host->GetLastCommittedURL() .DeprecatedGetOriginAsURL()), media_id, "", content::kRegistryStreamTypeTab); return id; } bool WebContents::IsCrashed() const { return web_contents()->IsCrashed(); } void WebContents::ForcefullyCrashRenderer() { content::RenderWidgetHostView* view = web_contents()->GetRenderWidgetHostView(); if (!view) return; content::RenderWidgetHost* rwh = view->GetRenderWidgetHost(); if (!rwh) return; content::RenderProcessHost* rph = rwh->GetProcess(); if (rph) { #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) // A generic |CrashDumpHungChildProcess()| is not implemented for Linux. // Instead we send an explicit IPC to crash on the renderer's IO thread. rph->ForceCrash(); #else // Try to generate a crash report for the hung process. #ifndef MAS_BUILD CrashDumpHungChildProcess(rph->GetProcess().Handle()); #endif rph->Shutdown(content::RESULT_CODE_HUNG); #endif } } void WebContents::SetUserAgent(const std::string& user_agent) { web_contents()->SetUserAgentOverride( blink::UserAgentOverride::UserAgentOnly(user_agent), false); } std::string WebContents::GetUserAgent() { return web_contents()->GetUserAgentOverride().ua_string_override; } v8::Local<v8::Promise> WebContents::SavePage( const base::FilePath& full_file_path, const content::SavePageType& save_type) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); gin_helper::Promise<void> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); if (!full_file_path.IsAbsolute()) { promise.RejectWithErrorMessage("Path must be absolute"); return handle; } auto* handler = new SavePageHandler(web_contents(), std::move(promise)); handler->Handle(full_file_path, save_type); return handle; } void WebContents::OpenDevTools(gin::Arguments* args) { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; std::string state; if (type_ == Type::kWebView || type_ == Type::kBackgroundPage || !owner_window()) { state = "detach"; } bool activate = true; if (args && args->Length() == 1) { gin_helper::Dictionary options; if (args->GetNext(&options)) { options.Get("mode", &state); options.Get("activate", &activate); } } DCHECK(inspectable_web_contents_); inspectable_web_contents_->SetDockState(state); inspectable_web_contents_->ShowDevTools(activate); } void WebContents::CloseDevTools() { if (type_ == Type::kRemote) return; DCHECK(inspectable_web_contents_); inspectable_web_contents_->CloseDevTools(); } bool WebContents::IsDevToolsOpened() { if (type_ == Type::kRemote) return false; DCHECK(inspectable_web_contents_); return inspectable_web_contents_->IsDevToolsViewShowing(); } bool WebContents::IsDevToolsFocused() { if (type_ == Type::kRemote) return false; DCHECK(inspectable_web_contents_); return inspectable_web_contents_->GetView()->IsDevToolsViewFocused(); } void WebContents::EnableDeviceEmulation( const blink::DeviceEmulationParams& params) { if (type_ == Type::kRemote) return; DCHECK(web_contents()); auto* frame_host = web_contents()->GetMainFrame(); if (frame_host) { auto* widget_host_impl = static_cast<content::RenderWidgetHostImpl*>( frame_host->GetView()->GetRenderWidgetHost()); if (widget_host_impl) { auto& frame_widget = widget_host_impl->GetAssociatedFrameWidget(); frame_widget->EnableDeviceEmulation(params); } } } void WebContents::DisableDeviceEmulation() { if (type_ == Type::kRemote) return; DCHECK(web_contents()); auto* frame_host = web_contents()->GetMainFrame(); if (frame_host) { auto* widget_host_impl = static_cast<content::RenderWidgetHostImpl*>( frame_host->GetView()->GetRenderWidgetHost()); if (widget_host_impl) { auto& frame_widget = widget_host_impl->GetAssociatedFrameWidget(); frame_widget->DisableDeviceEmulation(); } } } void WebContents::ToggleDevTools() { if (IsDevToolsOpened()) CloseDevTools(); else OpenDevTools(nullptr); } void WebContents::InspectElement(int x, int y) { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; DCHECK(inspectable_web_contents_); if (!inspectable_web_contents_->GetDevToolsWebContents()) OpenDevTools(nullptr); inspectable_web_contents_->InspectElement(x, y); } void WebContents::InspectSharedWorkerById(const std::string& workerId) { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) { if (agent_host->GetType() == content::DevToolsAgentHost::kTypeSharedWorker) { if (agent_host->GetId() == workerId) { OpenDevTools(nullptr); inspectable_web_contents_->AttachTo(agent_host); break; } } } } std::vector<scoped_refptr<content::DevToolsAgentHost>> WebContents::GetAllSharedWorkers() { std::vector<scoped_refptr<content::DevToolsAgentHost>> shared_workers; if (type_ == Type::kRemote) return shared_workers; if (!enable_devtools_) return shared_workers; for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) { if (agent_host->GetType() == content::DevToolsAgentHost::kTypeSharedWorker) { shared_workers.push_back(agent_host); } } return shared_workers; } void WebContents::InspectSharedWorker() { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) { if (agent_host->GetType() == content::DevToolsAgentHost::kTypeSharedWorker) { OpenDevTools(nullptr); inspectable_web_contents_->AttachTo(agent_host); break; } } } void WebContents::InspectServiceWorker() { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) { if (agent_host->GetType() == content::DevToolsAgentHost::kTypeServiceWorker) { OpenDevTools(nullptr); inspectable_web_contents_->AttachTo(agent_host); break; } } } void WebContents::SetIgnoreMenuShortcuts(bool ignore) { auto* web_preferences = WebContentsPreferences::From(web_contents()); DCHECK(web_preferences); web_preferences->SetIgnoreMenuShortcuts(ignore); } void WebContents::SetAudioMuted(bool muted) { web_contents()->SetAudioMuted(muted); } bool WebContents::IsAudioMuted() { return web_contents()->IsAudioMuted(); } bool WebContents::IsCurrentlyAudible() { return web_contents()->IsCurrentlyAudible(); } #if BUILDFLAG(ENABLE_PRINTING) void WebContents::OnGetDefaultPrinter( base::Value::Dict print_settings, printing::CompletionCallback print_callback, std::u16string device_name, bool silent, // <error, default_printer> std::pair<std::string, std::u16string> info) { // The content::WebContents might be already deleted at this point, and the // PrintViewManagerElectron class does not do null check. if (!web_contents()) { if (print_callback) std::move(print_callback).Run(false, "failed"); return; } if (!info.first.empty()) { if (print_callback) std::move(print_callback).Run(false, info.first); return; } // If the user has passed a deviceName use it, otherwise use default printer. std::u16string printer_name = device_name.empty() ? info.second : device_name; // If there are no valid printers available on the network, we bail. if (printer_name.empty() || !IsDeviceNameValid(printer_name)) { if (print_callback) std::move(print_callback).Run(false, "no valid printers available"); return; } print_settings.Set(printing::kSettingDeviceName, printer_name); auto* print_view_manager = PrintViewManagerElectron::FromWebContents(web_contents()); if (!print_view_manager) return; auto* focused_frame = web_contents()->GetFocusedFrame(); auto* rfh = focused_frame && focused_frame->HasSelection() ? focused_frame : web_contents()->GetMainFrame(); print_view_manager->PrintNow(rfh, silent, std::move(print_settings), std::move(print_callback)); } void WebContents::Print(gin::Arguments* args) { gin_helper::Dictionary options = gin::Dictionary::CreateEmpty(args->isolate()); base::Value::Dict settings; if (args->Length() >= 1 && !args->GetNext(&options)) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("webContents.print(): Invalid print settings specified."); return; } printing::CompletionCallback callback; if (args->Length() == 2 && !args->GetNext(&callback)) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("webContents.print(): Invalid optional callback provided."); return; } // Set optional silent printing bool silent = false; options.Get("silent", &silent); bool print_background = false; options.Get("printBackground", &print_background); settings.Set(printing::kSettingShouldPrintBackgrounds, print_background); // Set custom margin settings gin_helper::Dictionary margins = gin::Dictionary::CreateEmpty(args->isolate()); if (options.Get("margins", &margins)) { printing::mojom::MarginType margin_type = printing::mojom::MarginType::kDefaultMargins; margins.Get("marginType", &margin_type); settings.Set(printing::kSettingMarginsType, static_cast<int>(margin_type)); if (margin_type == printing::mojom::MarginType::kCustomMargins) { base::Value::Dict custom_margins; int top = 0; margins.Get("top", &top); custom_margins.Set(printing::kSettingMarginTop, top); int bottom = 0; margins.Get("bottom", &bottom); custom_margins.Set(printing::kSettingMarginBottom, bottom); int left = 0; margins.Get("left", &left); custom_margins.Set(printing::kSettingMarginLeft, left); int right = 0; margins.Get("right", &right); custom_margins.Set(printing::kSettingMarginRight, right); settings.Set(printing::kSettingMarginsCustom, std::move(custom_margins)); } } else { settings.Set( printing::kSettingMarginsType, static_cast<int>(printing::mojom::MarginType::kDefaultMargins)); } // Set whether to print color or greyscale bool print_color = true; options.Get("color", &print_color); auto const color_model = print_color ? printing::mojom::ColorModel::kColor : printing::mojom::ColorModel::kGray; settings.Set(printing::kSettingColor, static_cast<int>(color_model)); // Is the orientation landscape or portrait. bool landscape = false; options.Get("landscape", &landscape); settings.Set(printing::kSettingLandscape, landscape); // We set the default to the system's default printer and only update // if at the Chromium level if the user overrides. // Printer device name as opened by the OS. std::u16string device_name; options.Get("deviceName", &device_name); if (!device_name.empty() && !IsDeviceNameValid(device_name)) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("webContents.print(): Invalid deviceName provided."); return; } int scale_factor = 100; options.Get("scaleFactor", &scale_factor); settings.Set(printing::kSettingScaleFactor, scale_factor); int pages_per_sheet = 1; options.Get("pagesPerSheet", &pages_per_sheet); settings.Set(printing::kSettingPagesPerSheet, pages_per_sheet); // True if the user wants to print with collate. bool collate = true; options.Get("collate", &collate); settings.Set(printing::kSettingCollate, collate); // The number of individual copies to print int copies = 1; options.Get("copies", &copies); settings.Set(printing::kSettingCopies, copies); // Strings to be printed as headers and footers if requested by the user. std::string header; options.Get("header", &header); std::string footer; options.Get("footer", &footer); if (!(header.empty() && footer.empty())) { settings.Set(printing::kSettingHeaderFooterEnabled, true); settings.Set(printing::kSettingHeaderFooterTitle, header); settings.Set(printing::kSettingHeaderFooterURL, footer); } else { settings.Set(printing::kSettingHeaderFooterEnabled, false); } // We don't want to allow the user to enable these settings // but we need to set them or a CHECK is hit. settings.Set(printing::kSettingPrinterType, static_cast<int>(printing::mojom::PrinterType::kLocal)); settings.Set(printing::kSettingShouldPrintSelectionOnly, false); settings.Set(printing::kSettingRasterizePdf, false); // Set custom page ranges to print std::vector<gin_helper::Dictionary> page_ranges; if (options.Get("pageRanges", &page_ranges)) { base::Value::List page_range_list; for (auto& range : page_ranges) { int from, to; if (range.Get("from", &from) && range.Get("to", &to)) { base::Value::Dict range; // Chromium uses 1-based page ranges, so increment each by 1. range.Set(printing::kSettingPageRangeFrom, from + 1); range.Set(printing::kSettingPageRangeTo, to + 1); page_range_list.Append(std::move(range)); } else { continue; } } if (!page_range_list.empty()) settings.Set(printing::kSettingPageRange, std::move(page_range_list)); } // Duplex type user wants to use. printing::mojom::DuplexMode duplex_mode = printing::mojom::DuplexMode::kSimplex; options.Get("duplexMode", &duplex_mode); settings.Set(printing::kSettingDuplexMode, static_cast<int>(duplex_mode)); // We've already done necessary parameter sanitization at the // JS level, so we can simply pass this through. base::Value media_size(base::Value::Type::DICTIONARY); if (options.Get("mediaSize", &media_size)) settings.Set(printing::kSettingMediaSize, std::move(media_size)); // Set custom dots per inch (dpi) gin_helper::Dictionary dpi_settings; int dpi = 72; if (options.Get("dpi", &dpi_settings)) { int horizontal = 72; dpi_settings.Get("horizontal", &horizontal); settings.Set(printing::kSettingDpiHorizontal, horizontal); int vertical = 72; dpi_settings.Get("vertical", &vertical); settings.Set(printing::kSettingDpiVertical, vertical); } else { settings.Set(printing::kSettingDpiHorizontal, dpi); settings.Set(printing::kSettingDpiVertical, dpi); } print_task_runner_->PostTaskAndReplyWithResult( FROM_HERE, base::BindOnce(&GetDefaultPrinterAsync), base::BindOnce(&WebContents::OnGetDefaultPrinter, weak_factory_.GetWeakPtr(), std::move(settings), std::move(callback), device_name, silent)); } v8::Local<v8::Promise> WebContents::PrintToPDF(base::DictionaryValue settings) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); gin_helper::Promise<v8::Local<v8::Value>> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); PrintPreviewMessageHandler::FromWebContents(web_contents()) ->PrintToPDF(std::move(settings), std::move(promise)); return handle; } #endif void WebContents::AddWorkSpace(gin::Arguments* args, const base::FilePath& path) { if (path.empty()) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("path cannot be empty"); return; } DevToolsAddFileSystem(std::string(), path); } void WebContents::RemoveWorkSpace(gin::Arguments* args, const base::FilePath& path) { if (path.empty()) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("path cannot be empty"); return; } DevToolsRemoveFileSystem(path); } void WebContents::Undo() { web_contents()->Undo(); } void WebContents::Redo() { web_contents()->Redo(); } void WebContents::Cut() { web_contents()->Cut(); } void WebContents::Copy() { web_contents()->Copy(); } void WebContents::Paste() { web_contents()->Paste(); } void WebContents::PasteAndMatchStyle() { web_contents()->PasteAndMatchStyle(); } void WebContents::Delete() { web_contents()->Delete(); } void WebContents::SelectAll() { web_contents()->SelectAll(); } void WebContents::Unselect() { web_contents()->CollapseSelection(); } void WebContents::Replace(const std::u16string& word) { web_contents()->Replace(word); } void WebContents::ReplaceMisspelling(const std::u16string& word) { web_contents()->ReplaceMisspelling(word); } uint32_t WebContents::FindInPage(gin::Arguments* args) { std::u16string search_text; if (!args->GetNext(&search_text) || search_text.empty()) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("Must provide a non-empty search content"); return 0; } uint32_t request_id = ++find_in_page_request_id_; gin_helper::Dictionary dict; auto options = blink::mojom::FindOptions::New(); if (args->GetNext(&dict)) { dict.Get("forward", &options->forward); dict.Get("matchCase", &options->match_case); dict.Get("findNext", &options->new_session); } web_contents()->Find(request_id, search_text, std::move(options)); return request_id; } void WebContents::StopFindInPage(content::StopFindAction action) { web_contents()->StopFinding(action); } void WebContents::ShowDefinitionForSelection() { #if BUILDFLAG(IS_MAC) auto* const view = web_contents()->GetRenderWidgetHostView(); if (view) view->ShowDefinitionForSelection(); #endif } void WebContents::CopyImageAt(int x, int y) { auto* const host = web_contents()->GetMainFrame(); if (host) host->CopyImageAt(x, y); } void WebContents::Focus() { // Focusing on WebContents does not automatically focus the window on macOS // and Linux, do it manually to match the behavior on Windows. #if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX) if (owner_window()) owner_window()->Focus(true); #endif web_contents()->Focus(); } #if !BUILDFLAG(IS_MAC) bool WebContents::IsFocused() const { auto* view = web_contents()->GetRenderWidgetHostView(); if (!view) return false; if (GetType() != Type::kBackgroundPage) { auto* window = web_contents()->GetNativeView()->GetToplevelWindow(); if (window && !window->IsVisible()) return false; } return view->HasFocus(); } #endif void WebContents::SendInputEvent(v8::Isolate* isolate, v8::Local<v8::Value> input_event) { content::RenderWidgetHostView* view = web_contents()->GetRenderWidgetHostView(); if (!view) return; content::RenderWidgetHost* rwh = view->GetRenderWidgetHost(); blink::WebInputEvent::Type type = gin::GetWebInputEventType(isolate, input_event); if (blink::WebInputEvent::IsMouseEventType(type)) { blink::WebMouseEvent mouse_event; if (gin::ConvertFromV8(isolate, input_event, &mouse_event)) { if (IsOffScreen()) { #if BUILDFLAG(ENABLE_OSR) GetOffScreenRenderWidgetHostView()->SendMouseEvent(mouse_event); #endif } else { rwh->ForwardMouseEvent(mouse_event); } return; } } else if (blink::WebInputEvent::IsKeyboardEventType(type)) { content::NativeWebKeyboardEvent keyboard_event( blink::WebKeyboardEvent::Type::kRawKeyDown, blink::WebInputEvent::Modifiers::kNoModifiers, ui::EventTimeForNow()); if (gin::ConvertFromV8(isolate, input_event, &keyboard_event)) { rwh->ForwardKeyboardEvent(keyboard_event); return; } } else if (type == blink::WebInputEvent::Type::kMouseWheel) { blink::WebMouseWheelEvent mouse_wheel_event; if (gin::ConvertFromV8(isolate, input_event, &mouse_wheel_event)) { if (IsOffScreen()) { #if BUILDFLAG(ENABLE_OSR) GetOffScreenRenderWidgetHostView()->SendMouseWheelEvent( mouse_wheel_event); #endif } else { // Chromium expects phase info in wheel events (and applies a // DCHECK to verify it). See: https://crbug.com/756524. mouse_wheel_event.phase = blink::WebMouseWheelEvent::kPhaseBegan; mouse_wheel_event.dispatch_type = blink::WebInputEvent::DispatchType::kBlocking; rwh->ForwardWheelEvent(mouse_wheel_event); // Send a synthetic wheel event with phaseEnded to finish scrolling. mouse_wheel_event.has_synthetic_phase = true; mouse_wheel_event.delta_x = 0; mouse_wheel_event.delta_y = 0; mouse_wheel_event.phase = blink::WebMouseWheelEvent::kPhaseEnded; mouse_wheel_event.dispatch_type = blink::WebInputEvent::DispatchType::kEventNonBlocking; rwh->ForwardWheelEvent(mouse_wheel_event); } return; } } isolate->ThrowException( v8::Exception::Error(gin::StringToV8(isolate, "Invalid event object"))); } void WebContents::BeginFrameSubscription(gin::Arguments* args) { bool only_dirty = false; FrameSubscriber::FrameCaptureCallback callback; if (args->Length() > 1) { if (!args->GetNext(&only_dirty)) { args->ThrowError(); return; } } if (!args->GetNext(&callback)) { args->ThrowError(); return; } frame_subscriber_ = std::make_unique<FrameSubscriber>(web_contents(), callback, only_dirty); } void WebContents::EndFrameSubscription() { frame_subscriber_.reset(); } void WebContents::StartDrag(const gin_helper::Dictionary& item, gin::Arguments* args) { base::FilePath file; std::vector<base::FilePath> files; if (!item.Get("files", &files) && item.Get("file", &file)) { files.push_back(file); } v8::Local<v8::Value> icon_value; if (!item.Get("icon", &icon_value)) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("'icon' parameter is required"); return; } NativeImage* icon = nullptr; if (!NativeImage::TryConvertNativeImage(args->isolate(), icon_value, &icon) || icon->image().IsEmpty()) { return; } // Start dragging. if (!files.empty()) { base::CurrentThread::ScopedNestableTaskAllower allow; DragFileItems(files, icon->image(), web_contents()->GetNativeView()); } else { gin_helper::ErrorThrower(args->isolate()) .ThrowError("Must specify either 'file' or 'files' option"); } } v8::Local<v8::Promise> WebContents::CapturePage(gin::Arguments* args) { gfx::Rect rect; gin_helper::Promise<gfx::Image> promise(args->isolate()); v8::Local<v8::Promise> handle = promise.GetHandle(); // get rect arguments if they exist args->GetNext(&rect); auto* const view = web_contents()->GetRenderWidgetHostView(); if (!view) { promise.Resolve(gfx::Image()); return handle; } #if !BUILDFLAG(IS_MAC) // If the view's renderer is suspended this may fail on Windows/Linux - // bail if so. See CopyFromSurface in // content/public/browser/render_widget_host_view.h. auto* rfh = web_contents()->GetMainFrame(); if (rfh && rfh->GetVisibilityState() == blink::mojom::PageVisibilityState::kHidden) { promise.Resolve(gfx::Image()); return handle; } #endif // BUILDFLAG(IS_MAC) // Capture full page if user doesn't specify a |rect|. const gfx::Size view_size = rect.IsEmpty() ? view->GetViewBounds().size() : rect.size(); // By default, the requested bitmap size is the view size in screen // coordinates. However, if there's more pixel detail available on the // current system, increase the requested bitmap size to capture it all. gfx::Size bitmap_size = view_size; const gfx::NativeView native_view = view->GetNativeView(); const float scale = display::Screen::GetScreen() ->GetDisplayNearestView(native_view) .device_scale_factor(); if (scale > 1.0f) bitmap_size = gfx::ScaleToCeiledSize(view_size, scale); view->CopyFromSurface(gfx::Rect(rect.origin(), view_size), bitmap_size, base::BindOnce(&OnCapturePageDone, std::move(promise))); return handle; } void WebContents::IncrementCapturerCount(gin::Arguments* args) { gfx::Size size; bool stay_hidden = false; bool stay_awake = false; // get size arguments if they exist args->GetNext(&size); // get stayHidden arguments if they exist args->GetNext(&stay_hidden); // get stayAwake arguments if they exist args->GetNext(&stay_awake); std::ignore = web_contents() ->IncrementCapturerCount(size, stay_hidden, stay_awake) .Release(); } void WebContents::DecrementCapturerCount(gin::Arguments* args) { bool stay_hidden = false; bool stay_awake = false; // get stayHidden arguments if they exist args->GetNext(&stay_hidden); // get stayAwake arguments if they exist args->GetNext(&stay_awake); web_contents()->DecrementCapturerCount(stay_hidden, stay_awake); } bool WebContents::IsBeingCaptured() { return web_contents()->IsBeingCaptured(); } void WebContents::OnCursorChanged(const content::WebCursor& webcursor) { const ui::Cursor& cursor = webcursor.cursor(); if (cursor.type() == ui::mojom::CursorType::kCustom) { Emit("cursor-changed", CursorTypeToString(cursor), gfx::Image::CreateFrom1xBitmap(cursor.custom_bitmap()), cursor.image_scale_factor(), gfx::Size(cursor.custom_bitmap().width(), cursor.custom_bitmap().height()), cursor.custom_hotspot()); } else { Emit("cursor-changed", CursorTypeToString(cursor)); } } bool WebContents::IsGuest() const { return type_ == Type::kWebView; } void WebContents::AttachToIframe(content::WebContents* embedder_web_contents, int embedder_frame_id) { attached_ = true; if (guest_delegate_) guest_delegate_->AttachToIframe(embedder_web_contents, embedder_frame_id); } bool WebContents::IsOffScreen() const { #if BUILDFLAG(ENABLE_OSR) return type_ == Type::kOffScreen; #else return false; #endif } #if BUILDFLAG(ENABLE_OSR) void WebContents::OnPaint(const gfx::Rect& dirty_rect, const SkBitmap& bitmap) { Emit("paint", dirty_rect, gfx::Image::CreateFrom1xBitmap(bitmap)); } void WebContents::StartPainting() { auto* osr_wcv = GetOffScreenWebContentsView(); if (osr_wcv) osr_wcv->SetPainting(true); } void WebContents::StopPainting() { auto* osr_wcv = GetOffScreenWebContentsView(); if (osr_wcv) osr_wcv->SetPainting(false); } bool WebContents::IsPainting() const { auto* osr_wcv = GetOffScreenWebContentsView(); return osr_wcv && osr_wcv->IsPainting(); } void WebContents::SetFrameRate(int frame_rate) { auto* osr_wcv = GetOffScreenWebContentsView(); if (osr_wcv) osr_wcv->SetFrameRate(frame_rate); } int WebContents::GetFrameRate() const { auto* osr_wcv = GetOffScreenWebContentsView(); return osr_wcv ? osr_wcv->GetFrameRate() : 0; } #endif void WebContents::Invalidate() { if (IsOffScreen()) { #if BUILDFLAG(ENABLE_OSR) auto* osr_rwhv = GetOffScreenRenderWidgetHostView(); if (osr_rwhv) osr_rwhv->Invalidate(); #endif } else { auto* const window = owner_window(); if (window) window->Invalidate(); } } gfx::Size WebContents::GetSizeForNewRenderView(content::WebContents* wc) { if (IsOffScreen() && wc == web_contents()) { auto* relay = NativeWindowRelay::FromWebContents(web_contents()); if (relay) { auto* owner_window = relay->GetNativeWindow(); return owner_window ? owner_window->GetSize() : gfx::Size(); } } return gfx::Size(); } void WebContents::SetZoomLevel(double level) { zoom_controller_->SetZoomLevel(level); } double WebContents::GetZoomLevel() const { return zoom_controller_->GetZoomLevel(); } void WebContents::SetZoomFactor(gin_helper::ErrorThrower thrower, double factor) { if (factor < std::numeric_limits<double>::epsilon()) { thrower.ThrowError("'zoomFactor' must be a double greater than 0.0"); return; } auto level = blink::PageZoomFactorToZoomLevel(factor); SetZoomLevel(level); } double WebContents::GetZoomFactor() const { auto level = GetZoomLevel(); return blink::PageZoomLevelToZoomFactor(level); } void WebContents::SetTemporaryZoomLevel(double level) { zoom_controller_->SetTemporaryZoomLevel(level); } void WebContents::DoGetZoomLevel( electron::mojom::ElectronWebContentsUtility::DoGetZoomLevelCallback callback) { std::move(callback).Run(GetZoomLevel()); } std::vector<base::FilePath> WebContents::GetPreloadPaths() const { auto result = SessionPreferences::GetValidPreloads(GetBrowserContext()); if (auto* web_preferences = WebContentsPreferences::From(web_contents())) { base::FilePath preload; if (web_preferences->GetPreloadPath(&preload)) { result.emplace_back(preload); } } return result; } v8::Local<v8::Value> WebContents::GetLastWebPreferences( v8::Isolate* isolate) const { auto* web_preferences = WebContentsPreferences::From(web_contents()); if (!web_preferences) return v8::Null(isolate); return gin::ConvertToV8(isolate, *web_preferences->last_preference()); } v8::Local<v8::Value> WebContents::GetOwnerBrowserWindow( v8::Isolate* isolate) const { if (owner_window()) return BrowserWindow::From(isolate, owner_window()); else return v8::Null(isolate); } v8::Local<v8::Value> WebContents::Session(v8::Isolate* isolate) { return v8::Local<v8::Value>::New(isolate, session_); } content::WebContents* WebContents::HostWebContents() const { if (!embedder_) return nullptr; return embedder_->web_contents(); } void WebContents::SetEmbedder(const WebContents* embedder) { if (embedder) { NativeWindow* owner_window = nullptr; auto* relay = NativeWindowRelay::FromWebContents(embedder->web_contents()); if (relay) { owner_window = relay->GetNativeWindow(); } if (owner_window) SetOwnerWindow(owner_window); content::RenderWidgetHostView* rwhv = web_contents()->GetRenderWidgetHostView(); if (rwhv) { rwhv->Hide(); rwhv->Show(); } } } void WebContents::SetDevToolsWebContents(const WebContents* devtools) { if (inspectable_web_contents_) inspectable_web_contents_->SetDevToolsWebContents(devtools->web_contents()); } v8::Local<v8::Value> WebContents::GetNativeView(v8::Isolate* isolate) const { gfx::NativeView ptr = web_contents()->GetNativeView(); auto buffer = node::Buffer::Copy(isolate, reinterpret_cast<char*>(&ptr), sizeof(gfx::NativeView)); if (buffer.IsEmpty()) return v8::Null(isolate); else return buffer.ToLocalChecked(); } v8::Local<v8::Value> WebContents::DevToolsWebContents(v8::Isolate* isolate) { if (devtools_web_contents_.IsEmpty()) return v8::Null(isolate); else return v8::Local<v8::Value>::New(isolate, devtools_web_contents_); } v8::Local<v8::Value> WebContents::Debugger(v8::Isolate* isolate) { if (debugger_.IsEmpty()) { auto handle = electron::api::Debugger::Create(isolate, web_contents()); debugger_.Reset(isolate, handle.ToV8()); } return v8::Local<v8::Value>::New(isolate, debugger_); } content::RenderFrameHost* WebContents::MainFrame() { return web_contents()->GetMainFrame(); } void WebContents::NotifyUserActivation() { content::RenderFrameHost* frame = web_contents()->GetMainFrame(); if (frame) frame->NotifyUserActivation( blink::mojom::UserActivationNotificationType::kInteraction); } void WebContents::SetImageAnimationPolicy(const std::string& new_policy) { auto* web_preferences = WebContentsPreferences::From(web_contents()); web_preferences->SetImageAnimationPolicy(new_policy); web_contents()->OnWebPreferencesChanged(); } v8::Local<v8::Promise> WebContents::GetProcessMemoryInfo(v8::Isolate* isolate) { gin_helper::Promise<gin_helper::Dictionary> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); auto* frame_host = web_contents()->GetMainFrame(); if (!frame_host) { promise.RejectWithErrorMessage("Failed to create memory dump"); return handle; } auto pid = frame_host->GetProcess()->GetProcess().Pid(); v8::Global<v8::Context> context(isolate, isolate->GetCurrentContext()); memory_instrumentation::MemoryInstrumentation::GetInstance() ->RequestGlobalDumpForPid( pid, std::vector<std::string>(), base::BindOnce(&ElectronBindings::DidReceiveMemoryDump, std::move(context), std::move(promise), pid)); return handle; } v8::Local<v8::Promise> WebContents::TakeHeapSnapshot( v8::Isolate* isolate, const base::FilePath& file_path) { gin_helper::Promise<void> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); base::ThreadRestrictions::ScopedAllowIO allow_io; base::File file(file_path, base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE); if (!file.IsValid()) { promise.RejectWithErrorMessage("takeHeapSnapshot failed"); return handle; } auto* frame_host = web_contents()->GetMainFrame(); if (!frame_host) { promise.RejectWithErrorMessage("takeHeapSnapshot failed"); return handle; } if (!frame_host->IsRenderFrameCreated()) { promise.RejectWithErrorMessage("takeHeapSnapshot failed"); return handle; } // This dance with `base::Owned` is to ensure that the interface stays alive // until the callback is called. Otherwise it would be closed at the end of // this function. auto electron_renderer = std::make_unique<mojo::Remote<mojom::ElectronRenderer>>(); frame_host->GetRemoteInterfaces()->GetInterface( electron_renderer->BindNewPipeAndPassReceiver()); auto* raw_ptr = electron_renderer.get(); (*raw_ptr)->TakeHeapSnapshot( mojo::WrapPlatformFile(base::ScopedPlatformFile(file.TakePlatformFile())), base::BindOnce( [](mojo::Remote<mojom::ElectronRenderer>* ep, gin_helper::Promise<void> promise, bool success) { if (success) { promise.Resolve(); } else { promise.RejectWithErrorMessage("takeHeapSnapshot failed"); } }, base::Owned(std::move(electron_renderer)), std::move(promise))); return handle; } void WebContents::GrantDevicePermission( const url::Origin& origin, const base::Value* device, blink::PermissionType permissionType, content::RenderFrameHost* render_frame_host) { granted_devices_[render_frame_host->GetFrameTreeNodeId()][permissionType] [origin] .push_back( std::make_unique<base::Value>(device->Clone())); } std::vector<base::Value> WebContents::GetGrantedDevices( const url::Origin& origin, blink::PermissionType permissionType, content::RenderFrameHost* render_frame_host) { const auto& devices_for_frame_host_it = granted_devices_.find(render_frame_host->GetFrameTreeNodeId()); if (devices_for_frame_host_it == granted_devices_.end()) return {}; const auto& current_devices_it = devices_for_frame_host_it->second.find(permissionType); if (current_devices_it == devices_for_frame_host_it->second.end()) return {}; const auto& origin_devices_it = current_devices_it->second.find(origin); if (origin_devices_it == current_devices_it->second.end()) return {}; std::vector<base::Value> results; for (const auto& object : origin_devices_it->second) results.push_back(object->Clone()); return results; } void WebContents::UpdatePreferredSize(content::WebContents* web_contents, const gfx::Size& pref_size) { Emit("preferred-size-changed", pref_size); } bool WebContents::CanOverscrollContent() { return false; } std::unique_ptr<content::EyeDropper> WebContents::OpenEyeDropper( content::RenderFrameHost* frame, content::EyeDropperListener* listener) { return ShowEyeDropper(frame, listener); } void WebContents::RunFileChooser( content::RenderFrameHost* render_frame_host, scoped_refptr<content::FileSelectListener> listener, const blink::mojom::FileChooserParams& params) { FileSelectHelper::RunFileChooser(render_frame_host, std::move(listener), params); } void WebContents::EnumerateDirectory( content::WebContents* web_contents, scoped_refptr<content::FileSelectListener> listener, const base::FilePath& path) { FileSelectHelper::EnumerateDirectory(web_contents, std::move(listener), path); } bool WebContents::IsFullscreenForTabOrPending( const content::WebContents* source) { return html_fullscreen_; } bool WebContents::TakeFocus(content::WebContents* source, bool reverse) { if (source && source->GetOutermostWebContents() == source) { // If this is the outermost web contents and the user has tabbed or // shift + tabbed through all the elements, reset the focus back to // the first or last element so that it doesn't stay in the body. source->FocusThroughTabTraversal(reverse); return true; } return false; } content::PictureInPictureResult WebContents::EnterPictureInPicture( content::WebContents* web_contents) { #if BUILDFLAG(ENABLE_PICTURE_IN_PICTURE) return PictureInPictureWindowManager::GetInstance() ->EnterVideoPictureInPicture(web_contents); #else return content::PictureInPictureResult::kNotSupported; #endif } void WebContents::ExitPictureInPicture() { #if BUILDFLAG(ENABLE_PICTURE_IN_PICTURE) PictureInPictureWindowManager::GetInstance()->ExitPictureInPicture(); #endif } void WebContents::DevToolsSaveToFile(const std::string& url, const std::string& content, bool save_as) { base::FilePath path; auto it = saved_files_.find(url); if (it != saved_files_.end() && !save_as) { path = it->second; } else { file_dialog::DialogSettings settings; settings.parent_window = owner_window(); settings.force_detached = offscreen_; settings.title = url; settings.default_path = base::FilePath::FromUTF8Unsafe(url); if (!file_dialog::ShowSaveDialogSync(settings, &path)) { base::Value url_value(url); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.canceledSaveURL", &url_value, nullptr, nullptr); return; } } saved_files_[url] = path; // Notify DevTools. base::Value url_value(url); base::Value file_system_path_value(path.AsUTF8Unsafe()); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.savedURL", &url_value, &file_system_path_value, nullptr); file_task_runner_->PostTask(FROM_HERE, base::BindOnce(&WriteToFile, path, content)); } void WebContents::DevToolsAppendToFile(const std::string& url, const std::string& content) { auto it = saved_files_.find(url); if (it == saved_files_.end()) return; // Notify DevTools. base::Value url_value(url); inspectable_web_contents_->CallClientFunction("DevToolsAPI.appendedToURL", &url_value, nullptr, nullptr); file_task_runner_->PostTask( FROM_HERE, base::BindOnce(&AppendToFile, it->second, content)); } void WebContents::DevToolsRequestFileSystems() { auto file_system_paths = GetAddedFileSystemPaths(GetDevToolsWebContents()); if (file_system_paths.empty()) { base::ListValue empty_file_system_value; inspectable_web_contents_->CallClientFunction( "DevToolsAPI.fileSystemsLoaded", &empty_file_system_value, nullptr, nullptr); return; } std::vector<FileSystem> file_systems; for (const auto& file_system_path : file_system_paths) { base::FilePath path = base::FilePath::FromUTF8Unsafe(file_system_path.first); std::string file_system_id = RegisterFileSystem(GetDevToolsWebContents(), path); FileSystem file_system = CreateFileSystemStruct(GetDevToolsWebContents(), file_system_id, file_system_path.first, file_system_path.second); file_systems.push_back(file_system); } base::ListValue file_system_value; for (const auto& file_system : file_systems) file_system_value.Append(CreateFileSystemValue(file_system)); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.fileSystemsLoaded", &file_system_value, nullptr, nullptr); } void WebContents::DevToolsAddFileSystem( const std::string& type, const base::FilePath& file_system_path) { base::FilePath path = file_system_path; if (path.empty()) { std::vector<base::FilePath> paths; file_dialog::DialogSettings settings; settings.parent_window = owner_window(); settings.force_detached = offscreen_; settings.properties = file_dialog::OPEN_DIALOG_OPEN_DIRECTORY; if (!file_dialog::ShowOpenDialogSync(settings, &paths)) return; path = paths[0]; } std::string file_system_id = RegisterFileSystem(GetDevToolsWebContents(), path); if (IsDevToolsFileSystemAdded(GetDevToolsWebContents(), path.AsUTF8Unsafe())) return; FileSystem file_system = CreateFileSystemStruct( GetDevToolsWebContents(), file_system_id, path.AsUTF8Unsafe(), type); std::unique_ptr<base::DictionaryValue> file_system_value( CreateFileSystemValue(file_system)); auto* pref_service = GetPrefService(GetDevToolsWebContents()); DictionaryPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths); update.Get()->SetKey(path.AsUTF8Unsafe(), base::Value(type)); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.fileSystemAdded", nullptr, file_system_value.get(), nullptr); } void WebContents::DevToolsRemoveFileSystem( const base::FilePath& file_system_path) { if (!inspectable_web_contents_) return; std::string path = file_system_path.AsUTF8Unsafe(); storage::IsolatedContext::GetInstance()->RevokeFileSystemByPath( file_system_path); auto* pref_service = GetPrefService(GetDevToolsWebContents()); DictionaryPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths); update.Get()->RemoveKey(path); base::Value file_system_path_value(path); inspectable_web_contents_->CallClientFunction("DevToolsAPI.fileSystemRemoved", &file_system_path_value, nullptr, nullptr); } void WebContents::DevToolsIndexPath( int request_id, const std::string& file_system_path, const std::string& excluded_folders_message) { if (!IsDevToolsFileSystemAdded(GetDevToolsWebContents(), file_system_path)) { OnDevToolsIndexingDone(request_id, file_system_path); return; } if (devtools_indexing_jobs_.count(request_id) != 0) return; std::vector<std::string> excluded_folders; std::unique_ptr<base::Value> parsed_excluded_folders = base::JSONReader::ReadDeprecated(excluded_folders_message); if (parsed_excluded_folders && parsed_excluded_folders->is_list()) { for (const base::Value& folder_path : parsed_excluded_folders->GetListDeprecated()) { if (folder_path.is_string()) excluded_folders.push_back(folder_path.GetString()); } } devtools_indexing_jobs_[request_id] = scoped_refptr<DevToolsFileSystemIndexer::FileSystemIndexingJob>( devtools_file_system_indexer_->IndexPath( file_system_path, excluded_folders, base::BindRepeating( &WebContents::OnDevToolsIndexingWorkCalculated, weak_factory_.GetWeakPtr(), request_id, file_system_path), base::BindRepeating(&WebContents::OnDevToolsIndexingWorked, weak_factory_.GetWeakPtr(), request_id, file_system_path), base::BindRepeating(&WebContents::OnDevToolsIndexingDone, weak_factory_.GetWeakPtr(), request_id, file_system_path))); } void WebContents::DevToolsStopIndexing(int request_id) { auto it = devtools_indexing_jobs_.find(request_id); if (it == devtools_indexing_jobs_.end()) return; it->second->Stop(); devtools_indexing_jobs_.erase(it); } void WebContents::DevToolsSearchInPath(int request_id, const std::string& file_system_path, const std::string& query) { if (!IsDevToolsFileSystemAdded(GetDevToolsWebContents(), file_system_path)) { OnDevToolsSearchCompleted(request_id, file_system_path, std::vector<std::string>()); return; } devtools_file_system_indexer_->SearchInPath( file_system_path, query, base::BindRepeating(&WebContents::OnDevToolsSearchCompleted, weak_factory_.GetWeakPtr(), request_id, file_system_path)); } void WebContents::DevToolsSetEyeDropperActive(bool active) { auto* web_contents = GetWebContents(); if (!web_contents) return; if (active) { eye_dropper_ = std::make_unique<DevToolsEyeDropper>( web_contents, base::BindRepeating(&WebContents::ColorPickedInEyeDropper, base::Unretained(this))); } else { eye_dropper_.reset(); } } void WebContents::ColorPickedInEyeDropper(int r, int g, int b, int a) { base::DictionaryValue color; color.SetInteger("r", r); color.SetInteger("g", g); color.SetInteger("b", b); color.SetInteger("a", a); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.eyeDropperPickedColor", &color, nullptr, nullptr); } #if defined(TOOLKIT_VIEWS) && !BUILDFLAG(IS_MAC) ui::ImageModel WebContents::GetDevToolsWindowIcon() { return owner_window() ? owner_window()->GetWindowAppIcon() : ui::ImageModel{}; } #endif #if BUILDFLAG(IS_LINUX) void WebContents::GetDevToolsWindowWMClass(std::string* name, std::string* class_name) { *class_name = Browser::Get()->GetName(); *name = base::ToLowerASCII(*class_name); } #endif void WebContents::OnDevToolsIndexingWorkCalculated( int request_id, const std::string& file_system_path, int total_work) { base::Value request_id_value(request_id); base::Value file_system_path_value(file_system_path); base::Value total_work_value(total_work); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.indexingTotalWorkCalculated", &request_id_value, &file_system_path_value, &total_work_value); } void WebContents::OnDevToolsIndexingWorked(int request_id, const std::string& file_system_path, int worked) { base::Value request_id_value(request_id); base::Value file_system_path_value(file_system_path); base::Value worked_value(worked); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.indexingWorked", &request_id_value, &file_system_path_value, &worked_value); } void WebContents::OnDevToolsIndexingDone(int request_id, const std::string& file_system_path) { devtools_indexing_jobs_.erase(request_id); base::Value request_id_value(request_id); base::Value file_system_path_value(file_system_path); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.indexingDone", &request_id_value, &file_system_path_value, nullptr); } void WebContents::OnDevToolsSearchCompleted( int request_id, const std::string& file_system_path, const std::vector<std::string>& file_paths) { base::ListValue file_paths_value; for (const auto& file_path : file_paths) { file_paths_value.Append(file_path); } base::Value request_id_value(request_id); base::Value file_system_path_value(file_system_path); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.searchCompleted", &request_id_value, &file_system_path_value, &file_paths_value); } void WebContents::SetHtmlApiFullscreen(bool enter_fullscreen) { // Window is already in fullscreen mode, save the state. if (enter_fullscreen && owner_window_->IsFullscreen()) { native_fullscreen_ = true; UpdateHtmlApiFullscreen(true); return; } // Exit html fullscreen state but not window's fullscreen mode. if (!enter_fullscreen && native_fullscreen_) { UpdateHtmlApiFullscreen(false); return; } // Set fullscreen on window if allowed. auto* web_preferences = WebContentsPreferences::From(GetWebContents()); bool html_fullscreenable = web_preferences ? !web_preferences->ShouldDisableHtmlFullscreenWindowResize() : true; if (html_fullscreenable) { owner_window_->SetFullScreen(enter_fullscreen); } UpdateHtmlApiFullscreen(enter_fullscreen); native_fullscreen_ = false; } void WebContents::UpdateHtmlApiFullscreen(bool fullscreen) { if (fullscreen == is_html_fullscreen()) return; html_fullscreen_ = fullscreen; // Notify renderer of the html fullscreen change. web_contents() ->GetRenderViewHost() ->GetWidget() ->SynchronizeVisualProperties(); // The embedder WebContents is separated from the frame tree of webview, so // we must manually sync their fullscreen states. if (embedder_) embedder_->SetHtmlApiFullscreen(fullscreen); if (fullscreen) { Emit("enter-html-full-screen"); owner_window_->NotifyWindowEnterHtmlFullScreen(); } else { Emit("leave-html-full-screen"); owner_window_->NotifyWindowLeaveHtmlFullScreen(); } // Make sure all child webviews quit html fullscreen. if (!fullscreen && !IsGuest()) { auto* manager = WebViewManager::GetWebViewManager(web_contents()); manager->ForEachGuest( web_contents(), base::BindRepeating([](content::WebContents* guest) { WebContents* api_web_contents = WebContents::From(guest); api_web_contents->SetHtmlApiFullscreen(false); return false; })); } } // static v8::Local<v8::ObjectTemplate> WebContents::FillObjectTemplate( v8::Isolate* isolate, v8::Local<v8::ObjectTemplate> templ) { gin::InvokerOptions options; options.holder_is_first_argument = true; options.holder_type = "WebContents"; templ->Set( gin::StringToSymbol(isolate, "isDestroyed"), gin::CreateFunctionTemplate( isolate, base::BindRepeating(&gin_helper::Destroyable::IsDestroyed), options)); // We use gin_helper::ObjectTemplateBuilder instead of // gin::ObjectTemplateBuilder here to handle the fact that WebContents is // destroyable. return gin_helper::ObjectTemplateBuilder(isolate, templ) .SetMethod("destroy", &WebContents::Destroy) .SetMethod("getBackgroundThrottling", &WebContents::GetBackgroundThrottling) .SetMethod("setBackgroundThrottling", &WebContents::SetBackgroundThrottling) .SetMethod("getProcessId", &WebContents::GetProcessID) .SetMethod("getOSProcessId", &WebContents::GetOSProcessID) .SetMethod("equal", &WebContents::Equal) .SetMethod("_loadURL", &WebContents::LoadURL) .SetMethod("reload", &WebContents::Reload) .SetMethod("reloadIgnoringCache", &WebContents::ReloadIgnoringCache) .SetMethod("downloadURL", &WebContents::DownloadURL) .SetMethod("getURL", &WebContents::GetURL) .SetMethod("getTitle", &WebContents::GetTitle) .SetMethod("isLoading", &WebContents::IsLoading) .SetMethod("isLoadingMainFrame", &WebContents::IsLoadingMainFrame) .SetMethod("isWaitingForResponse", &WebContents::IsWaitingForResponse) .SetMethod("stop", &WebContents::Stop) .SetMethod("canGoBack", &WebContents::CanGoBack) .SetMethod("goBack", &WebContents::GoBack) .SetMethod("canGoForward", &WebContents::CanGoForward) .SetMethod("goForward", &WebContents::GoForward) .SetMethod("canGoToOffset", &WebContents::CanGoToOffset) .SetMethod("goToOffset", &WebContents::GoToOffset) .SetMethod("canGoToIndex", &WebContents::CanGoToIndex) .SetMethod("goToIndex", &WebContents::GoToIndex) .SetMethod("getActiveIndex", &WebContents::GetActiveIndex) .SetMethod("clearHistory", &WebContents::ClearHistory) .SetMethod("length", &WebContents::GetHistoryLength) .SetMethod("isCrashed", &WebContents::IsCrashed) .SetMethod("forcefullyCrashRenderer", &WebContents::ForcefullyCrashRenderer) .SetMethod("setUserAgent", &WebContents::SetUserAgent) .SetMethod("getUserAgent", &WebContents::GetUserAgent) .SetMethod("savePage", &WebContents::SavePage) .SetMethod("openDevTools", &WebContents::OpenDevTools) .SetMethod("closeDevTools", &WebContents::CloseDevTools) .SetMethod("isDevToolsOpened", &WebContents::IsDevToolsOpened) .SetMethod("isDevToolsFocused", &WebContents::IsDevToolsFocused) .SetMethod("enableDeviceEmulation", &WebContents::EnableDeviceEmulation) .SetMethod("disableDeviceEmulation", &WebContents::DisableDeviceEmulation) .SetMethod("toggleDevTools", &WebContents::ToggleDevTools) .SetMethod("inspectElement", &WebContents::InspectElement) .SetMethod("setIgnoreMenuShortcuts", &WebContents::SetIgnoreMenuShortcuts) .SetMethod("setAudioMuted", &WebContents::SetAudioMuted) .SetMethod("isAudioMuted", &WebContents::IsAudioMuted) .SetMethod("isCurrentlyAudible", &WebContents::IsCurrentlyAudible) .SetMethod("undo", &WebContents::Undo) .SetMethod("redo", &WebContents::Redo) .SetMethod("cut", &WebContents::Cut) .SetMethod("copy", &WebContents::Copy) .SetMethod("paste", &WebContents::Paste) .SetMethod("pasteAndMatchStyle", &WebContents::PasteAndMatchStyle) .SetMethod("delete", &WebContents::Delete) .SetMethod("selectAll", &WebContents::SelectAll) .SetMethod("unselect", &WebContents::Unselect) .SetMethod("replace", &WebContents::Replace) .SetMethod("replaceMisspelling", &WebContents::ReplaceMisspelling) .SetMethod("findInPage", &WebContents::FindInPage) .SetMethod("stopFindInPage", &WebContents::StopFindInPage) .SetMethod("focus", &WebContents::Focus) .SetMethod("isFocused", &WebContents::IsFocused) .SetMethod("sendInputEvent", &WebContents::SendInputEvent) .SetMethod("beginFrameSubscription", &WebContents::BeginFrameSubscription) .SetMethod("endFrameSubscription", &WebContents::EndFrameSubscription) .SetMethod("startDrag", &WebContents::StartDrag) .SetMethod("attachToIframe", &WebContents::AttachToIframe) .SetMethod("detachFromOuterFrame", &WebContents::DetachFromOuterFrame) .SetMethod("isOffscreen", &WebContents::IsOffScreen) #if BUILDFLAG(ENABLE_OSR) .SetMethod("startPainting", &WebContents::StartPainting) .SetMethod("stopPainting", &WebContents::StopPainting) .SetMethod("isPainting", &WebContents::IsPainting) .SetMethod("setFrameRate", &WebContents::SetFrameRate) .SetMethod("getFrameRate", &WebContents::GetFrameRate) #endif .SetMethod("invalidate", &WebContents::Invalidate) .SetMethod("setZoomLevel", &WebContents::SetZoomLevel) .SetMethod("getZoomLevel", &WebContents::GetZoomLevel) .SetMethod("setZoomFactor", &WebContents::SetZoomFactor) .SetMethod("getZoomFactor", &WebContents::GetZoomFactor) .SetMethod("getType", &WebContents::GetType) .SetMethod("_getPreloadPaths", &WebContents::GetPreloadPaths) .SetMethod("getLastWebPreferences", &WebContents::GetLastWebPreferences) .SetMethod("getOwnerBrowserWindow", &WebContents::GetOwnerBrowserWindow) .SetMethod("inspectServiceWorker", &WebContents::InspectServiceWorker) .SetMethod("inspectSharedWorker", &WebContents::InspectSharedWorker) .SetMethod("inspectSharedWorkerById", &WebContents::InspectSharedWorkerById) .SetMethod("getAllSharedWorkers", &WebContents::GetAllSharedWorkers) #if BUILDFLAG(ENABLE_PRINTING) .SetMethod("_print", &WebContents::Print) .SetMethod("_printToPDF", &WebContents::PrintToPDF) #endif .SetMethod("_setNextChildWebPreferences", &WebContents::SetNextChildWebPreferences) .SetMethod("addWorkSpace", &WebContents::AddWorkSpace) .SetMethod("removeWorkSpace", &WebContents::RemoveWorkSpace) .SetMethod("showDefinitionForSelection", &WebContents::ShowDefinitionForSelection) .SetMethod("copyImageAt", &WebContents::CopyImageAt) .SetMethod("capturePage", &WebContents::CapturePage) .SetMethod("setEmbedder", &WebContents::SetEmbedder) .SetMethod("setDevToolsWebContents", &WebContents::SetDevToolsWebContents) .SetMethod("getNativeView", &WebContents::GetNativeView) .SetMethod("incrementCapturerCount", &WebContents::IncrementCapturerCount) .SetMethod("decrementCapturerCount", &WebContents::DecrementCapturerCount) .SetMethod("isBeingCaptured", &WebContents::IsBeingCaptured) .SetMethod("setWebRTCIPHandlingPolicy", &WebContents::SetWebRTCIPHandlingPolicy) .SetMethod("getMediaSourceId", &WebContents::GetMediaSourceID) .SetMethod("getWebRTCIPHandlingPolicy", &WebContents::GetWebRTCIPHandlingPolicy) .SetMethod("takeHeapSnapshot", &WebContents::TakeHeapSnapshot) .SetMethod("setImageAnimationPolicy", &WebContents::SetImageAnimationPolicy) .SetMethod("_getProcessMemoryInfo", &WebContents::GetProcessMemoryInfo) .SetProperty("id", &WebContents::ID) .SetProperty("session", &WebContents::Session) .SetProperty("hostWebContents", &WebContents::HostWebContents) .SetProperty("devToolsWebContents", &WebContents::DevToolsWebContents) .SetProperty("debugger", &WebContents::Debugger) .SetProperty("mainFrame", &WebContents::MainFrame) .Build(); } const char* WebContents::GetTypeName() { return "WebContents"; } ElectronBrowserContext* WebContents::GetBrowserContext() const { return static_cast<ElectronBrowserContext*>( web_contents()->GetBrowserContext()); } // static gin::Handle<WebContents> WebContents::New( v8::Isolate* isolate, const gin_helper::Dictionary& options) { gin::Handle<WebContents> handle = gin::CreateHandle(isolate, new WebContents(isolate, options)); v8::TryCatch try_catch(isolate); gin_helper::CallMethod(isolate, handle.get(), "_init"); if (try_catch.HasCaught()) { node::errors::TriggerUncaughtException(isolate, try_catch); } return handle; } // static gin::Handle<WebContents> WebContents::CreateAndTake( v8::Isolate* isolate, std::unique_ptr<content::WebContents> web_contents, Type type) { gin::Handle<WebContents> handle = gin::CreateHandle( isolate, new WebContents(isolate, std::move(web_contents), type)); v8::TryCatch try_catch(isolate); gin_helper::CallMethod(isolate, handle.get(), "_init"); if (try_catch.HasCaught()) { node::errors::TriggerUncaughtException(isolate, try_catch); } return handle; } // static WebContents* WebContents::From(content::WebContents* web_contents) { if (!web_contents) return nullptr; auto* data = static_cast<UserDataLink*>( web_contents->GetUserData(kElectronApiWebContentsKey)); return data ? data->web_contents.get() : nullptr; } // static gin::Handle<WebContents> WebContents::FromOrCreate( v8::Isolate* isolate, content::WebContents* web_contents) { WebContents* api_web_contents = From(web_contents); if (!api_web_contents) { api_web_contents = new WebContents(isolate, web_contents); v8::TryCatch try_catch(isolate); gin_helper::CallMethod(isolate, api_web_contents, "_init"); if (try_catch.HasCaught()) { node::errors::TriggerUncaughtException(isolate, try_catch); } } return gin::CreateHandle(isolate, api_web_contents); } // static gin::Handle<WebContents> WebContents::CreateFromWebPreferences( v8::Isolate* isolate, const gin_helper::Dictionary& web_preferences) { // Check if webPreferences has |webContents| option. gin::Handle<WebContents> web_contents; if (web_preferences.GetHidden("webContents", &web_contents) && !web_contents.IsEmpty()) { // Set webPreferences from options if using an existing webContents. // These preferences will be used when the webContent launches new // render processes. auto* existing_preferences = WebContentsPreferences::From(web_contents->web_contents()); gin_helper::Dictionary web_preferences_dict; if (gin::ConvertFromV8(isolate, web_preferences.GetHandle(), &web_preferences_dict)) { existing_preferences->SetFromDictionary(web_preferences_dict); absl::optional<SkColor> color = existing_preferences->GetBackgroundColor(); web_contents->web_contents()->SetPageBaseBackgroundColor(color); // Because web preferences don't recognize transparency, // only set rwhv background color if a color exists auto* rwhv = web_contents->web_contents()->GetRenderWidgetHostView(); if (rwhv && color.has_value()) SetBackgroundColor(rwhv, color.value()); } } else { // Create one if not. web_contents = WebContents::New(isolate, web_preferences); } return web_contents; } // static WebContents* WebContents::FromID(int32_t id) { return GetAllWebContents().Lookup(id); } // static gin::WrapperInfo WebContents::kWrapperInfo = {gin::kEmbedderNativeGin}; } // namespace api } // namespace electron namespace { using electron::api::GetAllWebContents; using electron::api::WebContents; gin::Handle<WebContents> WebContentsFromID(v8::Isolate* isolate, int32_t id) { WebContents* contents = WebContents::FromID(id); return contents ? gin::CreateHandle(isolate, contents) : gin::Handle<WebContents>(); } gin::Handle<WebContents> WebContentsFromDevToolsTargetID( v8::Isolate* isolate, std::string target_id) { auto agent_host = content::DevToolsAgentHost::GetForId(target_id); WebContents* contents = agent_host ? WebContents::From(agent_host->GetWebContents()) : nullptr; return contents ? gin::CreateHandle(isolate, contents) : gin::Handle<WebContents>(); } std::vector<gin::Handle<WebContents>> GetAllWebContentsAsV8( v8::Isolate* isolate) { std::vector<gin::Handle<WebContents>> list; for (auto iter = base::IDMap<WebContents*>::iterator(&GetAllWebContents()); !iter.IsAtEnd(); iter.Advance()) { list.push_back(gin::CreateHandle(isolate, iter.GetCurrentValue())); } return list; } void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused, v8::Local<v8::Context> context, void* priv) { v8::Isolate* isolate = context->GetIsolate(); gin_helper::Dictionary dict(isolate, exports); dict.Set("WebContents", WebContents::GetConstructor(context)); dict.SetMethod("fromId", &WebContentsFromID); dict.SetMethod("fromDevToolsTargetId", &WebContentsFromDevToolsTargetID); dict.SetMethod("getAllWebContents", &GetAllWebContentsAsV8); } } // namespace NODE_LINKED_MODULE_CONTEXT_AWARE(electron_browser_web_contents, Initialize)
closed
electron/electron
https://github.com/electron/electron
33,880
[Bug]: Crash in WebFrameMain::Connect() -> GetInterface -> GetInterfaceByName
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17, 18 ### What operating system are you using? Windows ### Operating System Version Windows 10 19042.985 ### What arch are you using? x64 ### Last Known Working Electron version 14 ### Expected Behavior No crash ### Actual Behavior Electron crashes ![2022-04-21 10_07_53-Source Not Found (Debugging) - Microsoft Visual Studio](https://user-images.githubusercontent.com/10595986/164416772-c4800f31-d165-4639-88e3-23be25d8fe8c.png) This does not happen consistently but fairly often and can be reproduced in the app. I have not been able yet to make a small/standalone reproducable example ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/33880
https://github.com/electron/electron/pull/33919
17c8ec765bd40add42e22bd72a56317bfb9b2dbd
5ff94e7f2becc435e4e7c66e112686461b74e95b
2022-04-21T08:50:39Z
c++
2022-05-19T18:34:58Z
shell/browser/api/electron_api_web_frame_main.cc
// Copyright (c) 2020 Samuel Maddock <[email protected]>. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/api/electron_api_web_frame_main.h" #include <string> #include <unordered_map> #include <utility> #include <vector> #include "base/logging.h" #include "base/no_destructor.h" #include "content/browser/renderer_host/frame_tree_node.h" // nogncheck #include "content/public/browser/render_frame_host.h" #include "electron/shell/common/api/api.mojom.h" #include "gin/object_template_builder.h" #include "services/service_manager/public/cpp/interface_provider.h" #include "shell/browser/api/message_port.h" #include "shell/browser/browser.h" #include "shell/browser/javascript_environment.h" #include "shell/common/gin_converters/blink_converter.h" #include "shell/common/gin_converters/frame_converter.h" #include "shell/common/gin_converters/gurl_converter.h" #include "shell/common/gin_converters/value_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/gin_helper/error_thrower.h" #include "shell/common/gin_helper/object_template_builder.h" #include "shell/common/gin_helper/promise.h" #include "shell/common/node_includes.h" #include "shell/common/v8_value_serializer.h" namespace gin { template <> struct Converter<blink::mojom::PageVisibilityState> { static v8::Local<v8::Value> ToV8(v8::Isolate* isolate, blink::mojom::PageVisibilityState val) { std::string visibility; switch (val) { case blink::mojom::PageVisibilityState::kVisible: visibility = "visible"; break; case blink::mojom::PageVisibilityState::kHidden: case blink::mojom::PageVisibilityState::kHiddenButPainting: visibility = "hidden"; break; } return gin::ConvertToV8(isolate, visibility); } }; } // namespace gin namespace electron { namespace api { typedef std::unordered_map<int, WebFrameMain*> WebFrameMainIdMap; WebFrameMainIdMap& GetWebFrameMainMap() { static base::NoDestructor<WebFrameMainIdMap> instance; return *instance; } // static WebFrameMain* WebFrameMain::FromFrameTreeNodeId(int frame_tree_node_id) { WebFrameMainIdMap& frame_map = GetWebFrameMainMap(); auto iter = frame_map.find(frame_tree_node_id); auto* web_frame = iter == frame_map.end() ? nullptr : iter->second; return web_frame; } // static WebFrameMain* WebFrameMain::FromRenderFrameHost(content::RenderFrameHost* rfh) { return rfh ? FromFrameTreeNodeId(rfh->GetFrameTreeNodeId()) : nullptr; } gin::WrapperInfo WebFrameMain::kWrapperInfo = {gin::kEmbedderNativeGin}; WebFrameMain::WebFrameMain(content::RenderFrameHost* rfh) : frame_tree_node_id_(rfh->GetFrameTreeNodeId()), render_frame_(rfh) { GetWebFrameMainMap().emplace(frame_tree_node_id_, this); } WebFrameMain::~WebFrameMain() { Destroyed(); } void WebFrameMain::Destroyed() { MarkRenderFrameDisposed(); GetWebFrameMainMap().erase(frame_tree_node_id_); Unpin(); } void WebFrameMain::MarkRenderFrameDisposed() { render_frame_ = nullptr; render_frame_disposed_ = true; } void WebFrameMain::UpdateRenderFrameHost(content::RenderFrameHost* rfh) { // Should only be called when swapping frames. render_frame_disposed_ = false; render_frame_ = rfh; renderer_api_.reset(); } bool WebFrameMain::CheckRenderFrame() const { if (render_frame_disposed_) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); gin_helper::ErrorThrower(isolate).ThrowError( "Render frame was disposed before WebFrameMain could be accessed"); return false; } return true; } v8::Local<v8::Promise> WebFrameMain::ExecuteJavaScript( gin::Arguments* args, const std::u16string& code) { gin_helper::Promise<base::Value> promise(args->isolate()); v8::Local<v8::Promise> handle = promise.GetHandle(); // Optional userGesture parameter bool user_gesture; if (!args->PeekNext().IsEmpty()) { if (args->PeekNext()->IsBoolean()) { args->GetNext(&user_gesture); } else { args->ThrowTypeError("userGesture must be a boolean"); return handle; } } else { user_gesture = false; } if (render_frame_disposed_) { promise.RejectWithErrorMessage( "Render frame was disposed before WebFrameMain could be accessed"); return handle; } if (user_gesture) { auto* ftn = content::FrameTreeNode::From(render_frame_); ftn->UpdateUserActivationState( blink::mojom::UserActivationUpdateType::kNotifyActivation, blink::mojom::UserActivationNotificationType::kTest); } render_frame_->ExecuteJavaScriptForTests( code, base::BindOnce([](gin_helper::Promise<base::Value> promise, base::Value value) { promise.Resolve(value); }, std::move(promise))); return handle; } bool WebFrameMain::Reload() { if (!CheckRenderFrame()) return false; return render_frame_->Reload(); } void WebFrameMain::Send(v8::Isolate* isolate, bool internal, const std::string& channel, v8::Local<v8::Value> args) { blink::CloneableMessage message; if (!gin::ConvertFromV8(isolate, args, &message)) { isolate->ThrowException(v8::Exception::Error( gin::StringToV8(isolate, "Failed to serialize arguments"))); return; } if (!CheckRenderFrame()) return; GetRendererApi()->Message(internal, channel, std::move(message), 0 /* sender_id */); } const mojo::Remote<mojom::ElectronRenderer>& WebFrameMain::GetRendererApi() { if (!renderer_api_) { pending_receiver_ = renderer_api_.BindNewPipeAndPassReceiver(); if (render_frame_->IsRenderFrameCreated()) { render_frame_->GetRemoteInterfaces()->GetInterface( std::move(pending_receiver_)); } renderer_api_.set_disconnect_handler(base::BindOnce( &WebFrameMain::OnRendererConnectionError, weak_factory_.GetWeakPtr())); } return renderer_api_; } void WebFrameMain::OnRendererConnectionError() { renderer_api_.reset(); } void WebFrameMain::PostMessage(v8::Isolate* isolate, const std::string& channel, v8::Local<v8::Value> message_value, absl::optional<v8::Local<v8::Value>> transfer) { blink::TransferableMessage transferable_message; if (!electron::SerializeV8Value(isolate, message_value, &transferable_message)) { // SerializeV8Value sets an exception. return; } std::vector<gin::Handle<MessagePort>> wrapped_ports; if (transfer && !transfer.value()->IsUndefined()) { if (!gin::ConvertFromV8(isolate, *transfer, &wrapped_ports)) { isolate->ThrowException(v8::Exception::Error( gin::StringToV8(isolate, "Invalid value for transfer"))); return; } } bool threw_exception = false; transferable_message.ports = MessagePort::DisentanglePorts(isolate, wrapped_ports, &threw_exception); if (threw_exception) return; if (!CheckRenderFrame()) return; GetRendererApi()->ReceivePostMessage(channel, std::move(transferable_message)); } int WebFrameMain::FrameTreeNodeID() const { return frame_tree_node_id_; } std::string WebFrameMain::Name() const { if (!CheckRenderFrame()) return std::string(); return render_frame_->GetFrameName(); } base::ProcessId WebFrameMain::OSProcessID() const { if (!CheckRenderFrame()) return -1; base::ProcessHandle process_handle = render_frame_->GetProcess()->GetProcess().Handle(); return base::GetProcId(process_handle); } int WebFrameMain::ProcessID() const { if (!CheckRenderFrame()) return -1; return render_frame_->GetProcess()->GetID(); } int WebFrameMain::RoutingID() const { if (!CheckRenderFrame()) return -1; return render_frame_->GetRoutingID(); } GURL WebFrameMain::URL() const { if (!CheckRenderFrame()) return GURL::EmptyGURL(); return render_frame_->GetLastCommittedURL(); } blink::mojom::PageVisibilityState WebFrameMain::VisibilityState() const { if (!CheckRenderFrame()) return blink::mojom::PageVisibilityState::kHidden; return render_frame_->GetVisibilityState(); } content::RenderFrameHost* WebFrameMain::Top() const { if (!CheckRenderFrame()) return nullptr; return render_frame_->GetMainFrame(); } content::RenderFrameHost* WebFrameMain::Parent() const { if (!CheckRenderFrame()) return nullptr; return render_frame_->GetParent(); } std::vector<content::RenderFrameHost*> WebFrameMain::Frames() const { std::vector<content::RenderFrameHost*> frame_hosts; if (!CheckRenderFrame()) return frame_hosts; render_frame_->ForEachRenderFrameHost(base::BindRepeating( [](std::vector<content::RenderFrameHost*>* frame_hosts, content::RenderFrameHost* current_frame, content::RenderFrameHost* rfh) { if (rfh->GetParent() == current_frame) frame_hosts->push_back(rfh); }, &frame_hosts, render_frame_)); return frame_hosts; } std::vector<content::RenderFrameHost*> WebFrameMain::FramesInSubtree() const { std::vector<content::RenderFrameHost*> frame_hosts; if (!CheckRenderFrame()) return frame_hosts; render_frame_->ForEachRenderFrameHost(base::BindRepeating( [](std::vector<content::RenderFrameHost*>* frame_hosts, content::RenderFrameHost* rfh) { frame_hosts->push_back(rfh); }, &frame_hosts)); return frame_hosts; } void WebFrameMain::Connect() { if (pending_receiver_) { render_frame_->GetRemoteInterfaces()->GetInterface( std::move(pending_receiver_)); } } void WebFrameMain::DOMContentLoaded() { Emit("dom-ready"); } // static gin::Handle<WebFrameMain> WebFrameMain::New(v8::Isolate* isolate) { return gin::Handle<WebFrameMain>(); } // static gin::Handle<WebFrameMain> WebFrameMain::From(v8::Isolate* isolate, content::RenderFrameHost* rfh) { if (rfh == nullptr) return gin::Handle<WebFrameMain>(); auto* web_frame = FromRenderFrameHost(rfh); if (web_frame) return gin::CreateHandle(isolate, web_frame); auto handle = gin::CreateHandle(isolate, new WebFrameMain(rfh)); // Prevent garbage collection of frame until it has been deleted internally. handle->Pin(isolate); return handle; } // static v8::Local<v8::ObjectTemplate> WebFrameMain::FillObjectTemplate( v8::Isolate* isolate, v8::Local<v8::ObjectTemplate> templ) { return gin_helper::ObjectTemplateBuilder(isolate, templ) .SetMethod("executeJavaScript", &WebFrameMain::ExecuteJavaScript) .SetMethod("reload", &WebFrameMain::Reload) .SetMethod("_send", &WebFrameMain::Send) .SetMethod("_postMessage", &WebFrameMain::PostMessage) .SetProperty("frameTreeNodeId", &WebFrameMain::FrameTreeNodeID) .SetProperty("name", &WebFrameMain::Name) .SetProperty("osProcessId", &WebFrameMain::OSProcessID) .SetProperty("processId", &WebFrameMain::ProcessID) .SetProperty("routingId", &WebFrameMain::RoutingID) .SetProperty("url", &WebFrameMain::URL) .SetProperty("visibilityState", &WebFrameMain::VisibilityState) .SetProperty("top", &WebFrameMain::Top) .SetProperty("parent", &WebFrameMain::Parent) .SetProperty("frames", &WebFrameMain::Frames) .SetProperty("framesInSubtree", &WebFrameMain::FramesInSubtree) .Build(); } const char* WebFrameMain::GetTypeName() { return "WebFrameMain"; } } // namespace api } // namespace electron namespace { using electron::api::WebFrameMain; v8::Local<v8::Value> FromID(gin_helper::ErrorThrower thrower, int render_process_id, int render_frame_id) { if (!electron::Browser::Get()->is_ready()) { thrower.ThrowError("WebFrameMain is available only after app ready"); return v8::Null(thrower.isolate()); } auto* rfh = content::RenderFrameHost::FromID(render_process_id, render_frame_id); return WebFrameMain::From(thrower.isolate(), rfh).ToV8(); } 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("WebFrameMain", WebFrameMain::GetConstructor(context)); dict.SetMethod("fromId", &FromID); } } // namespace NODE_LINKED_MODULE_CONTEXT_AWARE(electron_browser_web_frame_main, Initialize)
closed
electron/electron
https://github.com/electron/electron
33,880
[Bug]: Crash in WebFrameMain::Connect() -> GetInterface -> GetInterfaceByName
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17, 18 ### What operating system are you using? Windows ### Operating System Version Windows 10 19042.985 ### What arch are you using? x64 ### Last Known Working Electron version 14 ### Expected Behavior No crash ### Actual Behavior Electron crashes ![2022-04-21 10_07_53-Source Not Found (Debugging) - Microsoft Visual Studio](https://user-images.githubusercontent.com/10595986/164416772-c4800f31-d165-4639-88e3-23be25d8fe8c.png) This does not happen consistently but fairly often and can be reproduced in the app. I have not been able yet to make a small/standalone reproducable example ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/33880
https://github.com/electron/electron/pull/33919
17c8ec765bd40add42e22bd72a56317bfb9b2dbd
5ff94e7f2becc435e4e7c66e112686461b74e95b
2022-04-21T08:50:39Z
c++
2022-05-19T18:34:58Z
shell/browser/api/electron_api_web_frame_main.h
// Copyright (c) 2020 Samuel Maddock <[email protected]>. // 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_WEB_FRAME_MAIN_H_ #define ELECTRON_SHELL_BROWSER_API_ELECTRON_API_WEB_FRAME_MAIN_H_ #include <string> #include <vector> #include "base/memory/weak_ptr.h" #include "base/process/process.h" #include "gin/handle.h" #include "gin/wrappable.h" #include "mojo/public/cpp/bindings/remote.h" #include "shell/browser/event_emitter_mixin.h" #include "shell/common/gin_helper/constructible.h" #include "shell/common/gin_helper/pinnable.h" #include "third_party/blink/public/mojom/page/page_visibility_state.mojom-forward.h" class GURL; namespace content { class RenderFrameHost; } namespace gin { class Arguments; } namespace electron { namespace api { class WebContents; // Bindings for accessing frames from the main process. class WebFrameMain : public gin::Wrappable<WebFrameMain>, public gin_helper::EventEmitterMixin<WebFrameMain>, public gin_helper::Pinnable<WebFrameMain>, public gin_helper::Constructible<WebFrameMain> { public: // Create a new WebFrameMain and return the V8 wrapper of it. static gin::Handle<WebFrameMain> New(v8::Isolate* isolate); static gin::Handle<WebFrameMain> From( v8::Isolate* isolate, content::RenderFrameHost* render_frame_host); static WebFrameMain* FromFrameTreeNodeId(int frame_tree_node_id); static WebFrameMain* FromRenderFrameHost( content::RenderFrameHost* render_frame_host); // gin::Wrappable static gin::WrapperInfo kWrapperInfo; static v8::Local<v8::ObjectTemplate> FillObjectTemplate( v8::Isolate*, v8::Local<v8::ObjectTemplate>); const char* GetTypeName() override; content::RenderFrameHost* render_frame_host() const { return render_frame_; } // disable copy WebFrameMain(const WebFrameMain&) = delete; WebFrameMain& operator=(const WebFrameMain&) = delete; protected: explicit WebFrameMain(content::RenderFrameHost* render_frame); ~WebFrameMain() override; private: friend class WebContents; // Called when FrameTreeNode is deleted. void Destroyed(); // Mark RenderFrameHost as disposed and to no longer access it. This can // happen when the WebFrameMain v8 handle is GC'd or when a FrameTreeNode // is removed. void MarkRenderFrameDisposed(); // Swap out the internal RFH when cross-origin navigation occurs. void UpdateRenderFrameHost(content::RenderFrameHost* rfh); const mojo::Remote<mojom::ElectronRenderer>& GetRendererApi(); // WebFrameMain can outlive its RenderFrameHost pointer so we need to check // whether its been disposed of prior to accessing it. bool CheckRenderFrame() const; v8::Local<v8::Promise> ExecuteJavaScript(gin::Arguments* args, const std::u16string& code); bool Reload(); void Send(v8::Isolate* isolate, bool internal, const std::string& channel, v8::Local<v8::Value> args); void PostMessage(v8::Isolate* isolate, const std::string& channel, v8::Local<v8::Value> message_value, absl::optional<v8::Local<v8::Value>> transfer); int FrameTreeNodeID() const; std::string Name() const; base::ProcessId OSProcessID() const; int ProcessID() const; int RoutingID() const; GURL URL() const; blink::mojom::PageVisibilityState VisibilityState() const; content::RenderFrameHost* Top() const; content::RenderFrameHost* Parent() const; std::vector<content::RenderFrameHost*> Frames() const; std::vector<content::RenderFrameHost*> FramesInSubtree() const; void OnRendererConnectionError(); void Connect(); void DOMContentLoaded(); mojo::Remote<mojom::ElectronRenderer> renderer_api_; mojo::PendingReceiver<mojom::ElectronRenderer> pending_receiver_; int frame_tree_node_id_; content::RenderFrameHost* render_frame_ = nullptr; // Whether the RenderFrameHost has been removed and that it should no longer // be accessed. bool render_frame_disposed_ = false; base::WeakPtrFactory<WebFrameMain> weak_factory_{this}; }; } // namespace api } // namespace electron #endif // ELECTRON_SHELL_BROWSER_API_ELECTRON_API_WEB_FRAME_MAIN_H_